diff --git a/Cargo.lock b/Cargo.lock index 65cc426291..9acedd45bd 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1009,6 +1009,15 @@ dependencies = [ "ruzstd", ] +[[package]] +name = "craft-cms" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=50b0ee7bf811e363b5f238382b5c77318cf33e46#50b0ee7bf811e363b5f238382b5c77318cf33e46" +dependencies = [ + "md-5", + "rayon", +] + [[package]] name = "craft-codepage" version = "0.1.0" @@ -6741,6 +6750,7 @@ dependencies = [ name = "vectorcraft-color" version = "0.24.1" dependencies = [ + "craft-cms", "kurbo 0.13.1", "moxcms", "proptest", diff --git a/Cargo.toml b/Cargo.toml index fea9cdda55..d60edf2af7 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,6 +11,7 @@ rust-version = "1.95" repository = "https://github.com/storytold/vectorcraft" [workspace.dependencies] +craft-cms = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" } craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46", default-features = false, features = ["interpret", "write"] } craft-print = { git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" } craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "50b0ee7bf811e363b5f238382b5c77318cf33e46" } diff --git a/ROADMAP.md b/ROADMAP.md index ef05d5dc9a..90a6100167 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -146,7 +146,9 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 2026-11-17: Curvature Circle tool (after the Circle tool in its group): a click on a path draws the circle that touches it there and bends as it bends, on the side it bends toward, or with Shift on the other side; a segment that is the usual cubic of a circular arc of 90° or less gives the arc's own radius, so a click on a circle draws that circle; the tool shows the circle, its center and its radius (with an asterisk for an arc's radius) until the click, or "Straight segment", "Cusp", "Corner" or "Circle too large" where it draws none (`shape.curvatureCircle`). One undo step per circle. A VectorCraft addition: headline numbers unchanged. - 2026-11-15: Circle through three points: three Shift-clicks with the Ellipse tool, or `shape.circleThroughPoints` with three points or three selected anchor points, draw the circle whose edge passes through them, with the current paint, in one undo step; after two points the tool previews the circle through the pointer, and two points that are the same or three on one line are refused with a message. Scores and estimates unchanged. - 2026-11-17: Circle tool (after the Ellipse tool in its group): two clicks or a drag draw the circle on that diameter, and a click followed by a drag from a second point to a third draws the circle through the three; Shift keeps the diameter at 45° steps, Alt rounds a two-point circle's diameter to the rulers' ticks at the current zoom, points snap to Smart Guides, and the tool shows the circle, its center, its radii and its diameter until the release, or "Circle too large" for points on one line or a circle past the canvas. `shape.circleThroughPoints` also takes two points or two selected anchor points as the ends of a diameter. One undo step per circle. A VectorCraft addition: headline numbers unchanged. +- 2026-11-17: Circle Tool Options (double-click the Circle tool): Show Center, Show Radii and Show Diameter switch what the tool shows while a circle is drawn, Color sets the color of the center cross and radius lines, Anchors at Standard Positions off puts the circle's anchors at the points it was drawn through (`shape.circleThroughPoints {anchors: "points"}`), and Third Point by Dragging off draws a three-point circle with three clicks and a two-point circle with a double-click on the second point. A VectorCraft addition: headline numbers unchanged. - 2026-11-19: Quick Pen tool, in the Pen tool's group (Alt+P, Option+P on macOS): clicks or drags add straight lines, continuous arcs or sharp-corner arcs; Alt tapped on its own switches the action, C flips the last arc, `[` and `]` size it, a click on the first point closes the path and a click on an open end continues it (`path.quickPen`, part of #2660). Headline numbers unchanged. +- 2026-11-19: Quick Pen toolbar on the canvas while the tool is active: Straight Line, Continuous Arc and Sharp Corner Arc, Flip Arc, and More Options with Hide Toolbar, Pin Toolbar Position and Reset Toolbar Position; it follows the drawing beside the path's last point and its handle drags it (`tool.quickPen.flipArc`, `window.quickPenToolbar`, Window › Quick Pen Toolbar; part of #2660). Headline numbers unchanged. - 2026-10-31: Pattern libraries: Window › Swatch Libraries › Patterns and the Swatches panel's library menu open Geometric Patterns, a built-in library of eleven pattern swatches (dots, stripes, checks, a grid and shapes); clicking one adds its pattern and swatch to the document, once, and applies it to the active fill or stroke (`swatch.library.add`). - 2026-11-11: Pattern libraries: Patterns › Grit Textures, a second built-in pattern library, holds eight seamless black textures (Fine Grain, Coarse Grit, Sand, Speckle, Stipple, Scratches, Sparse Flecks and Dense Flecks) on tiles of 18 to 36 pt, each drawn the same way every time; marks that reach past a tile edge continue on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged. - 2026-11-11: Pattern libraries: Patterns › Optical Effects, a third built-in pattern library, of VectorCraft's own designs, holds eight black wave, moiré and op-art tiles (Sine Bands, Ripple Lines, Interference Rings, Offset Rings, Warped Checks, Pinched Stripes, Chevron Pulse and Radiating Lenses) of 32 to 48 pt, each drawn the same way every time; each tile is one period of its design, and art that reaches past a tile edge continues on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged. diff --git a/apps/vectorcraft-cli/src/main.rs b/apps/vectorcraft-cli/src/main.rs index 5dfe7386f6..533074b9b5 100644 --- a/apps/vectorcraft-cli/src/main.rs +++ b/apps/vectorcraft-cli/src/main.rs @@ -253,6 +253,7 @@ fn with_stores(mut h: Headless) -> Headless { prefs_dir::attach_pdf_preset_store(&mut h.session); prefs_dir::attach_custom_dictionary(&mut h.session); prefs_dir::attach_arrowheads(&mut h.session); + prefs_dir::attach_bevels(&mut h.session); h } diff --git a/apps/vectorcraft/src/main.rs b/apps/vectorcraft/src/main.rs index aa62211500..29cb56bdfa 100644 --- a/apps/vectorcraft/src/main.rs +++ b/apps/vectorcraft/src/main.rs @@ -567,6 +567,8 @@ fn main() -> std::process::ExitCode { prefs_dir::attach_custom_dictionary(&mut app.session); // The custom arrowheads, kept in their own file next to the preferences. prefs_dir::attach_arrowheads(&mut app.session); + // The custom bevels, kept in their own file next to the preferences. + prefs_dir::attach_bevels(&mut app.session); // Fit the window to its monitor, or put it back where it was (still hidden). let winit_window = cc.winit_window().cloned(); if let Some(w) = &winit_window { diff --git a/apps/vectorcraft/src/prefs_dir.rs b/apps/vectorcraft/src/prefs_dir.rs index f863a6eba3..492e2ea7bf 100644 --- a/apps/vectorcraft/src/prefs_dir.rs +++ b/apps/vectorcraft/src/prefs_dir.rs @@ -122,6 +122,14 @@ pub fn attach_arrowheads(session: &mut vectorcraft_engine::Session) { } } +/// Keep the custom bevels (`threeD.bevels.edit`) in the `Bevels.vectorcraft` file next to the +/// settings, and list the bevels it holds. +pub fn attach_bevels(session: &mut vectorcraft_engine::Session) { + if let Some(path) = store_dir(vectorcraft_engine::cmd::bevels::FILE_NAME) { + session.attach_bevels_file(path.to_string_lossy().to_string()); + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/cad/src/scene.rs b/crates/cad/src/scene.rs index 3fc68180d0..700632313e 100644 --- a/crates/cad/src/scene.rs +++ b/crates/cad/src/scene.rs @@ -34,6 +34,7 @@ const WIDE_LINES: &str = "lines wider than 2.11 mm (the widest lineweight) are written at 2.11 mm: Alter Paths for Appearance writes their true width"; const STROKE_EXTRAS: &str = "stroke alignment, width profiles, arrowheads and brushes are left out (Maximize Editability writes strokes as lines)"; const CLIPPING: &str = "clipping masks are not applied: the art they clip is written whole"; +const DISTORTED_IMAGES: &str = "images changed by Perspective Distort or Free Distort are written as the nearest parallelogram"; const TYPE_ITEMS: &str = "fills and strokes added to whole type objects are left out of text entities (outline the text to keep them)"; /// The warning for an image left out because it can't be decoded: the note raster exports give /// (`vectorcraft-engine`'s `rasterfx::undecoded_warning`). @@ -671,7 +672,18 @@ impl<'a> Scene<'a> { self.shape(n, &bp, *rule); } NodeKind::Text(t) => self.text(n, t), - NodeKind::Image(im) => self.image(&self.doc.shown_image(n, im)), + NodeKind::Image(im) => match vectorcraft_doc::image_quad::nearest_affine(n) { + // DXF clips nothing, so a distorted image is written at the affine placement nearest + // its corners, with the warning once it is written. + Some(xf) => { + if self.image(&ImageObject { xf, ..self.doc.shown_image(n, im).into_owned() }) { + self.warn(DISTORTED_IMAGES); + } + } + None => { + self.image(&self.doc.shown_image(n, im)); + } + }, NodeKind::SymbolInstance { symbol, xf } => { let doc = self.doc; if self.symbol_nodes >= vectorcraft_doc::MAX_SYMBOL_NODES { @@ -1325,18 +1337,19 @@ impl<'a> Scene<'a> { name } - /// A placed image, linked to its file (written once per image). - fn image(&mut self, im: &ImageObject) { + /// A placed image, linked to its file (written once per image). False when no `IMAGE` entity is + /// written. + fn image(&mut self, im: &ImageObject) -> bool { if !self.o.version.handles() { self.warn(NO_IMAGES); - return; + return false; } if !self.o.include_images { self.note_setting(IMAGES_OFF); - return; + return false; } - let Some(i) = self.image_def(im) else { return }; - let Some((dw, dh)) = self.images.get(i).map(|d| (f64::from(d.size.0), f64::from(d.size.1))) else { return }; + let Some(i) = self.image_def(im) else { return false }; + let Some((dw, dh)) = self.images.get(i).map(|d| (f64::from(d.size.0), f64::from(d.size.1))) else { return false }; let (w, h) = (f64::from(im.width.max(1)), f64::from(im.height.max(1))); let map = self.to_dxf * im.xf; let lin = |v: kurbo::Vec2| (map * v.to_point()) - (map * Point::ZERO); @@ -1349,7 +1362,7 @@ impl<'a> Scene<'a> { let at = map * Point::new(0.0, h); let handle = self.handle(); let reactor = self.handle(); - let Some(def) = self.images.get_mut(i) else { return }; + let Some(def) = self.images.get_mut(i) else { return false }; def.reactors.push((reactor, handle)); let def = def.handle; let layer = self.layer.clone(); @@ -1375,6 +1388,7 @@ impl<'a> Scene<'a> { if self.o.version >= crate::DxfVersion::R2010 { self.e.int(290, 0); } + true } /// The image file for image `im`, encoded once in the chosen format (`None`: left out). diff --git a/crates/cad/src/tests.rs b/crates/cad/src/tests.rs index 797223b688..35a1e8c45d 100644 --- a/crates/cad/src/tests.rs +++ b/crates/cad/src/tests.rs @@ -984,6 +984,37 @@ fn images_can_be_left_out_with_their_files() { assert!(r12.warnings.iter().any(|w| w.contains("no images")) && r12.setting_notes.is_empty()); } +/// DXF does not clip, so an image changed by Perspective Distort is written as one image at the +/// placement nearest its corners, with a warning; an undistorted image gets no warning. +#[test] +fn a_distorted_image_is_written_as_its_nearest_parallelogram_with_a_warning() { + let mut d = image_and_fill_doc(Paint::None); + let warned = |o: &DxfOutput| o.warnings.iter().any(|w| w.contains("Perspective Distort or Free Distort")); + assert!(!warned(&export(&d, &opts(&d)).unwrap())); + let id = d.layers[0].children().unwrap()[1].id; + let q = [(12.0, 20.0), (28.0, 20.0), (30.0, 30.0), (10.0, 30.0)].map(|(x, y)| Point::new(x, y)); + d.node_mut(id).unwrap().set_image_corners(q).unwrap(); + let out = export(&d, &opts(&d)).unwrap(); + assert!(warned(&out), "{:?}", out.warnings); + assert_eq!(kinds(&out).iter().filter(|k| *k == "IMAGE").count(), 1, "{:?}", kinds(&out)); + // Placed as an undistorted image with the nearest affine placement as its transform would be. + let near = vectorcraft_doc::image_quad::nearest_affine(d.node(id).unwrap()).unwrap(); + let mut plain = d.clone(); + let n = plain.node_mut(id).unwrap(); + n.extras_mut().image_quad = None; + if let NodeKind::Image(im) = &mut n.kind { + im.xf = near; + } + let placement = |o: &DxfOutput| { + let e = entities(o).into_iter().find(|e| kind(e) == "IMAGE").expect("an IMAGE"); + [10, 20, 11, 21, 12, 22].map(|c| all(&e, c)) + }; + assert_eq!(placement(&out), placement(&export(&plain, &opts(&plain)).unwrap())); + // With images left out, no IMAGE is written and the distortion warning does not appear. + let left_out = export(&d, &DxfOptions { include_images: false, ..opts(&d) }).unwrap(); + assert!(!warned(&left_out), "{:?}", left_out.warnings); +} + #[test] fn images_and_hatches_are_left_out_independently_and_the_cnc_preset_leaves_out_both() { let d = image_and_fill_doc(Paint::solid(Color::rgb(1.0, 0.0, 0.0))); diff --git a/crates/color/Cargo.toml b/crates/color/Cargo.toml index a007ede39f..1273b5d0ad 100644 --- a/crates/color/Cargo.toml +++ b/crates/color/Cargo.toml @@ -9,6 +9,7 @@ description = "VectorCraft color" workspace = true [dependencies] +craft-cms = { workspace = true } kurbo = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } diff --git a/crates/color/src/lib.rs b/crates/color/src/lib.rs index fa8cd564f2..c3d74615ae 100644 --- a/crates/color/src/lib.rs +++ b/crates/color/src/lib.rs @@ -10,6 +10,7 @@ pub mod freeform; pub mod gradient; pub mod harmony; pub mod libraries; +pub mod oklab; pub mod palette_io; pub mod recolor; pub mod swatch; @@ -340,6 +341,49 @@ pub fn hsb_to_rgb([h, s, v]: [f32; 3]) -> [f32; 3] { [r + m, g + m, b + m] } +/// HSL (hue in degrees 0..360, saturation and lightness 0..1) of RGB numbers 0..1, with no color +/// conversion, as CSS Color 4 converts sRGB to HSL +/// (). The hue is 0 while the saturation is +/// powerless, and a color outside 0..1 that gives a negative saturation turns its hue by 180°. As in +/// the specification's conversion, a lightness of 0.00001 or less, a lightness less than 0.00001 +/// below 1, or a saturation of 0.00001 or less reads as a gray. +pub fn rgb_to_hsl([r, g, b]: [f32; 3]) -> [f32; 3] { + const EPSILON: f32 = 1e-5; + let max = r.max(g).max(b); + let min = r.min(g).min(b); + let d = max - min; + let l = (max + min) / 2.0; + if d <= 0.0 { + return [0.0, 0.0, l]; + } + let mut s = if l.abs() <= EPSILON || (1.0 - l).abs() < EPSILON { 0.0 } else { (max - l) / l.min(1.0 - l) }; + let mut h = rgb_to_hsb([r, g, b])[0]; + if s < 0.0 { + h += 180.0; + s = -s; + } + if s <= EPSILON { + return [0.0, 0.0, l]; + } + let h = h.rem_euclid(360.0); + [if h >= 360.0 { 0.0 } else { h }, s, l] +} + +/// RGB numbers 0..1 of HSL `[h, s, l]` (hue in degrees, saturation and lightness 0..1), as CSS +/// Color 4 converts HSL to sRGB (): the inverse of +/// [`rgb_to_hsl`]. A hue outside 0..360 wraps into that range before the conversion, so -120° +/// gives the color of 240° and a hue of 10,000,000,000° the color of 280°. The specification's +/// sample code uses JavaScript's remainder operator and gives a different color for a negative hue. +pub fn hsl_to_rgb([h, s, l]: [f32; 3]) -> [f32; 3] { + let h = h.rem_euclid(360.0); + let a = s * l.min(1.0 - l); + let f = |n: f32| { + let k = (n + h / 30.0).rem_euclid(12.0); + l - a * (k - 3.0).min(9.0 - k).clamp(-1.0, 1.0) + }; + [f(0.0), f(8.0), f(4.0)] +} + /// `new` expressed in the colour model of `orig` ([`Color::in_model`]): results of colour operations /// (harmonies, blends, inversions, recolouring) keep the model of the colour they came from. pub fn keep_model(orig: Color, new: Color) -> Color { @@ -499,6 +543,59 @@ mod tests { } } + /// The HSL examples of CSS Color 4, section 7 (), + /// the first six rows, and two hues outside 0..360 that wrap into that range. + #[test] + fn hsl_follows_css_color_4() { + for (hsl, hex) in [ + ([0.0, 1.0, 0.5], "#ff0000"), + ([120.0, 1.0, 0.5], "#00ff00"), + ([120.0, 1.0, 0.25], "#008000"), + ([120.0, 1.0, 0.75], "#80ff80"), + ([240.0, 1.0, 0.5], "#0000ff"), + ([60.0, 1.0, 0.5], "#ffff00"), + ([360.0, 1.0, 0.5], "#ff0000"), + ([-120.0, 1.0, 0.5], "#0000ff"), + ] { + let [r, g, b] = hsl_to_rgb(hsl); + assert_eq!(Color::rgb(r, g, b).to_hex(), hex, "{hsl:?}"); + } + let [h, s, l] = rgb_to_hsl([1.0, 0.5, 0.0]); + assert!((h - 30.0).abs() < 1e-4 && (s - 1.0).abs() < 1e-6 && (l - 0.5).abs() < 1e-6, "{h} {s} {l}"); + let [h, s, l] = rgb_to_hsl(Color::rgb8(255, 128, 0).to_rgb_uncalibrated()); + assert!((h - 30.0).abs() < 0.2 && (s - 1.0).abs() < 1e-6 && (l - 0.5).abs() < 1e-3, "{h} {s} {l}"); + // A gray has no hue: the hue is 0 and the saturation 0, at any lightness. + for v in [0.0, 0.25, 0.5, 1.0] { + assert_eq!(rgb_to_hsl([v, v, v]), [0.0, 0.0, v]); + } + // Black and white keep any hue and saturation they are given. + assert_eq!(hsl_to_rgb([200.0, 0.7, 0.0]), [0.0, 0.0, 0.0]); + assert_eq!(hsl_to_rgb([200.0, 0.7, 1.0]), [1.0, 1.0, 1.0]); + // A color past the gamut that gives a negative saturation turns its hue by 180°. + let [h, s, _] = rgb_to_hsl([1.2, 1.5, 1.4]); + assert!(s > 0.0 && (h - (160.0 + 180.0)).abs() < 1e-3, "{h} {s}"); + // A huge hue wraps before the channels are worked out: 10,000,000,000° is 280°. + let (huge, wrapped) = (hsl_to_rgb([10_000_000_000.0, 1.0, 0.5]), hsl_to_rgb([280.0, 1.0, 0.5])); + assert!((0..3).all(|i| (huge[i] - wrapped[i]).abs() < 1e-6), "{huge:?} {wrapped:?}"); + } + + /// The 216 web colors go to HSL and back to the same 8-bit color. + #[test] + fn hsl_roundtrip() { + let steps = [0x00, 0x33, 0x66, 0x99, 0xcc, 0xff]; + for r in steps { + for g in steps { + for b in steps { + let c = Color::rgb8(r, g, b); + let [h, s, l] = rgb_to_hsl(c.to_rgb_uncalibrated()); + assert!((0.0..360.0).contains(&h) && (0.0..=1.0).contains(&s) && (0.0..=1.0).contains(&l), "{}", c.to_hex()); + let back = hsl_to_rgb([h, s, l]).map(|v| (v * 255.0).round() as u8); + assert_eq!(back, [r, g, b], "{}", c.to_hex()); + } + } + } + } + #[test] fn cmyk_conversions() { assert_eq!(Color::cmyk(0.0, 0.0, 0.0, 1.0).to_rgb_uncalibrated(), [0.0, 0.0, 0.0]); diff --git a/crates/color/src/libraries.rs b/crates/color/src/libraries.rs index 5fc952a061..c2946d92a2 100644 --- a/crates/color/src/libraries.rs +++ b/crates/color/src/libraries.rs @@ -99,18 +99,24 @@ pub fn builtin_library(id: &str) -> Option> { // ---------- colour construction ---------- -/// sRGB (0..=1, gamma encoded) of OKLab `(l, a, b)`, unclamped. +/// sRGB (0..=1, gamma encoded) of OKLab `(l, a, b)`, unclamped. A linear channel below +/// −0.0031308 is encoded with the curve's sign turned, as CSS Color 4's extended sRGB does +/// (). pub(crate) fn oklab_to_srgb(l: f64, a: f64, b: f64) -> [f64; 3] { + oklab_to_linear_srgb(l, a, b).map(|v| if v.abs() <= 0.003_130_8 { 12.92 * v } else { v.signum() * (1.055 * v.abs().powf(1.0 / 2.4) - 0.055) }) +} + +/// Linear sRGB of OKLab `(l, a, b)`, unclamped. +pub(crate) fn oklab_to_linear_srgb(l: f64, a: f64, b: f64) -> [f64; 3] { let l_ = l + 0.396_337_777_4 * a + 0.215_803_757_3 * b; let m_ = l - 0.105_561_345_8 * a - 0.063_854_172_8 * b; let s_ = l - 0.089_484_177_5 * a - 1.291_485_548_0 * b; let (l3, m3, s3) = (l_ * l_ * l_, m_ * m_ * m_, s_ * s_ * s_); - let lin = [ + [ 4.076_741_662_1 * l3 - 3.307_711_591_3 * m3 + 0.230_969_929_2 * s3, -1.268_438_004_6 * l3 + 2.609_757_401_1 * m3 - 0.341_319_396_5 * s3, -0.004_196_086_3 * l3 - 0.703_418_614_7 * m3 + 1.707_614_701_0 * s3, - ]; - lin.map(|v| if v <= 0.003_130_8 { 12.92 * v } else { 1.055 * v.powf(1.0 / 2.4) - 0.055 }) + ] } /// OKLab `[l, a, b]` of a colour's display RGB. @@ -118,11 +124,13 @@ pub fn to_oklab(c: &Color) -> [f64; 3] { srgb_to_oklab(c.to_rgb_uncalibrated()) } -/// OKLab `[l, a, b]` of sRGB `rgb` (0..=1, gamma encoded). +/// OKLab `[l, a, b]` of sRGB `rgb` (0..=1, gamma encoded). A channel below −0.04045 is decoded +/// with the curve's sign turned, as CSS Color 4's extended sRGB does +/// (). pub(crate) fn srgb_to_oklab(rgb: [f32; 3]) -> [f64; 3] { let [r, g, b] = rgb.map(|v| { let v = f64::from(v); - if v <= 0.040_45 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) } + if v.abs() <= 0.040_45 { v / 12.92 } else { v.signum() * ((v.abs() + 0.055) / 1.055).powf(2.4) } }); let l = (0.412_221_470_8 * r + 0.536_332_536_3 * g + 0.051_445_992_9 * b).cbrt(); let m = (0.211_903_498_2 * r + 0.680_699_545_1 * g + 0.107_396_956_6 * b).cbrt(); diff --git a/crates/color/src/oklab.rs b/crates/color/src/oklab.rs new file mode 100644 index 0000000000..31500d1ac5 --- /dev/null +++ b/crates/color/src/oklab.rs @@ -0,0 +1,266 @@ +//! OKLCH, the polar form of Oklab, as CSS Color 4 defines it +//! (): lightness L from 0 to 1, chroma +//! C (CSS reads 100% as 0.4) and hue H in degrees from the positive `a` axis. The conversions take +//! and give gamma-encoded sRGB through the Oklab matrices of [`crate::libraries`]. + +use crate::libraries::{oklab_to_linear_srgb, oklab_to_srgb, srgb_to_oklab}; + +/// The chroma CSS reads as 100%. +pub const CHROMA_FULL: f64 = 0.4; + +/// Chroma at or below which the hue is powerless (CSS Color 4's ε); [`to_oklch`] gives hue 0 there. +pub const POWERLESS_CHROMA: f64 = 0.000_004; + +/// How far outside 0..=1 an sRGB component may be and still count as inside the gamut. +const GAMUT_SLACK: f64 = 1e-4; + +/// OKLCH `[l, c, h°]` of sRGB `rgb` (gamma encoded). Values outside 0..=1 are converted as they +/// are. The hue is in 0..360, and 0 while the chroma is powerless. +pub fn to_oklch(rgb: [f32; 3]) -> [f64; 3] { + let [l, a, b] = srgb_to_oklab(rgb); + let c = a.hypot(b); + if c <= POWERLESS_CHROMA { + return [l, 0.0, 0.0]; + } + [l, c, b.atan2(a).to_degrees().rem_euclid(360.0)] +} + +/// sRGB (gamma encoded) of OKLCH `(l, c, h°)`, unclamped. +pub fn oklch_to_srgb(l: f64, c: f64, h: f64) -> [f64; 3] { + let (sin, cos) = h.to_radians().sin_cos(); + oklab_to_srgb(l, c * cos, c * sin) +} + +/// Whether sRGB `rgb` lies inside the sRGB gamut. +pub fn in_srgb(rgb: [f64; 3]) -> bool { + rgb.iter().all(|v| (-GAMUT_SLACK..=1.0 + GAMUT_SLACK).contains(v)) +} + +/// The largest chroma sRGB holds at lightness `l` and hue `h°`: 0 at or outside black and white. +pub fn max_chroma(l: f64, h: f64) -> f64 { + largest_fitting_chroma(l, h, f64::INFINITY) +} + +/// The largest chroma no more than `limit` that sRGB holds at lightness `l` and hue `h°`: 0 at or +/// outside black and white. +/// +/// The chromas sRGB holds along the ray can come in several stretches: at the lightness and hue of +/// blue the ray leaves sRGB at a chroma of about 0.266 and comes back at blue itself, about 0.313, +/// and near black the gamut slack opens stretches of its own. Each linear sRGB channel is a cubic +/// in the chroma, so every stretch ends where a channel's cubic meets a bound of the gamut. The +/// search finds each such chroma between the cubic's turning points and takes the largest one that +/// fits. +fn largest_fitting_chroma(l: f64, h: f64, limit: f64) -> f64 { + if !(l > 0.0 && l < 1.0) || !h.is_finite() { + return 0.0; + } + let top = limit.min(0.5); + if top <= 0.0 { + return 0.0; + } + let fits = |c: f64| in_srgb(oklch_to_srgb(l, c, h)); + if fits(top) { + return top; + } + let (sin, cos) = h.to_radians().sin_cos(); + let lin = |c: f64| oklab_to_linear_srgb(l, c * cos, c * sin); + // The linear channels at chromas 0, s, 2s and 3s give each cubic's coefficients in t = c / s. + let s = top / 3.0; + let y = [lin(0.0), lin(s), lin(2.0 * s), lin(3.0 * s)]; + let bounds = [-GAMUT_SLACK / 12.92, ((1.0 + GAMUT_SLACK + 0.055) / 1.055).powf(2.4)]; + let mut ends = vec![0.0]; + for ch in 0..3 { + let [y0, y1, y2, y3] = [y[0][ch], y[1][ch], y[2][ch], y[3][ch]]; + let (d1, d2, d3) = (y1 - y0, y2 - 2.0 * y1 + y0, y3 - 3.0 * y2 + 3.0 * y1 - y0); + let k = [y0, d1 - d2 / 2.0 + d3 / 3.0, d2 / 2.0 - d3 / 2.0, d3 / 6.0]; + let p = |t: f64| ((k[3] * t + k[2]) * t + k[1]) * t + k[0]; + // The cubic rises or falls on each stretch between its turning points. + let mut cuts = vec![0.0, 3.0]; + cuts.extend(turning_points(3.0 * k[3], 2.0 * k[2], k[1]).into_iter().filter(|t| *t > 0.0 && *t < 3.0)); + cuts.sort_by(f64::total_cmp); + ends.extend(cuts.iter().map(|t| t * s)); + for w in cuts.windows(2) { + for bound in bounds { + let (mut a, mut b) = (w[0], w[1]); + let fa = p(a) - bound; + if fa * (p(b) - bound) > 0.0 { + continue; + } + for _ in 0..60 { + let mid = (a + b) / 2.0; + if (p(mid) - bound) * fa > 0.0 { a = mid } else { b = mid } + } + ends.extend([a * s, b * s]); + } + } + } + ends.sort_by(|a, b| b.total_cmp(a)); + ends.into_iter().flat_map(|c| [c, c - 1e-9]).find(|c| (0.0..=top).contains(c) && fits(*c)).unwrap_or(0.0) +} + +/// The real roots of `a t² + b t + c`. +fn turning_points(a: f64, b: f64, c: f64) -> Vec { + if a.abs() < 1e-15 { + return if b.abs() < 1e-15 { Vec::new() } else { vec![-c / b] }; + } + let disc = b * b - 4.0 * a * c; + if disc < 0.0 { + return Vec::new(); + } + let r = disc.sqrt(); + vec![(-b - r) / (2.0 * a), (-b + r) / (2.0 * a)] +} + +/// The sRGB color (gamma encoded, 0..=1) of OKLCH `(l, c, h°)`, and whether its chroma was lowered: +/// a color outside sRGB keeps its lightness and hue and takes the largest chroma below it that +/// fits. Lightness is clamped to 0..=1 and chroma to 0 or more. +pub fn from_oklch(l: f64, c: f64, h: f64) -> ([f32; 3], bool) { + let l = if l.is_nan() { 0.0 } else { l.clamp(0.0, 1.0) }; + let c = if c.is_nan() { 0.0 } else { c.max(0.0) }; + let h = if h.is_finite() { h } else { 0.0 }; + let exact = oklch_to_srgb(l, c, h); + let (rgb, lowered) = if in_srgb(exact) { (exact, false) } else { (oklch_to_srgb(l, largest_fitting_chroma(l, h, c), h), true) }; + (rgb.map(|v| v.clamp(0.0, 1.0) as f32), lowered) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn eight(rgb: [f32; 3]) -> [u8; 3] { + rgb.map(|v| (v * 255.0).round() as u8) + } + + #[test] + fn red_has_the_oklch_of_the_oklab_matrices_and_converts_back() { + let [l, c, h] = to_oklch([1.0, 0.0, 0.0]); + assert!((l - 0.6280).abs() < 5e-5 && (c - 0.2577).abs() < 5e-5 && (h - 29.23).abs() < 5e-3, "{l} {c} {h}"); + let (rgb, lowered) = from_oklch(l, c, h); + assert_eq!((eight(rgb), lowered), ([255, 0, 0], false)); + } + + /// CSS Color 4's examples convert to the hue its oklab() and oklch() forms give. + #[test] + fn the_polar_form_matches_the_css_examples() { + for ([l, a, b], [cl, cc, ch]) in + [([0.40101, 0.1147, 0.0453], [0.40101, 0.12332, 21.555]), ([0.65125, -0.0320, 0.1274], [0.65125, 0.13138, 104.097])] + { + let rgb = oklab_to_srgb(l, a, b).map(|v| v as f32); + let [ol, oc, oh] = to_oklch(rgb); + assert!((ol - cl).abs() < 1e-4 && (oc - cc).abs() < 1e-4 && (oh - ch).abs() < 0.05, "{ol} {oc} {oh}"); + } + } + + #[test] + fn the_216_web_colors_round_trip() { + let steps = [0u8, 0x33, 0x66, 0x99, 0xcc, 0xff]; + for r in steps { + for g in steps { + for b in steps { + let rgb = [r, g, b].map(|v| f32::from(v) / 255.0); + let [l, c, h] = to_oklch(rgb); + assert_eq!(eight(from_oklch(l, c, h).0), [r, g, b], "{l} {c} {h}"); + } + } + } + } + + #[test] + fn grays_have_no_chroma_and_hue_zero() { + for v in [0.0, 0.5, 1.0] { + let [_, c, h] = to_oklch([v, v, v]); + assert!(c <= POWERLESS_CHROMA && h == 0.0, "{c} {h}"); + } + } + + /// A chroma past the gamut gives a color inside it with the same lightness and hue, and says so. + #[test] + fn a_chroma_past_the_gamut_is_lowered_keeping_lightness_and_hue() { + let (l, h) = (0.7, 150.0); + let max = max_chroma(l, h); + assert!(max > 0.05 && max < CHROMA_FULL, "{max}"); + assert!(in_srgb(oklch_to_srgb(l, max, h)) && !in_srgb(oklch_to_srgb(l, max + 1e-3, h))); + let (rgb, lowered) = from_oklch(l, CHROMA_FULL, h); + assert!(lowered); + let [ol, oc, oh] = to_oklch(rgb); + assert!((ol - l).abs() < 2e-3 && (oh - h).abs() < 1.0 && (oc - max).abs() < 2e-3, "{ol} {oc} {oh}"); + assert!(!from_oklch(l, max * 0.5, h).1); + } + + /// At the lightness and hue of blue the ray leaves sRGB and comes back at blue itself, so the + /// largest chroma is blue's, and a chroma past it gives blue. + #[test] + fn the_largest_chroma_at_blues_hue_is_blues() { + let [l, c, h] = to_oklch([0.0, 0.0, 1.0]); + let max = max_chroma(l, h); + assert!((max - c).abs() < 1e-4 && in_srgb(oklch_to_srgb(l, max, h)), "{max} {c}"); + let (rgb, lowered) = from_oklch(l, CHROMA_FULL, h); + assert_eq!((eight(rgb), lowered), ([0, 0, 255], true)); + // A chroma between the two stretches takes the end of the first one, inside sRGB. + let (rgb, lowered) = from_oklch(l, 0.29, h); + let [_, gc, _] = to_oklch(rgb); + assert!(lowered && gc < 0.27 && in_srgb(oklch_to_srgb(l, gc, h)), "{gc}"); + // A hue just past blue's: a narrow second stretch ends just below the line from black to blue. + let (l, h) = (0.44, 264.06); + let max = max_chroma(l, h); + assert!(max > 0.304 && max < 0.305 && in_srgb(oklch_to_srgb(l, max, h)), "{max}"); + let [_, got, _] = to_oklch(from_oklch(l, 0.35, h).0); + assert!(got > 0.303, "{got}"); + // A darker blue on the line from black to blue. + let [l, c, h] = to_oklch([0.0, 0.0, 0.25]); + assert!((max_chroma(l, h) - c).abs() < 1e-4, "{} {c}", max_chroma(l, h)); + } + + /// Just below blue's lightness the line from black to blue passes a chroma of 0.3125, where a + /// search from 0 to 0.5 lands first. A chroma asked for below that line still gives a color + /// inside sRGB with the lightness and hue asked for. + #[test] + fn a_chroma_below_the_line_from_black_to_blue_stays_inside_srgb() { + let [bl, bc, h] = to_oklch([0.0, 0.0, 1.0]); + let l = bl * 0.3125 / bc; + let (rgb, lowered) = from_oklch(l, 0.29, h); + let [gl, gc, gh] = to_oklch(rgb); + assert!(lowered && gc < 0.29 && in_srgb(oklch_to_srgb(l, gc, h)), "{gc}"); + assert!((gl - l).abs() < 2e-3 && (gh - h).abs() < 1.0, "{gl} {gh}"); + } + + /// sRGB channels below 0 go through the transfer curve with its sign turned, as CSS Color 4's + /// extended sRGB does, in both directions. + #[test] + fn negative_channels_use_the_signed_transfer_curve() { + let linear = -((0.5_f64 + 0.055) / 1.055).powf(2.4); + let [l, c, _] = to_oklch([-0.5; 3]); + assert!((l - linear.cbrt()).abs() < 1e-4 && c <= POWERLESS_CHROMA, "{l} {c}"); + for v in oklch_to_srgb(linear.cbrt(), 0.0, 0.0) { + assert!((v + 0.5).abs() < 1e-4, "{v}"); + } + // Small values near 0 keep the straight part of the curve. + let [l, _, _] = to_oklch([-0.01; 3]); + assert!((l - (-0.01_f64 / 12.92).cbrt()).abs() < 1e-4, "{l}"); + } + + /// The largest chroma fits and is at least the largest one a scan in steps of 0.0005 finds, at + /// every hue and at lightnesses near black too, where the ray can come back into sRGB away from + /// any primary color's hue (L 0.02 and H 242° fit up to about 0.022 after leaving near 0.012). + #[test] + fn the_largest_chroma_is_never_below_a_scan_of_the_ray() { + let scan = |l: f64, h: f64| (0..=1000).map(|i| f64::from(i) * 0.0005).filter(|c| in_srgb(oklch_to_srgb(l, *c, h))).fold(0.0, f64::max); + assert!(max_chroma(0.02, 242.0) > 0.02, "{}", max_chroma(0.02, 242.0)); + for l in [0.005, 0.02, 0.05, 0.1, 0.3, 0.44, 0.6, 0.8, 0.95, 0.99] { + for h in (0..72).map(|i| f64::from(i) * 5.0 + 2.0) { + let max = max_chroma(l, h); + assert!(in_srgb(oklch_to_srgb(l, max, h)) && max >= scan(l, h), "L {l} H {h}: {max} < {}", scan(l, h)); + } + } + } + + #[test] + fn black_white_and_bad_numbers_hold_no_chroma() { + assert_eq!(max_chroma(0.0, 30.0), 0.0); + assert_eq!(max_chroma(1.0, 30.0), 0.0); + assert_eq!(max_chroma(f64::NAN, 30.0), 0.0); + assert_eq!(max_chroma(0.5, f64::INFINITY), 0.0); + assert_eq!(eight(from_oklch(f64::NAN, f64::NAN, f64::NAN).0), [0, 0, 0]); + assert_eq!(eight(from_oklch(2.0, -1.0, 0.0).0), [255, 255, 255]); + } +} diff --git a/crates/color/src/palette_io.rs b/crates/color/src/palette_io.rs index 9be00b4b21..c14075bd2e 100644 --- a/crates/color/src/palette_io.rs +++ b/crates/color/src/palette_io.rs @@ -6,6 +6,8 @@ use std::collections::{HashMap, HashSet}; +pub use craft_cms::palette::css_property; +use craft_cms::palette::{self as cms_palette, Palette, PaletteColor, PaletteError, PaletteGroup, PaletteSwatch}; use serde::{Deserialize, Serialize}; use crate::{Color, GradientKind, Paint, Swatch, SwatchGroup, SwatchLibrary}; @@ -83,18 +85,93 @@ struct NativeFile { const NATIVE_FORMAT: &str = "vcswatches"; const GPL_HEADER: &str = "GIMP Palette"; -const GPL_GROUP: &str = "# Group:"; const ASE_SIGNATURE: &[u8] = b"ASEF"; -const ASE_GROUP_START: u16 = 0xC001; -const ASE_GROUP_END: u16 = 0xC002; -const ASE_COLOR: u16 = 0x0001; -/// The most colors and groups read from one `.ase` file. -const ASE_MAX_ENTRIES: usize = 100_000; -/// The most UTF-16 code units of a name that are kept. -const ASE_MAX_NAME: usize = 1024; -const ASE_CUT_SHORT: &str = "the swatch exchange file is cut short"; const ACB_SIGNATURE: &[u8] = b"8BCB"; -const ACB_CUT_SHORT: &str = "the color book is cut short"; +#[cfg(test)] +const ASE_GROUP_START: u16 = 0xC001; +#[cfg(test)] +const ASE_MAX_ENTRIES: usize = 100_000; + +fn color_to_cms(c: Color) -> PaletteColor { + match c { + Color::Rgb { r, g, b } => PaletteColor::Rgb { r, g, b }, + Color::Cmyk { c, m, y, k } => PaletteColor::Cmyk { c, m, y, k }, + Color::Lab { l, a, b } => PaletteColor::Lab { l, a, b }, + Color::Gray { k } => PaletteColor::Gray { k }, + } +} + +fn color_from_cms(c: PaletteColor) -> Color { + match c { + PaletteColor::Rgb { r, g, b } => Color::rgb(r, g, b), + PaletteColor::Cmyk { c, m, y, k } => Color::cmyk(c, m, y, k), + PaletteColor::Lab { l, a, b } => Color::lab(l, a, b), + PaletteColor::Gray { k } => Color::gray(k), + } +} + +// GPL must retain the app-managed display conversion; ASE preserves authoring models. +fn swatches_to_cms(list: &[Swatch], rgb_only: bool) -> Vec { + list.iter() + .filter_map(|w| { + w.paint.color().map(|c| PaletteSwatch { + name: w.name.clone(), + color: if rgb_only { + let [r, g, b, _] = c.to_rgba8(1.0); + PaletteColor::rgb8(r, g, b) + } else { + color_to_cms(c) + }, + global: w.global, + spot: w.spot, + }) + }) + .collect() +} + +fn swatches_from_cms(list: Vec) -> Vec { + list.into_iter().map(|w| Swatch { name: w.name, paint: Paint::solid(color_from_cms(w.color)), global: w.global, spot: w.spot }).collect() +} + +fn to_cms_palette(lib: &SwatchLibrary, rgb_only: bool) -> Palette { + Palette { + name: lib.name.clone(), + swatches: swatches_to_cms(&lib.swatches, rgb_only), + groups: lib.groups.iter().map(|g| PaletteGroup { name: g.name.clone(), swatches: swatches_to_cms(&g.swatches, rgb_only) }).collect(), + } +} + +fn from_cms_palette(p: Palette) -> SwatchLibrary { + SwatchLibrary { + name: p.name, + swatches: swatches_from_cms(p.swatches), + groups: p.groups.into_iter().map(|g| SwatchGroup { name: g.name, swatches: swatches_from_cms(g.swatches) }).collect(), + } +} + +/// Maps structured shared palette errors to VectorCraft's translatable messages. +fn palette_error(err: PaletteError) -> String { + match err { + PaletteError::UnsupportedFormat => "not a supported palette (.gpl, .ase, or .acb)".into(), + PaletteError::TruncatedAse => "the swatch exchange file is cut short".into(), + PaletteError::TruncatedAcb => "the color book is cut short".into(), + PaletteError::AseWriteEntryLimit { limit, entries } => format!( + "VectorCraft reads at most {ASE_MAX_ENTRIES} colors and groups from a swatch exchange file, and this library has {entries}", + ASE_MAX_ENTRIES = limit + ), + PaletteError::AseReadEntryLimit { limit } => { + format!("the swatch exchange file holds more than {ASE_MAX_ENTRIES} colors and groups", ASE_MAX_ENTRIES = limit) + } + PaletteError::AseBlockCount => "too many swatch exchange blocks".into(), + PaletteError::AseBlockLength => "a swatch exchange block is too long".into(), + PaletteError::AseNameLength => "a swatch exchange name is too long".into(), + PaletteError::AseVersion { major, minor } => format!("swatch exchange version {major}.{minor} isn't supported (only 1.x)"), + PaletteError::AcbVersion { version } => format!("color book version {version} isn't supported (only 1)"), + PaletteError::AcbEntryLimit { limit } => format!("the color book holds more than {ASE_MAX_ENTRIES} colors", ASE_MAX_ENTRIES = limit), + PaletteError::AcbColorSpace { space: other } => format!("color books in color space {other} aren't supported (only RGB, CMYK and Lab)"), + PaletteError::AcbNameBytes { limit } => format!("the color book's names take more than {} MB", limit >> 20), + } +} /// Write `lib` in `format` → the file's bytes. Pattern swatches (their tiles live in a document) /// and None are left out; `.gpl` keeps solid colours only, as 8-bit RGB, and `.ase` keeps solid @@ -113,8 +190,12 @@ pub fn write(lib: &SwatchLibrary, format: PaletteFormat) -> Result, Stri let file = NativeFile { format: NATIVE_FORMAT.into(), version: 1, library }; serde_json::to_string_pretty(&file).unwrap_or_default() } - PaletteFormat::Gpl => write_gpl(lib), - PaletteFormat::Ase => return write_ase(lib), + PaletteFormat::Gpl => { + return cms_palette::write_palette_typed(&to_cms_palette(lib, true), cms_palette::PaletteFormat::Gpl).map_err(palette_error); + } + PaletteFormat::Ase => { + return cms_palette::write_palette_typed(&to_cms_palette(lib, false), cms_palette::PaletteFormat::Ase).map_err(palette_error); + } PaletteFormat::Css => write_css(lib, keep), }; Ok(text.into_bytes()) @@ -125,49 +206,6 @@ fn one_line(s: &str) -> String { s.split(['\n', '\r', '\t']).collect::>().join(" ").trim().to_string() } -fn write_gpl(lib: &SwatchLibrary) -> String { - let mut out = format!("{GPL_HEADER}\nName: {}\nColumns: 0\n#\n", one_line(&lib.name)); - let colors = |out: &mut String, list: &[Swatch]| { - for w in list { - if let Some(c) = w.paint.color() { - let [r, g, b, _] = c.to_rgba8(1.0); - out.push_str(&format!("{r:3} {g:3} {b:3}\t{}\n", one_line(&w.name))); - } - } - }; - colors(&mut out, &lib.swatches); - for g in &lib.groups { - out.push_str(&format!("{GPL_GROUP} {}\n", one_line(&g.name))); - colors(&mut out, &g.swatches); - } - out -} - -/// `name` as a CSS custom property (`--` and an escaped identifier): lower case, spaces as -/// hyphens, other characters an identifier can't hold escaped with a backslash. -pub fn css_property(name: &str) -> String { - let mut out = String::from("--"); - for word in name.split_whitespace() { - if out.len() > 2 { - out.push('-'); - } - for ch in word.chars().flat_map(char::to_lowercase) { - if ch.is_ascii_alphanumeric() || ch == '-' || ch == '_' || !ch.is_ascii() { - out.push(ch); - } else if ch.is_ascii_graphic() { - out.push('\\'); - out.push(ch); - } else { - out.push_str(&format!("\\{:x} ", ch as u32)); - } - } - } - if out.len() == 2 { - out.push_str("swatch"); - } - out -} - /// A colour as CSS (`#rrggbb`, or `#rrggbbaa` below full opacity). fn css_color(c: &Color, opacity: f32) -> String { let [r, g, b, a] = c.to_rgba8(opacity); @@ -265,108 +303,12 @@ fn write_css(lib: &SwatchLibrary, keep: impl Fn(&&Swatch) -> bool) -> String { out } -/// `.ase`, as [`read_ase`] reads it: version 1.0, the ungrouped colors, then each color group as a -/// group start (its name), its colors and a group end, also for a group without colors. A color is -/// written in its own model: RGB, CMYK and gray components from 0 to 1 (gray as a level, 1 is -/// white), Lab lightness as a fraction of 100 and a and b from −128 to 127. Components are clamped -/// to those ranges, and a component that isn't a finite number is written as 0. The color type is -/// 1 for a spot color, 0 for another global color and 2 for a process color. -/// -/// A swatch exchange file holds solid colors only: gradients, patterns and None are left out, and -/// a tint swatch is written as the color it shows, a process color without its link to its base. -/// The file has no library name ([`read_ase`] names a library after its file). More than -/// [`ASE_MAX_ENTRIES`] colors and groups is an error. -fn write_ase(lib: &SwatchLibrary) -> Result, String> { - let solid = |list: &[Swatch]| list.iter().filter(|w| w.paint.color().is_some()).count(); - let entries = solid(&lib.swatches) + lib.groups.iter().map(|g| 1 + solid(&g.swatches)).sum::(); - if entries > ASE_MAX_ENTRIES { - return Err(format!( - "VectorCraft reads at most {ASE_MAX_ENTRIES} colors and groups from a swatch exchange file, and this library has {entries}" - )); - } - let mut body = vec![]; - let mut blocks = put_ase_colors(&mut body, &lib.swatches)?; - for g in &lib.groups { - let mut name = vec![]; - put_ase_name(&mut name, &g.name)?; - put_ase_block(&mut body, ASE_GROUP_START, &name)?; - blocks += 2 + put_ase_colors(&mut body, &g.swatches)?; - put_ase_block(&mut body, ASE_GROUP_END, &[])?; - } - let blocks = u32::try_from(blocks).map_err(|_| "too many swatch exchange blocks".to_string())?; - let mut out = ASE_SIGNATURE.to_vec(); - out.extend(1u16.to_be_bytes()); - out.extend(0u16.to_be_bytes()); - out.extend(blocks.to_be_bytes()); - out.extend(body); - Ok(out) -} - -/// The color blocks of the solid colors in `list` → how many were written. -fn put_ase_colors(out: &mut Vec, list: &[Swatch]) -> Result { - let unit = |v: f32| if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 }; - let ab = |v: f32| if v.is_finite() { v.clamp(-128.0, 127.0) } else { 0.0 }; - let mut n = 0; - for (w, color) in list.iter().filter_map(|w| Some((w, w.paint.color()?))) { - let mut body = vec![]; - put_ase_name(&mut body, &w.name)?; - let (model, values): (&[u8; 4], Vec) = match color { - Color::Rgb { r, g, b } => (b"RGB ", vec![unit(r), unit(g), unit(b)]), - Color::Cmyk { c, m, y, k } => (b"CMYK", vec![unit(c), unit(m), unit(y), unit(k)]), - Color::Lab { l, a, b } => (b"LAB ", vec![unit(l / 100.0), ab(a), ab(b)]), - Color::Gray { k } => (b"Gray", vec![1.0 - unit(k)]), - }; - body.extend(model); - body.extend(values.iter().flat_map(|v| v.to_be_bytes())); - let kind: u16 = if w.spot { - 1 - } else if w.global { - 0 - } else { - 2 - }; - body.extend(kind.to_be_bytes()); - put_ase_block(out, ASE_COLOR, &body)?; - n += 1; - } - Ok(n) -} - -/// A block: its type, the length of its body and the body. -fn put_ase_block(out: &mut Vec, kind: u16, body: &[u8]) -> Result<(), String> { - let len = u32::try_from(body.len()).map_err(|_| "a swatch exchange block is too long".to_string())?; - out.extend(kind.to_be_bytes()); - out.extend(len.to_be_bytes()); - out.extend_from_slice(body); - Ok(()) -} - -/// A name as `.ase` stores it: a `u16` count of UTF-16 code units, the terminating zero included, -/// then the units. NUL characters are left out, and a name longer than [`ASE_MAX_NAME`] code units -/// is cut before the character that would pass that limit. -fn put_ase_name(out: &mut Vec, name: &str) -> Result<(), String> { - let mut units: Vec = vec![]; - for c in name.chars().filter(|&c| c != '\0') { - let mut buf = [0; 2]; - let encoded = c.encode_utf16(&mut buf); - if units.len() + encoded.len() > ASE_MAX_NAME { - break; - } - units.extend_from_slice(encoded); - } - units.push(0); - let count = u16::try_from(units.len()).map_err(|_| "a swatch exchange name is too long".to_string())?; - out.extend(count.to_be_bytes()); - out.extend(units.iter().flat_map(|u| u.to_be_bytes())); - Ok(()) -} - /// Read a `.vcswatches` or `.gpl` library (detected from its content). `name` names it when the /// file doesn't. pub fn read(text: &str, name: &str) -> Result { let text = text.trim_start_matches('\u{feff}').trim_start(); if text.starts_with(GPL_HEADER) { - return Ok(read_gpl(text, name)); + return cms_palette::read_palette_typed(text.as_bytes(), name).map(from_cms_palette).map_err(palette_error); } if text.starts_with('{') { let f: NativeFile = serde_json::from_str(text).map_err(|e| format!("not a swatch library: {e}"))?; @@ -391,11 +333,8 @@ pub fn sniff(text: &str) -> bool { /// Read the bytes of a library file: a swatch exchange `.ase` file, else a `.vcswatches` or /// `.gpl` library ([`read`]). `name` names it when the file doesn't. pub fn read_bytes(bytes: &[u8], name: &str) -> Result { - if bytes.starts_with(ASE_SIGNATURE) { - return read_ase(bytes, name); - } - if bytes.starts_with(ACB_SIGNATURE) { - return read_acb(bytes, name).map_err(|e| if e == ASE_CUT_SHORT { ACB_CUT_SHORT.into() } else { e }); + if bytes.starts_with(ASE_SIGNATURE) || bytes.starts_with(ACB_SIGNATURE) { + return cms_palette::read_palette_typed(bytes, name).map(from_cms_palette).map_err(palette_error); } read(&String::from_utf8_lossy(bytes), name) } @@ -409,303 +348,5 @@ pub fn sniff_bytes(bytes: &[u8]) -> bool { || sniff(&String::from_utf8_lossy(bytes.get(..1024).unwrap_or(bytes))) } -/// `.gpl`: `Name:` names the library, `# Group: name` starts a colour group, other `#` lines and -/// headers (`Columns:`) are skipped, as are lines that aren't `r g b [name]`. Unnamed colors are -/// named by their values and unnamed groups "Color Group"; a name a color or group already has gets -/// a number ([`UniqueNames`]). -fn read_gpl(text: &str, fallback: &str) -> SwatchLibrary { - let mut lib = SwatchLibrary { name: fallback.into(), ..Default::default() }; - let mut names = UniqueNames::default(); - for line in text.lines().skip(1) { - let line = line.trim(); - if let Some(g) = line.strip_prefix(GPL_GROUP) { - lib.groups.push(SwatchGroup { name: names.unique(group_name(g)), swatches: vec![] }); - continue; - } - if let Some(n) = line.strip_prefix("Name:") { - if !n.trim().is_empty() { - lib.name = n.trim().to_string(); - } - continue; - } - // Comments, headers (`Columns: 4`) and anything else that isn't a colour are skipped. - let words: Vec<&str> = line.split_whitespace().collect(); - let rgb: Vec = words.iter().take(3).map_while(|v| v.parse().ok()).collect(); - let [r, g, b] = rgb[..] else { continue }; - let rest = words[3..].join(" "); - let base = if rest.is_empty() { format!("R={r} G={g} B={b}") } else { rest }; - let w = Swatch { name: names.unique(base), paint: Paint::solid(Color::rgb8(r, g, b)), global: false, spot: false }; - match lib.groups.last_mut() { - Some(grp) => grp.swatches.push(w), - None => lib.swatches.push(w), - } - } - lib -} - -/// `.ase`, from public descriptions of the format: the layout from -/// , the component ranges from -/// . After the signature come, big-endian, a `u16` major (1) and -/// minor version, a `u32` block count and the blocks, each a `u16` type, a `u32` body length and -/// the body. A group start's body is a name. A color's body is a name, a four-character model -/// (`RGB `, `CMYK`, `LAB `, `Gray`), its components as `f32` (3, 4, 3 and 1 of them) and a `u16` -/// color type (0 global, 1 spot, 2 process). RGB, CMYK and gray components run from 0 to 1 (a -/// gray level of 1 is white), Lab lightness from 0 to 1 and a and b from −128 to 127. A lightness -/// above 1 is read as L* itself. A name is a `u16` count of UTF-16 code units, the terminating zero -/// included, then the units. -/// -/// Color groups become groups: a group start inside an open group ends that group, and a group -/// left open ends with the file. Blocks of other types and colors in other models are skipped. -/// Unnamed colors are named by their values and unnamed groups "Color Group"; a name a color or -/// group already has gets a number ([`UniqueNames`]). A truncated file, a major version other than -/// 1 or more than [`ASE_MAX_ENTRIES`] colors and groups is an error. -fn read_ase(bytes: &[u8], fallback: &str) -> Result { - let mut data = AseData(bytes); - data.bytes(ASE_SIGNATURE.len())?; - let (major, minor) = (data.u16()?, data.u16()?); - if major != 1 { - return Err(format!("swatch exchange version {major}.{minor} isn't supported (only 1.x)")); - } - let blocks = data.u32()?; - let mut lib = SwatchLibrary { name: fallback.into(), ..Default::default() }; - let mut names = UniqueNames::default(); - let (mut in_group, mut entries) = (false, 0usize); - for _ in 0..blocks { - let kind = data.u16()?; - let len = usize::try_from(data.u32()?).unwrap_or(usize::MAX); - let mut body = AseData(data.bytes(len)?); - if matches!(kind, ASE_GROUP_START | ASE_COLOR) { - entries += 1; - if entries > ASE_MAX_ENTRIES { - return Err(format!("the swatch exchange file holds more than {ASE_MAX_ENTRIES} colors and groups")); - } - } - match kind { - ASE_GROUP_START => { - lib.groups.push(SwatchGroup { name: names.unique(group_name(&body.name()?)), swatches: vec![] }); - in_group = true; - } - ASE_GROUP_END => in_group = false, - ASE_COLOR => { - let Some(mut w) = ase_swatch(&mut body)? else { continue }; - w.name = names.unique(std::mem::take(&mut w.name)); - match lib.groups.last_mut().filter(|_| in_group) { - Some(g) => g.swatches.push(w), - None => lib.swatches.push(w), - } - } - // Other blocks are skipped. - _ => {} - } - } - Ok(lib) -} - -/// `.acb` (a color book, read only), from public descriptions of the format: after the signature -/// come, big-endian, a `u16` version (1) and book id, the title, prefix, suffix and description -/// as strings, a `u16` color count, page size and page selector offset, a `u16` color space (0 -/// RGB, 2 CMYK, 7 Lab) and the colors: each a name, a six-character catalog code and its -/// components as bytes. RGB runs from 0 to 255, CMYK ink is stored inverted (255 is no ink), Lab -/// lightness is 0 to 255 for 0 to 100 and a and b are offset by 128. A string is a `u32` count of -/// UTF-16 code units, then the units; a `$$$/key=Text` string means `Text`, and `^R`, `^C` stand -/// for ® and ©. An optional `spflspot` or `spflproc` at the end says whether the colors are spot -/// or process colors (a book without it is a spot color book). -/// -/// The book's colors are named with its prefix and suffix ("PANTONE 185 C"); colors without a -/// name (the padding of a book's pages) are left out. A version other than 1, a color space other -/// than those three or more than [`ASE_MAX_ENTRIES`] colors is an error. -fn read_acb(bytes: &[u8], fallback: &str) -> Result { - let mut data = AseData(bytes); - data.bytes(ACB_SIGNATURE.len())?; - let version = data.u16()?; - if version != 1 { - return Err(format!("color book version {version} isn't supported (only 1)")); - } - let _book_id = data.u16()?; - let [title, prefix, suffix, _description] = [data.acb_string()?, data.acb_string()?, data.acb_string()?, data.acb_string()?]; - let count = usize::from(data.u16()?); - if count > ASE_MAX_ENTRIES { - return Err(format!("the color book holds more than {ASE_MAX_ENTRIES} colors")); - } - let (_page_size, _page_offset) = (data.u16()?, data.u16()?); - let space = data.u16()?; - let mut colors = Vec::with_capacity(count); - for _ in 0..count { - let name = data.acb_string()?; - let _code = data.bytes(6)?; - let color = match space { - 0 => { - let [r, g, b] = data.array::<3>()?; - Color::rgb8(r, g, b) - } - 2 => { - let ink = |v: u8| f32::from(255 - v) / 255.0; - let [c, m, y, k] = data.array::<4>()?; - Color::cmyk(ink(c), ink(m), ink(y), ink(k)) - } - 7 => { - let [l, a, b] = data.array::<3>()?; - Color::lab(f32::from(l) * 100.0 / 255.0, f32::from(a) - 128.0, f32::from(b) - 128.0) - } - other => return Err(format!("color books in color space {other} aren't supported (only RGB, CMYK and Lab)")), - }; - colors.push((name, color)); - } - // Spot colors unless the book says process ones. - let spot = data.0.windows(8).last() != Some(b"spflproc".as_slice()); - let mut lib = SwatchLibrary { name: if title.is_empty() { fallback.into() } else { title }, ..Default::default() }; - let mut names = UniqueNames::default(); - // Every name gets the prefix and the suffix, and is kept twice (the swatch's and the set of - // names taken): a megabyte book of long affixes and many colors came to hundreds of MB. - let mut kept = 0usize; - for (name, color) in colors.into_iter().filter(|(n, _)| !n.trim().is_empty()) { - kept = kept.saturating_add(2 * (prefix.len() + name.len() + suffix.len())); - if kept > ACB_MAX_NAME_BYTES { - return Err(format!("the color book's names take more than {} MB", ACB_MAX_NAME_BYTES >> 20)); - } - let name = names.unique(format!("{prefix}{name}{suffix}").trim().to_string()); - lib.swatches.push(Swatch { name, paint: Paint::solid(color), global: spot, spot }); - } - Ok(lib) -} - -/// Most bytes a color book's full color names (with its prefix and suffix) may take, counted -/// twice as they are kept twice. -const ACB_MAX_NAME_BYTES: usize = 64 << 20; - -/// The swatch of an `.ase` color block, `None` for a model other than RGB, CMYK, Lab and Gray. -/// Components are clamped to their ranges. -fn ase_swatch(body: &mut AseData) -> Result, String> { - let name = body.name()?; - let unit = |v: f32| v.clamp(0.0, 1.0); - let color = match &body.array::<4>()? { - b"RGB " => { - let [r, g, b] = [body.f32()?, body.f32()?, body.f32()?]; - Color::rgb(unit(r), unit(g), unit(b)) - } - b"CMYK" => { - let [c, m, y, k] = [body.f32()?, body.f32()?, body.f32()?, body.f32()?]; - Color::cmyk(unit(c), unit(m), unit(y), unit(k)) - } - // Lightness is stored as a fraction of 100. Some writers store L* itself, which shows as a - // value above 1. - b"LAB " => { - let [l, a, b] = [body.f32()?, body.f32()?, body.f32()?]; - let l = if l > 1.0 { l.min(100.0) } else { unit(l) * 100.0 }; - Color::lab(l, a.clamp(-128.0, 127.0), b.clamp(-128.0, 127.0)) - } - // A gray level (1 is white); a gray color holds its ink. - b"Gray" => Color::gray(1.0 - unit(body.f32()?)), - _ => return Ok(None), - }; - // Some writers leave the color type out, which makes a process color. - let kind = if body.0.len() >= 2 { body.u16()? } else { 2 }; - // Spot colors are global. - let (global, spot) = match kind { - 0 => (true, false), - 1 => (true, true), - _ => (false, false), - }; - let name = if name.is_empty() { value_name(color) } else { name }; - Ok(Some(Swatch { name, paint: Paint::solid(color), global, spot })) -} - -/// A color's values in its own model, as new swatches are named ("C=10 M=20 Y=30 K=0", -/// "R=255 G=128 B=0", "Gray K=40", "L=52 a=70 b=-30"). -fn value_name(c: Color) -> String { - let pct = |v: f32| (v * 100.0).round(); - let byte = |v: f32| (v * 255.0).round(); - match c { - Color::Cmyk { c, m, y, k } => format!("C={} M={} Y={} K={}", pct(c), pct(m), pct(y), pct(k)), - Color::Rgb { r, g, b } => format!("R={} G={} B={}", byte(r), byte(g), byte(b)), - Color::Gray { k } => format!("Gray K={}", pct(k)), - // `+ 0.0` turns a rounded -0 into 0. - Color::Lab { l, a, b } => format!("L={} a={} b={}", l.round() + 0.0, a.round() + 0.0, b.round() + 0.0), - } -} - -/// `.ase` data, read field by field; reading past its end is an error. -struct AseData<'a>(&'a [u8]); - -impl<'a> AseData<'a> { - fn bytes(&mut self, n: usize) -> Result<&'a [u8], String> { - let (head, rest) = self.0.split_at_checked(n).ok_or(ASE_CUT_SHORT)?; - self.0 = rest; - Ok(head) - } - fn array(&mut self) -> Result<[u8; N], String> { - let (head, rest) = self.0.split_first_chunk::().ok_or(ASE_CUT_SHORT)?; - self.0 = rest; - Ok(*head) - } - fn u16(&mut self) -> Result { - self.array().map(u16::from_be_bytes) - } - fn u32(&mut self) -> Result { - self.array().map(u32::from_be_bytes) - } - /// A component; one that isn't a finite number reads as 0. - fn f32(&mut self) -> Result { - let v = f32::from_be_bytes(self.array()?); - Ok(if v.is_finite() { v } else { 0.0 }) - } - /// A color book string ([`read_acb`]): a `u32` count of UTF-16 code units, then the units, - /// with `$$$/key=Text` read as `Text` and `^R`, `^C` as ®, ©; at most [`ASE_MAX_NAME`] units - /// are kept. - fn acb_string(&mut self) -> Result { - let n = usize::try_from(self.u32()?).unwrap_or(usize::MAX); - let (units, _) = self.bytes(n.checked_mul(2).ok_or(ASE_CUT_SHORT)?)?.as_chunks::<2>(); - let units: Vec = units.iter().take(ASE_MAX_NAME).map(|u| u16::from_be_bytes(*u)).take_while(|&u| u != 0).collect(); - let s = String::from_utf16_lossy(&units); - let s = match s.strip_prefix("$$$/") { - Some(key) => key.split_once('=').map_or("", |(_, text)| text).to_string(), - None => s, - }; - Ok(s.replace("^R", "®").replace("^C", "©")) - } - /// A name up to its terminating zero, trimmed. A block that ends before it has no name. - fn name(&mut self) -> Result { - if self.0.is_empty() { - return Ok(String::new()); - } - let n = usize::from(self.u16()?); - let (units, _) = self.bytes(n * 2)?.as_chunks::<2>(); - let units: Vec = units.iter().take(ASE_MAX_NAME).map(|u| u16::from_be_bytes(*u)).take_while(|&u| u != 0).collect(); - Ok(String::from_utf16_lossy(&units).trim().to_string()) - } -} - -/// A group's name as a file gives it, trimmed; "Color Group" when it has none. -fn group_name(name: &str) -> String { - let name = name.trim(); - if name.is_empty() { "Color Group".into() } else { name.to_string() } -} - -/// The swatch and group names a reader has handed out. Swatches and color groups share one set of -/// names, as in a document, and a name already taken gets the first free number ("Black 2"). -#[derive(Default)] -struct UniqueNames { - taken: HashSet, - /// The last number tried for each repeated name. - last: HashMap, -} - -impl UniqueNames { - fn unique(&mut self, base: String) -> String { - if self.taken.insert(base.clone()) { - return base; - } - // Each pass tries the next number, and only finitely many names are taken. - let n = self.last.entry(base.clone()).or_insert(1); - loop { - *n += 1; - let name = format!("{base} {n}"); - if self.taken.insert(name.clone()) { - return name; - } - } - } -} - #[cfg(test)] mod tests; diff --git a/crates/color/src/palette_io/tests.rs b/crates/color/src/palette_io/tests.rs index bbbae16a53..b0036b6fc6 100644 --- a/crates/color/src/palette_io/tests.rs +++ b/crates/color/src/palette_io/tests.rs @@ -2,6 +2,9 @@ use super::*; use crate::{Gradient, GradientPaint, GradientStop}; use proptest::prelude::*; +const ASE_COLOR: u16 = 0x0001; +const ASE_GROUP_END: u16 = 0xC002; + #[test] fn gpl_blank_name_keeps_fallback() { let blank = "GIMP Palette\nName: \nColumns: 0\n#\n 1 2 3\tx\n"; @@ -700,3 +703,52 @@ proptest! { } } } + +#[test] +fn shared_gpl_adapter_uses_app_color_conversion() { + let colors = [Color::cmyk(0.2, 0.4, 0.6, 0.1), Color::lab(55.0, 30.0, -25.0), Color::gray(0.3)]; + let lib = SwatchLibrary { + name: "Managed".into(), + swatches: colors + .iter() + .enumerate() + .map(|(i, &color)| Swatch { name: format!("Color {i}"), paint: Paint::solid(color), global: false, spot: false }) + .collect(), + groups: vec![], + }; + let mut expected = String::from("GIMP Palette\nName: Managed\nColumns: 0\n#\n"); + for (i, color) in colors.iter().enumerate() { + let [r, g, b, _] = color.to_rgba8(1.0); + expected.push_str(&format!("{r:3} {g:3} {b:3}\tColor {i}\n")); + } + assert_eq!(write(&lib, PaletteFormat::Gpl).unwrap(), expected.as_bytes()); + assert!(to_cms_palette(&lib, true).swatches.iter().all(|w| matches!(w.color, PaletteColor::Rgb { .. }))); + assert!(matches!(to_cms_palette(&lib, false).swatches[0].color, PaletteColor::Cmyk { .. })); + assert!(matches!(to_cms_palette(&lib, false).swatches[1].color, PaletteColor::Lab { .. })); +} + +#[test] +fn typed_palette_errors_keep_app_wording() { + let cases = [ + (PaletteError::UnsupportedFormat, "not a supported palette (.gpl, .ase, or .acb)"), + (PaletteError::TruncatedAse, "the swatch exchange file is cut short"), + (PaletteError::TruncatedAcb, "the color book is cut short"), + ( + PaletteError::AseWriteEntryLimit { limit: 3, entries: 4 }, + "VectorCraft reads at most 3 colors and groups from a swatch exchange file, and this library has 4", + ), + (PaletteError::AseReadEntryLimit { limit: 3 }, "the swatch exchange file holds more than 3 colors and groups"), + (PaletteError::AseBlockCount, "too many swatch exchange blocks"), + (PaletteError::AseBlockLength, "a swatch exchange block is too long"), + (PaletteError::AseNameLength, "a swatch exchange name is too long"), + (PaletteError::AseVersion { major: 2, minor: 3 }, "swatch exchange version 2.3 isn't supported (only 1.x)"), + (PaletteError::AcbVersion { version: 2 }, "color book version 2 isn't supported (only 1)"), + (PaletteError::AcbEntryLimit { limit: 3 }, "the color book holds more than 3 colors"), + (PaletteError::AcbColorSpace { space: 5 }, "color books in color space 5 aren't supported (only RGB, CMYK and Lab)"), + (PaletteError::AcbNameBytes { limit: 64 << 20 }, "the color book's names take more than 64 MB"), + ]; + for (error, expected) in cases { + assert_eq!(palette_error(error), expected); + } + assert_eq!(read_bytes(b"8BCB\0\x01\0\0\0\0\0\x03\0x", "fallback").unwrap_err(), "the color book is cut short"); +} diff --git a/crates/doc/src/blend.rs b/crates/doc/src/blend.rs index 7c7429acc2..02458af8c5 100644 --- a/crates/doc/src/blend.rs +++ b/crates/doc/src/blend.rs @@ -1156,6 +1156,17 @@ impl Lerp { (NodeKind::PlacedDocument(o), NodeKind::PlacedDocument(x), NodeKind::PlacedDocument(y)) => o.xf = lerp_affine(x.xf, y.xf, t), _ => {} } + // Between distorted images, each step's corners lie between the keys' corners. A + // step whose corners would fold keeps the nearer key's. + if (a.is_distorted_image() || b.is_distorted_image()) + && let (Some(qa), Some(qb)) = (a.image_corners(), b.image_corners()) + { + let near = if t < 0.5 { qa } else { qb }; + if n.set_image_corners([0, 1, 2, 3].map(|i| qa[i].lerp(qb[i], t))).is_err() { + // The nearer key's corners passed the same check when it was distorted. + let _ = n.set_image_corners(near); + } + } n.extras_mut().mask = None; n } @@ -2297,6 +2308,43 @@ mod tests { assert_eq!(m.subpaths[0].anchors[0].p, Point::new(55.0, 0.0)); } + /// A step between two distorted images has its corners between the keys' corners. + #[test] + fn steps_between_distorted_images_have_corners_between_theirs() { + let image = |q: [(f64, f64); 4]| { + let im = crate::ImageObject { + key: "k".into(), + width: 10, + height: 10, + xf: Affine::IDENTITY, + link: None, + placement: Default::default(), + pixels: None, + }; + let mut n = Node::new(NodeId(1), NodeKind::Image(Box::new(im))); + n.set_image_corners(q.map(|(x, y)| Point::new(x, y))).unwrap(); + n + }; + let a = image([(40.0, 0.0), (60.0, 0.0), (100.0, 100.0), (0.0, 100.0)]); + let b = image([(200.0, 0.0), (300.0, 0.0), (280.0, 100.0), (220.0, 100.0)]); + let mid = Lerp::new(&a, &b, (None, None)).at(0.5); + let want = [(120.0, 0.0), (180.0, 0.0), (190.0, 100.0), (110.0, 100.0)]; + let got = mid.image_corners().unwrap(); + for (g, (x, y)) in got.iter().zip(want) { + assert!(g.distance(Point::new(x, y)) < 1e-9, "{got:?}"); + } + // Toward a key flipped left to right, the middle step's corners would meet: each step + // there keeps the nearer key's corners, whether that key is distorted or not. + let flipped = image([(60.0, 0.0), (40.0, 0.0), (0.0, 100.0), (100.0, 100.0)]); + let mirror = image([(100.0, 0.0), (0.0, 0.0), (0.0, 100.0), (100.0, 100.0)]); + assert!(!mirror.is_distorted_image()); + for (b, t) in [(&flipped, 0.5), (&mirror, 0.5), (&mirror, 0.45)] { + let got = Lerp::new(&a, b, (None, None)).at(t).image_corners().unwrap(); + let near = (if t < 0.5 { &a } else { b }).image_corners().unwrap(); + assert!(got.iter().zip(near).all(|(g, w)| g.distance(w) < 1e-9), "{t}: {got:?} against {near:?}"); + } + } + fn key(x: f64) -> Arc { Arc::new(Node::path(NodeId(1), vectorcraft_geom::shapes::rectangle(Rect::new(x, 0.0, x + 10.0, 10.0)), Appearance::default())) } diff --git a/crates/doc/src/document_guides.rs b/crates/doc/src/document_guides.rs index ba6e4dc428..ba203610d6 100644 --- a/crates/doc/src/document_guides.rs +++ b/crates/doc/src/document_guides.rs @@ -500,11 +500,73 @@ impl Document { self.patterns.iter_mut().find(|p| p.name == name) } + /// The [`Self::unknown`] key that holds each symbol set's Symbol Set Density, `{set id: density}`. + /// [`Self::reid`] gives a copy of a set in this document the density recorded for its source, and + /// [`Self::carry_set_densities`] gives a pasted set the density recorded for it at Copy. + pub const SYMBOL_SET_DENSITY_KEY: &'static str = "symbolSetDensity"; + + /// The Symbol Set Densities recorded for `nodes` and their descendants, by id. + pub fn set_densities_of(&self, nodes: &[Node]) -> std::collections::BTreeMap { + let Some(serde_json::Value::Object(record)) = self.unknown.get(Self::SYMBOL_SET_DENSITY_KEY) else { return Default::default() }; + let mut out = std::collections::BTreeMap::new(); + let mut stack: Vec<&Node> = nodes.iter().collect(); + while let Some(n) = stack.pop() { + if let Some(v) = record.get(&n.id.0.to_string()) { + out.insert(n.id, v.clone()); + } + stack.extend(n.children().into_iter().flatten().map(|c| &**c)); + } + out + } + + /// Record for `copy`, a [`Self::reid`] copy of `source`, and its descendants the Symbol Set + /// Densities that `densities` holds for `source` and its descendants, and none for those it + /// holds none for (whatever [`Self::reid`] recorded). + pub fn carry_set_densities(&mut self, source: &Node, copy: &Node, densities: &std::collections::BTreeMap) { + if densities.is_empty() && !self.unknown.contains_key(Self::SYMBOL_SET_DENSITY_KEY) { + return; + } + let mut pairs = vec![(source, copy)]; + while let Some((s, c)) = pairs.pop() { + match densities.get(&s.id) { + Some(v) => { + if let serde_json::Value::Object(m) = + self.unknown.entry(Self::SYMBOL_SET_DENSITY_KEY).or_insert_with(|| serde_json::Value::Object(Default::default())) + { + m.insert(c.id.0.to_string(), v.clone()); + } + } + None => { + if let Some(serde_json::Value::Object(m)) = self.unknown.get_mut(Self::SYMBOL_SET_DENSITY_KEY) { + m.remove(&c.id.0.to_string()); + } + } + } + if let (Some(sc), Some(cc)) = (s.children(), c.children()) { + pairs.extend(sc.iter().zip(cc.iter()).map(|(a, b)| (&**a, &**b))); + } + } + } + /// Deep-clone `node` with fresh ids for it and all descendants, its images' own pixels taken /// in ([`Self::adopt_pixels`]). pub fn reid(&mut self, node: &Node) -> Node { let mut n = node.clone(); n.id = self.alloc_id(); + // A copy of a symbol set keeps the Symbol Set Density recorded for its source, when the source + // is this document's node with that id; a node from another document may share the id of an + // unrelated set here. + let density = self + .unknown + .get(Self::SYMBOL_SET_DENSITY_KEY) + .and_then(|m| m.get(node.id.0.to_string())) + .filter(|_| self.node(node.id) == Some(node)) + .cloned(); + if let Some(v) = density + && let Some(serde_json::Value::Object(m)) = self.unknown.get_mut(Self::SYMBOL_SET_DENSITY_KEY) + { + m.insert(n.id.0.to_string(), v); + } if let NodeKind::Image(im) = &mut n.kind { self.adopt_image_pixels(im); } diff --git a/crates/doc/src/hit.rs b/crates/doc/src/hit.rs index c996699391..fcbe2f9db1 100644 --- a/crates/doc/src/hit.rs +++ b/crates/doc/src/hit.rs @@ -1503,14 +1503,17 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio // An image is hit within its frame (on the frame's edge only with Selection by Path Only, // #3291, and in outline mode where the frame is all that is drawn, #6437), and where its // own fills and strokes paint ([`image_paint`]) except in outline mode. - NodeKind::Image(im) => { + NodeKind::Image(_) => { + // The frame joins the image's corners ([`Node::image_frame`]); a plain image is picked + // inside by its bounds, without building it. if opt.path_only || (opt.outline && !symbols.document().setup.outline_images) { - use vectorcraft_geom::kurbo::Shape; - let mut frame = Rect::new(0.0, 0.0, f64::from(im.width), f64::from(im.height)).to_path(0.1); - frame.apply_affine(im.xf); - if stroke_contains(&frame, 0.0, opt.tol, p) { + if n.image_frame().is_some_and(|frame| stroke_contains(&frame, 0.0, opt.tol, p)) { return Some(HitKind::Outline); } + } else if let Some(frame) = n.is_distorted_image().then(|| n.image_frame()).flatten() { + if fill_contains(&frame, FillRule::NonZero, p) || stroke_contains(&frame, 0.0, opt.tol, p) { + return Some(HitKind::Bounds); + } } else if n.geometric_bounds_with(symbols).is_some_and(|b| b.inflate(opt.tol, opt.tol).contains(p)) { return Some(HitKind::Bounds); } diff --git a/crates/doc/src/image_quad.rs b/crates/doc/src/image_quad.rs new file mode 100644 index 0000000000..e07fd47760 --- /dev/null +++ b/crates/doc/src/image_quad.rs @@ -0,0 +1,599 @@ +//! Perspective Distort and Free Distort on an image: its pixel rectangle's corners placed anywhere +//! on the page, as long as they make a strictly convex quadrilateral. +//! +//! An image whose corners make a parallelogram is placed by its transform alone +//! ([`crate::ImageObject::xf`]). Other corners are kept in the image's extras +//! ([`crate::NodeExtras::image_quad`]), and the image is then drawn through the projective map +//! that takes its pixel rectangle to them. The renderer, the exporters and printing draw it as a +//! raster mesh warp ([`crate::live::mesh_warp_image`]) made from that map ([`distorted_art`]): no +//! warped copy of the pixels is kept. The quad stays with the image's transform: moving, scaling, +//! rotating or shearing the image maps its corners too ([`crate::Node::transform`]). +//! +//! The convexity rule, the tolerance of the mesh and its cell limit are VectorCraft's own. + +use std::sync::Arc; + +use vectorcraft_geom::kurbo::BezPath; +use vectorcraft_geom::{Affine, Homography, PathData, Point, Rect, SubPath}; + +use crate::{Appearance, ImageObject, Node, NodeKind}; + +/// Most cells along each side of the mesh an image is drawn with ([`cells`]). +pub const MAX_CELLS: usize = 64; + +/// The cells along each side an image with fewer pixels than this may still take ([`cells`]). +pub const MIN_CELL_CAP: usize = 8; + +/// How far (in points) the mesh an image is drawn with in files and print may stray from the exact +/// projective map ([`Density::PAGE`]). +pub const TOLERANCE: f64 = 0.05; + +/// How finely [`distorted_art_at`] cuts a distorted image ([`cells`]), and how far each piece +/// reaches into its neighbors. A pixel inside the image draws opaque only when one piece covers +/// it whole, so pieces much smaller than a pixel would let the page show through. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Density { + /// How far (in points) the mesh may stray from the exact projective map. + pub tolerance: f64, + /// The shortest a cell may be along the longest side of the corners, in points. + pub min_cell: f64, + /// How far (in points) each piece reaches past its triangle. + pub overlap: f64, +} + +impl Density { + /// For files and print, whose viewing size is not known: within [`TOLERANCE`], cells of at + /// least 2 pt, and pieces that reach half a point past their triangles. + pub const PAGE: Density = Density { tolerance: TOLERANCE, min_cell: 2.0, overlap: 0.5 }; + + /// For drawing at `scale` device pixels a point: within a quarter of a pixel, cells of at least + /// 4 pixels, and pieces that reach 2 pixels past their triangles. + pub fn at_scale(scale: f64) -> Density { + let s = if scale.is_finite() && scale > 1e-6 { scale } else { 1.0 }; + Density { tolerance: 0.25 / s, min_cell: 4.0 / s, overlap: 2.0 / s } + } + + /// [`Density::PAGE`] for art that is drawn `scale` times its size (a symbol's art in an + /// instance that scales it): the tolerance, the cell size and the overlap measured on the page. + pub fn page_at(scale: f64) -> Density { + let s = if scale.is_finite() && scale > 1e-6 { scale } else { 1.0 }; + let p = Density::PAGE; + Density { tolerance: p.tolerance / s, min_cell: p.min_cell / s, overlap: p.overlap / s } + } +} + +/// How much `a` stretches its most stretched direction: the larger singular value of its linear +/// part. +pub fn max_stretch(a: Affine) -> f64 { + let [m0, m1, m2, m3, _, _] = a.as_coeffs(); + let sum = m0 * m0 + m1 * m1 + m2 * m2 + m3 * m3; + let det = m0 * m3 - m1 * m2; + ((sum + (sum * sum - 4.0 * det * det).max(0.0).sqrt()) / 2.0).sqrt() +} + +/// Why corners cannot be an image's. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum QuadError { + /// A corner is not a finite point. + NotFinite, + /// The corners fold over, meet, or lie on one line: the quadrilateral is not strictly convex. + NotConvex, + /// The corners are convex but so close to a line that the perspective map through them cannot + /// place every corner. + TooNarrow, +} + +impl std::fmt::Display for QuadError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(match self { + Self::NotFinite => "the corners of a distorted image must be finite points", + Self::NotConvex => "the corners of a distorted image must make a convex shape: an image cannot fold over itself or collapse to a line", + Self::TooNarrow => "the corners of a distorted image are too close together for a perspective map", + }) + } +} + +/// `im`'s pixel rectangle: (0, 0) to its width and height. +fn pixel_rect(im: &ImageObject) -> Rect { + Rect::new(0.0, 0.0, f64::from(im.width), f64::from(im.height)) +} + +/// The corners of `r` in the order a quad keeps them: top left, top right, bottom right, bottom +/// left. +fn rect_corners(r: Rect) -> [Point; 4] { + [Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x1, r.y1), Point::new(r.x0, r.y1)] +} + +/// Whether the corners `q` (in order around the shape) are finite and make a strictly convex +/// quadrilateral, turning either way round. Each turn must be larger than 1e-9 times the product +/// of the two sides it joins, a test that gives the same answer at any scale. +pub fn check(q: &[Point; 4]) -> Result<(), QuadError> { + if q.iter().any(|p| !p.is_finite()) { + return Err(QuadError::NotFinite); + } + let mut sign = 0.0; + for i in 0..4 { + let (a, b, c) = (q[i], q[(i + 1) % 4], q[(i + 2) % 4]); + let (u, v) = (b - a, c - b); + let cross = u.cross(v); + let scale = u.hypot() * v.hypot(); + if !cross.is_finite() || !scale.is_finite() || cross.abs() <= 1e-9 * scale || scale == 0.0 { + return Err(QuadError::NotConvex); + } + if sign == 0.0 { + sign = cross.signum(); + } else if cross.signum() != sign { + return Err(QuadError::NotConvex); + } + } + // Four turns the same way round can still wind twice (a star); a convex quadrilateral's + // diagonals cross. + let crosses = |a: Point, b: Point, c: Point, d: Point| (b - a).cross(c - a).signum() != (b - a).cross(d - a).signum(); + if !crosses(q[0], q[2], q[1], q[3]) || !crosses(q[1], q[3], q[0], q[2]) { + return Err(QuadError::NotConvex); + } + Ok(()) +} + +/// Whether `q` can be image `im`'s corners: [`check`], and either a parallelogram or corners the +/// perspective map from its pixels ([`pixel_map`]) places, each within a millionth of `q`'s +/// shortest side plus the rounding error of coordinates as far from the origin as `q`'s. +pub fn check_for(im: &ImageObject, q: &[Point; 4]) -> Result<(), QuadError> { + check(q)?; + if parallelogram(im, q).is_some() { + return Ok(()); + } + let tol = placement_tolerance(q); + let map = pixel_map(im, q); + let placed = rect_corners(pixel_rect(im)).iter().zip(q).all(|(c, want)| map.apply(*c).is_some_and(|p| p.distance(*want) <= tol)); + if placed { Ok(()) } else { Err(QuadError::TooNarrow) } +} + +/// How far a map may place a corner from `q`'s: a millionth of `q`'s shortest side plus the +/// rounding error of coordinates as far from the origin as `q`'s. +fn placement_tolerance(q: &[Point; 4]) -> f64 { + let side = (0..4).map(|i| q[i].distance(q[(i + 1) % 4])).fold(f64::INFINITY, f64::min); + let far = q.iter().map(|p| p.x.abs().max(p.y.abs())).fold(0.0, f64::max); + side * 1e-6 + far * 1e-12 +} + +/// The affine map from `im`'s pixel space that places its corners at `q`, when `q` is a +/// parallelogram (within 1e-9 of the quad's size): the map puts the fourth corner within +/// [`placement_tolerance`] of `q`'s. `None` otherwise. +fn parallelogram(im: &ImageObject, q: &[Point; 4]) -> Option { + let size = q.iter().fold(0.0_f64, |m, p| m.max((*p - q[0]).hypot())); + // The affine map through the other three corners misses the bottom right one by this much. + let gap = (q[0].to_vec2() + q[2].to_vec2() - q[1].to_vec2() - q[3].to_vec2()).hypot(); + if gap > 1e-9 * size || gap > placement_tolerance(q) { + return None; + } + let (w, h) = (f64::from(im.width.max(1)), f64::from(im.height.max(1))); + let (x, y) = ((q[1] - q[0]) / w, (q[3] - q[0]) / h); + let a = Affine::new([x.x, x.y, y.x, y.y, q[0].x, q[0].y]); + a.is_finite().then_some(a) +} + +/// The homography taking the unit square's corners (0,0), (1,0), (1,1), (0,1) to `q`. +fn square_to(q: &[Point; 4]) -> Homography { + let [p0, p1, p2, p3] = *q; + let (sx, sy) = (p0.x - p1.x + p2.x - p3.x, p0.y - p1.y + p2.y - p3.y); + let (dx1, dx2, dy1, dy2) = (p1.x - p2.x, p3.x - p2.x, p1.y - p2.y, p3.y - p2.y); + let den = dx1 * dy2 - dx2 * dy1; + let (g, h) = if den.abs() < 1e-300 { (0.0, 0.0) } else { ((sx * dy2 - dx2 * sy) / den, (dx1 * sy - sx * dy1) / den) }; + Homography([[p1.x - p0.x + g * p1.x, p3.x - p0.x + h * p3.x, p0.x], [p1.y - p0.y + g * p1.y, p3.y - p0.y + h * p3.y, p0.y], [g, h, 1.0]]) +} + +impl Node { + /// This image's distortion: where its pixel rectangle's corners stand (top left, top right, + /// bottom right, bottom left) when they do not make a parallelogram. `None` for an image placed + /// by its transform alone, for anything that is not an image, and for corners a file holds + /// that [`check_for`] refuses (the image is then placed by its transform). + pub fn image_quad(&self) -> Option<[Point; 4]> { + let NodeKind::Image(im) = &self.kind else { return None }; + let q = **self.extras().image_quad.as_ref()?; + check_for(im, &q).is_ok().then_some(q) + } + + /// Whether this is an image with a distortion ([`Self::image_quad`]). + pub fn is_distorted_image(&self) -> bool { + self.image_quad().is_some() + } + + /// Where this image's pixel rectangle's corners stand: its distortion, or its transform's + /// corners. `None` for anything that is not an image. + pub fn image_corners(&self) -> Option<[Point; 4]> { + let NodeKind::Image(im) = &self.kind else { return None }; + Some(self.image_quad().unwrap_or_else(|| rect_corners(pixel_rect(im)).map(|p| im.xf * p))) + } + + /// Place this image's corners at `q` (top left, top right, bottom right, bottom left): by its + /// transform when they make a parallelogram (and the distortion is cleared), else as its + /// distortion. An error, and nothing changes, when `q` fails [`check_for`] or this is not an + /// image. + pub fn set_image_corners(&mut self, q: [Point; 4]) -> Result<(), QuadError> { + let NodeKind::Image(im) = &mut self.kind else { return Err(QuadError::NotConvex) }; + check_for(im, &q)?; + match parallelogram(im, &q) { + Some(xf) => { + im.xf = xf; + if self.extras().image_quad.is_some() { + self.extras_mut().image_quad = None; + } + } + None => self.extras_mut().image_quad = Some(Box::new(q)), + } + Ok(()) + } + + /// The outline of this image's frame on the page: its corners joined by straight lines. + /// `None` for anything that is not an image. + pub fn image_frame(&self) -> Option { + let q = self.image_corners()?; + let mut bp = BezPath::new(); + bp.move_to(q[0]); + for p in &q[1..] { + bp.line_to(*p); + } + bp.close_path(); + Some(bp) + } + + /// The map from this image's pixel space to the page: projective for a distorted image, its + /// transform otherwise. `None` for anything that is not an image. + pub fn image_map(&self) -> Option { + let NodeKind::Image(im) = &self.kind else { return None }; + Some(match self.image_quad() { + Some(q) => pixel_map(im, &q), + None => Homography::from_affine(im.xf), + }) + } +} + +/// The projective map from `im`'s pixel space to the page that puts its corners at `q`. +fn pixel_map(im: &ImageObject, q: &[Point; 4]) -> Homography { + let (w, h) = (f64::from(im.width.max(1)), f64::from(im.height.max(1))); + square_to(q).then_after(&Homography::from_affine(Affine::scale_non_uniform(1.0 / w, 1.0 / h))) +} + +/// How many cells along each side the mesh of a distorted image takes: the fewest (a power of two +/// up to [`MAX_CELLS`]) for which the mesh's triangles, each mapped by the affine map through its +/// corners, stay within `density`'s tolerance of `map` at the middle of every cell and every cell +/// side. An image takes no more cells than it has pixels along its longer side, or +/// [`MIN_CELL_CAP`] when that is more, and no more than leave each cell `density.min_cell` along +/// the longest side of its corners. A perspective that needs more cells than these limits allow is +/// drawn with the cells they allow. +pub fn cells(map: &Homography, im: &ImageObject, density: Density) -> usize { + let (w, h) = (f64::from(im.width.max(1)), f64::from(im.height.max(1))); + let corners = [Point::new(0.0, 0.0), Point::new(w, 0.0), Point::new(w, h), Point::new(0.0, h)].map(|p| map.apply(p)); + let longest = + corners.iter().zip(corners.iter().cycle().skip(1)).filter_map(|(a, b)| Some(a.as_ref()?.distance(*b.as_ref()?))).fold(0.0, f64::max); + let by_size = longest / density.min_cell; + let by_size = if by_size.is_finite() { (by_size as usize).max(1) } else { MAX_CELLS }; + let most = MAX_CELLS.min((im.width.max(im.height) as usize).max(MIN_CELL_CAP)).min(by_size); + let at = |x: f64, y: f64| map.apply(Point::new(x, y)); + let mut k = 1; + while k < most { + let fits = (0..k * k).all(|c| { + let (i, j) = ((c % k) as f64, (c / k) as f64); + let (x0, y0, x1, y1) = (w * i / k as f64, h * j / k as f64, w * (i + 1.0) / k as f64, h * (j + 1.0) / k as f64); + let (Some(a), Some(b), Some(cc), Some(d)) = (at(x0, y0), at(x1, y0), at(x1, y1), at(x0, y1)) else { return false }; + let near = |exact: Option, m: Point| exact.is_some_and(|e| e.distance(m) <= density.tolerance); + near(at((x0 + x1) / 2.0, (y0 + y1) / 2.0), a.midpoint(cc)) + && near(at((x0 + x1) / 2.0, y0), a.midpoint(b)) + && near(at(x1, (y0 + y1) / 2.0), b.midpoint(cc)) + && near(at((x0 + x1) / 2.0, y1), d.midpoint(cc)) + && near(at(x0, (y0 + y1) / 2.0), a.midpoint(d)) + }); + if fits { + break; + } + k *= 2; + } + k.min(most) +} + +/// For a format that cannot clip an image into the pieces of [`distorted_art`]: the affine +/// placement nearest distorted image `n`'s projective map, the one that matches it at the middle +/// of its pixels. `None` when `n` is not a distorted image. +pub fn nearest_affine(n: &Node) -> Option { + let NodeKind::Image(im) = &n.kind else { return None }; + let q = n.image_quad()?; + pixel_map(im, &q).affine_at(pixel_rect(im).center()) +} + +/// Distorted image `n` as the art that draws it in files and print: [`distorted_art_at`] with +/// [`Density::PAGE`]. +pub fn distorted_art(n: &Node) -> Option { + distorted_art_at(n, Density::PAGE) +} + +/// Distorted image `n` as the art that draws it: a clip group, clipped by its corners, around the +/// raster mesh warp ([`crate::live::mesh_warp_image`]) of its pixels through its projective map, +/// with [`cells`] cells along each side for `density` and each piece reaching `density.overlap` +/// past its triangle. The art has `n`'s id but not its name and transparency (which the caller +/// keeps on the object around the art). `None` when `n` is not a distorted image. +pub fn distorted_art_at(n: &Node, density: Density) -> Option { + let NodeKind::Image(im) = &n.kind else { return None }; + let q = n.image_quad()?; + let map = pixel_map(im, &q); + let k = cells(&map, im, density); + let mut plain = n.clone(); + // Whether the image shows is the image's to decide: a hidden source image that a view draws + // anyway (Image Trace's Source Image) draws its art. + plain.visible = true; + // The image's own fills and strokes paint by the image's rules, not on the mesh's group. + plain.appearance = Default::default(); + plain.name = None; + plain.opacity = 1.0; + plain.blend = Default::default(); + plain.isolate = false; + plain.knockout = Default::default(); + plain.knockout_shape = false; + if let Some(e) = plain.extras_if_any() { + e.mask = None; + } + let mut art = crate::live::mesh_warp_image_with(&plain, im, &|p| p, k, n.extras().pixelated, false, Some(density.overlap)); + // The pieces along the image's edges reach past its corners too: the corners clip them. + let mut edge = Node::path(n.id, PathData::single(SubPath::polyline(&q, true)), Appearance::default()); + if let NodeKind::Path { clipping, .. } = &mut edge.kind { + *clipping = true; + } + let pieces = std::mem::replace(&mut art.kind, NodeKind::Group { children: vec![], clip: true }); + let mut mesh = art.clone(); + mesh.kind = pieces; + art.knockout = Default::default(); + art.kind = NodeKind::Group { children: vec![Arc::new(edge), Arc::new(mesh)], clip: true }; + Some(art) +} + +/// The pieces of [`distorted_art_at`]'s art: the children of its mesh group. +pub fn distorted_pieces(art: &Node) -> &[Arc] { + art.children().and_then(|c| c.get(1)).and_then(|m| m.children()).map_or(&[], Vec::as_slice) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::NodeId; + + fn image(w: u32, h: u32) -> Node { + let im = ImageObject { key: "k".into(), width: w, height: h, xf: Affine::IDENTITY, link: None, placement: Default::default(), pixels: None }; + Node::new(NodeId(1), NodeKind::Image(Box::new(im))) + } + + fn pts(v: [(f64, f64); 4]) -> [Point; 4] { + v.map(|(x, y)| Point::new(x, y)) + } + + #[test] + fn a_convex_quad_either_way_round_passes_and_a_fold_or_line_does_not() { + assert_eq!(check(&pts([(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)])), Ok(())); + assert_eq!(check(&pts([(0.0, 0.0), (0.0, 10.0), (10.0, 10.0), (10.0, 0.0)])), Ok(())); + // Two corners swapped: the sides cross. + assert_eq!(check(&pts([(0.0, 0.0), (10.0, 0.0), (0.0, 10.0), (10.0, 10.0)])), Err(QuadError::NotConvex)); + // A dent. + assert_eq!(check(&pts([(0.0, 0.0), (10.0, 0.0), (2.0, 2.0), (0.0, 10.0)])), Err(QuadError::NotConvex)); + // Three on a line, and two corners at one point. + assert_eq!(check(&pts([(0.0, 0.0), (5.0, 0.0), (10.0, 0.0), (0.0, 10.0)])), Err(QuadError::NotConvex)); + assert_eq!(check(&pts([(0.0, 0.0), (0.0, 0.0), (10.0, 10.0), (0.0, 10.0)])), Err(QuadError::NotConvex)); + assert_eq!(check(&pts([(f64::NAN, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)])), Err(QuadError::NotFinite)); + } + + /// A convex quad with one edge so short that the perspective map through it cannot place the + /// other corners: refused when set, and a file's copy of it leaves the image undistorted. + #[test] + fn corners_the_perspective_map_cannot_place_are_refused() { + let q = pts([(50.0, 0.0), (50.000000005, 0.0), (100.0, 100.0), (0.0, 100.0)]); + assert_eq!(check(&q), Ok(())); + let mut n = image(100, 100); + assert_eq!(n.set_image_corners(q), Err(QuadError::TooNarrow)); + assert!(n.extras().image_quad.is_none()); + n.extras_mut().image_quad = Some(Box::new(q)); + assert_eq!(n.image_quad(), None); + assert!(distorted_art(&n).is_none()); + assert_eq!(n.image_corners(), Some(rect_corners(Rect::new(0.0, 0.0, 100.0, 100.0)))); + } + + #[test] + fn a_parallelogram_goes_into_the_transform_and_other_corners_into_the_quad() { + let mut n = image(100, 50); + n.set_image_corners(pts([(10.0, 0.0), (110.0, 10.0), (100.0, 60.0), (0.0, 50.0)])).unwrap(); + assert_eq!(n.image_quad(), None); + let NodeKind::Image(im) = &n.kind else { panic!("an image") }; + assert!((im.xf * Point::new(100.0, 50.0)).distance(Point::new(100.0, 60.0)) < 1e-9); + let q = pts([(40.0, 0.0), (60.0, 0.0), (100.0, 100.0), (0.0, 100.0)]); + n.set_image_corners(q).unwrap(); + assert_eq!(n.image_quad(), Some(q)); + assert_eq!(n.image_corners(), Some(q)); + let map = n.image_map().unwrap(); + for (c, want) in rect_corners(Rect::new(0.0, 0.0, 100.0, 50.0)).iter().zip(q) { + assert!(map.apply(*c).unwrap().distance(want) < 1e-9, "{c:?}"); + } + // Back to a rectangle: the quad is cleared. + n.set_image_corners(pts([(0.0, 0.0), (100.0, 0.0), (100.0, 50.0), (0.0, 50.0)])).unwrap(); + assert!(n.extras().image_quad.is_none()); + } + + /// Corners whose gap from a parallelogram is tiny next to the quad's size but not next to its + /// shortest side stay a distortion: the affine map would put the bottom right corner twice as + /// low as asked. + #[test] + fn corners_the_affine_map_misses_stay_a_distortion() { + let mut n = image(100, 100); + let q = pts([(0.0, 0.0), (100000.0, 0.0), (100000.0, 0.00005), (0.0, 0.0001)]); + n.set_image_corners(q).unwrap(); + assert_eq!(n.image_quad(), Some(q)); + let map = n.image_map().unwrap(); + for (c, want) in rect_corners(Rect::new(0.0, 0.0, 100.0, 100.0)).iter().zip(q) { + assert!(map.apply(*c).unwrap().distance(want) < 1e-9, "{c:?}"); + } + } + + /// A scale that squeezes valid corners past what a perspective map can place leaves the image + /// at the placement nearest them, scaled, not at the rectangle it had before. + #[test] + fn a_scale_past_the_perspective_limit_keeps_the_nearest_placement() { + let mut n = image(100, 100); + n.set_image_corners(pts([(0.0, 0.0), (100.0, 0.0), (200.0, 2e-7), (0.0, 2e-7)])).unwrap(); + assert!(n.is_distorted_image()); + n.transform(Affine::scale_non_uniform(1.0, 0.25), false); + assert!(n.extras().image_quad.is_none()); + let b = n.geometric_bounds().unwrap(); + assert!(b.height() < 1e-6 && (b.width() - 150.0).abs() < 60.0, "{b:?}"); + } + + /// A file's corners that the image cannot take are dropped as it is read, so a later scale + /// that would make them valid leaves the image placed by its transform; a list of three + /// points is dropped too, and the rest of the image is read. + #[test] + fn corners_a_file_holds_that_are_refused_or_not_four_are_dropped_as_it_is_read() { + let mut n = image(100, 100); + n.extras_mut().image_quad = Some(Box::new(pts([(0.0, 0.0), (100.0, 0.0), (200.0, 5e-8), (0.0, 5e-8)]))); + assert_eq!(n.image_quad(), None); + let mut read: Node = serde_json::from_value(serde_json::to_value(&n).unwrap()).unwrap(); + assert!(read.extras().image_quad.is_none()); + read.transform(Affine::scale_non_uniform(1.0, 4.0), false); + assert!(!read.is_distorted_image()); + assert_eq!(read.geometric_bounds(), Some(Rect::new(0.0, 0.0, 100.0, 400.0))); + let mut v = serde_json::to_value(&n).unwrap(); + v["image_quad"] = serde_json::json!([[0.0, 0.0], [10.0, 0.0], [10.0, 10.0]]); + let read: Node = serde_json::from_value(v).unwrap(); + assert!(read.extras().image_quad.is_none()); + assert!(matches!(read.kind, NodeKind::Image(_))); + // Past a fourth point the rest is skipped without being read as points. + for extra in [serde_json::json!([5.0, 5.0]), serde_json::json!("not a point")] { + let mut v = serde_json::to_value(&n).unwrap(); + v["image_quad"] = serde_json::json!([[40.0, 0.0], [60.0, 0.0], [100.0, 100.0], [0.0, 100.0], extra, {"x": 1}]); + let read: Node = serde_json::from_value(v).unwrap(); + assert!(read.extras().image_quad.is_none()); + } + // Valid corners read back. + let q = pts([(40.0, 0.0), (60.0, 0.0), (100.0, 100.0), (0.0, 100.0)]); + n.set_image_corners(q).unwrap(); + let read: Node = serde_json::from_value(serde_json::to_value(&n).unwrap()).unwrap(); + assert_eq!(read.image_quad(), Some(q)); + } + + #[test] + fn refused_corners_change_nothing_and_a_bad_quad_in_a_file_is_ignored() { + let mut n = image(10, 10); + let before = n.clone(); + assert!(n.set_image_corners(pts([(0.0, 0.0), (10.0, 0.0), (0.0, 10.0), (10.0, 10.0)])).is_err()); + assert_eq!(n, before); + n.extras_mut().image_quad = Some(Box::new(pts([(0.0, 0.0), (10.0, 0.0), (0.0, 10.0), (10.0, 10.0)]))); + assert_eq!(n.image_quad(), None); + assert_eq!(n.image_corners(), Some(pts([(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)]))); + } + + #[test] + fn the_mesh_is_as_fine_as_the_perspective_needs() { + let mut n = image(400, 400); + n.set_image_corners(pts([(10.0, 0.0), (400.0, 5.0), (390.0, 400.0), (0.0, 395.0)])).unwrap(); + let NodeKind::Image(im) = n.kind.clone() else { panic!("an image") }; + let gentle = cells(&n.image_map().unwrap(), &im, Density::PAGE); + n.set_image_corners(pts([(160.0, 0.0), (240.0, 0.0), (400.0, 400.0), (0.0, 400.0)])).unwrap(); + let strong = cells(&n.image_map().unwrap(), &im, Density::PAGE); + assert!(gentle < strong && strong <= MAX_CELLS, "{gentle} {strong}"); + // Three by two pixels drawn as large still bend, in up to MIN_CELL_CAP cells. + let mut tiny = image(3, 2); + tiny.set_image_corners(pts([(160.0, 0.0), (240.0, 0.0), (400.0, 400.0), (0.0, 400.0)])).unwrap(); + let NodeKind::Image(tim) = &tiny.kind else { panic!("an image") }; + assert_eq!(cells(&tiny.image_map().unwrap(), tim, Density::PAGE), MIN_CELL_CAP.min(strong)); + // Drawn small, the same corners take only cells of at least 4 pixels: their longest side, + // about 431 pt, is about 17 pixels at 1/25 px a point, room for 4 cells. + let map = n.image_map().unwrap(); + assert!(cells(&map, &im, Density::at_scale(1.0 / 25.0)) <= 4); + // Drawn large, a quarter of a pixel is finer than 0.05 pt, so no fewer cells than on the page. + assert!(cells(&map, &im, Density::at_scale(8.0)) >= strong); + // Each cell of the page's mesh is at least 2 pt along the longest side: about 32 pt takes + // 16 at most. + let mut small = image(400, 400); + small.set_image_corners(pts([(12.0, 0.0), (18.0, 0.0), (30.0, 30.0), (0.0, 30.0)])).unwrap(); + assert!(cells(&small.image_map().unwrap(), &im, Density::PAGE) <= 16); + } + + /// Each piece of the art reaches the density's overlap past its triangle, and the corners clip + /// the art, so nothing draws outside them. + #[test] + fn the_pieces_overlap_and_the_corners_clip_them() { + let mut n = image(100, 100); + let q = pts([(40.0, 0.0), (60.0, 0.0), (100.0, 100.0), (0.0, 100.0)]); + n.set_image_corners(q).unwrap(); + let art = distorted_art_at(&n, Density { tolerance: 1.0, min_cell: 1.0, overlap: 3.0 }).unwrap(); + let Some([edge, _]) = art.children().map(Vec::as_slice) else { panic!("an edge and a mesh") }; + assert!(matches!(edge.kind, NodeKind::Path { clipping: true, .. })); + assert_eq!(edge.geometric_bounds(), Some(Rect::new(0.0, 0.0, 100.0, 100.0))); + let pieces = distorted_pieces(&art); + assert!(pieces.len() >= 2); + // The first piece's clip triangle reaches 3 pt past the image's top left corner. + let Some([clip, _]) = pieces[0].children().map(Vec::as_slice) else { panic!("a clip and an image") }; + let b = clip.geometric_bounds().unwrap(); + assert!(b.y0 < -2.0, "{b:?}"); + } + + #[test] + fn the_art_puts_the_pixel_corners_on_the_quad() { + let mut n = image(100, 100); + n.opacity = 0.5; + let q = pts([(40.0, 0.0), (60.0, 0.0), (100.0, 100.0), (0.0, 100.0)]); + n.set_image_corners(q).unwrap(); + let art = distorted_art(&n).unwrap(); + assert_eq!(art.opacity, 1.0); + let mut corners_seen = [false; 4]; + art.walk(&mut |c| { + if let NodeKind::Image(im) = &c.kind { + for (i, (p, want)) in rect_corners(Rect::new(0.0, 0.0, 100.0, 100.0)).iter().zip(q).enumerate() { + if (im.xf * *p).distance(want) < 1e-9 { + corners_seen[i] = true; + } + } + } + }); + assert_eq!(corners_seen, [true; 4]); + assert!(distorted_art(&image(4, 4)).is_none()); + // A hidden image that a view draws anyway gives art that draws. + n.visible = false; + assert!(distorted_art(&n).unwrap().visible); + // The image's own fills and strokes stay off the mesh's group. + let stroke = vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK); + n.appearance = crate::Appearance::basic(vectorcraft_color::Paint::None, stroke, 1.0).into(); + assert!(distorted_art(&n).unwrap().appearance.items.is_empty()); + } + + #[test] + fn deep_expansion_reaches_a_distorted_image_inside_a_group() { + let mut n = image(100, 100); + n.set_image_corners(pts([(40.0, 0.0), (60.0, 0.0), (100.0, 100.0), (0.0, 100.0)])).unwrap(); + let inner = Node::new(NodeId(2), NodeKind::Group { children: vec![std::sync::Arc::new(n)], clip: false }); + let outer = Node::new(NodeId(3), NodeKind::Group { children: vec![std::sync::Arc::new(inner)], clip: false }); + let out = crate::live::expand_deep(&outer, None); + let mut distorted = 0; + let mut pieces = 0; + out.walk(&mut |c| { + distorted += usize::from(c.is_distorted_image()); + pieces += usize::from(matches!(c.kind, NodeKind::Image(_))); + }); + assert_eq!(distorted, 0); + assert!(pieces > 1, "{pieces}"); + } + + /// A distorted image with an effect of its own stays an image with its appearance when the + /// art around it is expanded, so the effect still applies where the art is drawn. + #[test] + fn deep_expansion_keeps_a_distorted_image_with_its_own_appearance() { + let mut n = image(100, 100); + n.set_image_corners(pts([(40.0, 0.0), (60.0, 0.0), (100.0, 100.0), (0.0, 100.0)])).unwrap(); + let effect = crate::Effect { id: "distort.transform".into(), params: serde_json::json!({"moveH": 40}), visible: true }; + n.appearance = crate::Appearance { effects: vec![effect], ..Default::default() }.into(); + let inner = Node::new(NodeId(2), NodeKind::Group { children: vec![std::sync::Arc::new(n.clone())], clip: false }); + let outer = Node::new(NodeId(3), NodeKind::Group { children: vec![std::sync::Arc::new(inner)], clip: false }); + let out = crate::live::expand_deep(&outer, None); + let mut kept = vec![]; + out.walk(&mut |c| { + if c.is_distorted_image() { + kept.push(c.appearance.clone()); + } + }); + assert_eq!(kept, vec![n.appearance]); + } +} diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 3f53bc693f..0578474c99 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -22,6 +22,7 @@ pub mod graph; mod halftone_radii; pub mod hit; mod id_index; +pub mod image_quad; pub use id_index::{path_lookups, tree_walks}; pub mod inks; mod inline; diff --git a/crates/doc/src/live.rs b/crates/doc/src/live.rs index 337634db2e..3813b24950 100644 --- a/crates/doc/src/live.rs +++ b/crates/doc/src/live.rs @@ -57,11 +57,11 @@ pub use envelope::{ envelope_content_boxes, envelope_content_boxes_with, envelope_expand, envelope_frame, envelope_grid, envelope_mapper, envelope_of, envelope_overlay, envelope_stroke_margin, set_type_ink, smooth_handles, warp_grid, }; -pub(crate) use expand::max_outset; pub use expand::{ Hooks, MAX_GENERATED, Outliner, PatternTiles, affine_near, expand_deep, expand_deep_hooks, expand_live, expand_live_hooks, expand_live_with, - expanded_group, expanded_group_hooks, is_live, mesh_quad_nodes, mesh_warp_cost, mesh_warp_image, subtree_has_live, + expanded_group, expanded_group_hooks, is_drawn_live, is_live, mesh_quad_nodes, mesh_warp_cost, mesh_warp_image, subtree_has_live, }; +pub(crate) use expand::{max_outset, mesh_warp_image_with}; #[cfg(test)] use mesh::grid_eval; pub use mesh::{Coons, GradientMesh, MeshAppearance, MeshPiece, MeshPoint, MeshQuad, default_fidelity, grid_points, nodes_bounds}; diff --git a/crates/doc/src/live/expand.rs b/crates/doc/src/live/expand.rs index d87d7a28c4..e1eb3acc3d 100644 --- a/crates/doc/src/live/expand.rs +++ b/crates/doc/src/live/expand.rs @@ -212,12 +212,26 @@ pub fn mesh_warp_cost(cells: usize) -> usize { /// partly transparent image keeps its own alpha there. More cells than [`MAX_GENERATED`] objects /// allow make an empty group. pub fn mesh_warp_image(n: &Node, im: &ImageObject, f: &dyn Fn(Point) -> Point, cells: usize, pixelated: bool, masked: bool) -> Node { + mesh_warp_image_with(n, im, f, cells, pixelated, masked, None) +} + +/// [`mesh_warp_image`], each piece reaching `overlap` points past its edges when given. +pub(crate) fn mesh_warp_image_with( + n: &Node, + im: &ImageObject, + f: &dyn Fn(Point) -> Point, + cells: usize, + pixelated: bool, + masked: bool, + overlap: Option, +) -> Node { let k = cells.max(1); let mut g = n.clone(); g.kind = NodeKind::Group { children: vec![], clip: false }; g.knockout = crate::Knockout::On; if let Some(e) = g.extras_if_any() { e.colorize = None; + e.image_quad = None; } if mesh_warp_cost(k) > MAX_GENERATED { return g; @@ -228,24 +242,31 @@ pub fn mesh_warp_image(n: &Node, im: &ImageObject, f: &dyn Fn(Point) -> Point, c let color_mask = n.extras().color_mask.clone(); let (pw, ph) = (im.width as f64, im.height as f64); let at = |i: usize, j: usize| Point::new(pw * i as f64 / k as f64, ph * j as f64 / k as f64); + // A distorted image's pixels reach the page through its projective map. + let to_page = n.image_map().filter(|_| n.is_distorted_image()); + let place = |p: Point| to_page.and_then(|m| m.apply(p)).unwrap_or(im.xf * p); let mut pieces = Vec::with_capacity(2 * k * k); for j in 0..k { for i in 0..k { let s = [at(i, j), at(i + 1, j), at(i + 1, j + 1), at(i, j + 1)]; - let d = s.map(|p| f(im.xf * p)); + let d = s.map(|p| f(place(p))); for t in [[0, 1, 2], [0, 2, 3]] { let (st, dt) = (t.map(|v| s[v]), t.map(|v| d[v])); let Some(xf) = affine_between(st, dt) else { continue }; let c = Point::new((dt[0].x + dt[1].x + dt[2].x) / 3.0, (dt[0].y + dt[1].y + dt[2].y) / 3.0); - let grow = (dt[0].distance(dt[1]).max(dt[1].distance(dt[2])) * 0.02).min(0.5); - let tri: Vec = dt - .iter() - .map(|p| { - let v = *p - c; - let len = v.hypot(); - if len > 1e-12 { *p + v * (grow / len) } else { *p } - }) - .collect(); + let tri: Vec = match overlap { + Some(g) => grown_triangle(dt, g), + None => { + let grow = (dt[0].distance(dt[1]).max(dt[1].distance(dt[2])) * 0.02).min(0.5); + dt.iter() + .map(|p| { + let v = *p - c; + let len = v.hypot(); + if len > 1e-12 { *p + v * (grow / len) } else { *p } + }) + .collect() + } + }; let shape = PathData::single(SubPath::polyline(&tri, true)); let mut image = Node::new(n.id, NodeKind::Image(Box::new(ImageObject { xf, ..im.clone() }))); image.extras_mut().pixelated = pixelated; @@ -274,6 +295,23 @@ pub fn mesh_warp_image(n: &Node, im: &ImageObject, f: &dyn Fn(Point) -> Point, c g } +/// Triangle `t` with each side moved `g` outward: `t` scaled about its incenter. A corner moves +/// at most 8 `g`, so a very thin triangle's sides move less than `g`. +fn grown_triangle(t: [Point; 3], g: f64) -> Vec { + let side = |i: usize| t[(i + 1) % 3].distance(t[(i + 2) % 3]); + let (a, b, c) = (side(0), side(1), side(2)); + let perimeter = a + b + c; + let area = ((t[1] - t[0]).cross(t[2] - t[0]) / 2.0).abs(); + if !(perimeter > 1e-12 && area > 0.0 && g.is_finite() && g > 0.0) { + return t.to_vec(); + } + let center = Point::new((a * t[0].x + b * t[1].x + c * t[2].x) / perimeter, (a * t[0].y + b * t[1].y + c * t[2].y) / perimeter); + let r = 2.0 * area / perimeter; + let far = t.iter().map(|p| p.distance(center)).fold(0.0, f64::max); + let grow = (g / r).min(8.0 * g / far.max(1e-12)); + t.iter().map(|p| center + (*p - center) * (1.0 + grow)).collect() +} + /// Distort Pattern Fills: path or compound path `n` with each visible pattern fill turned into the /// tiles it paints in a clip group shaped like `n` (with the fill's opacity and blend mode), its /// other fills and strokes on copies of it, in paint order, under `n`'s transparency. `None` @@ -353,6 +391,13 @@ pub fn is_live(n: &Node) -> bool { ) } +/// Is this drawn and written as evaluated art: a live object ([`is_live`]) or a distorted image +/// ([`Node::image_quad`]), whose art is [`crate::image_quad::distorted_art`]. Effects and +/// container paint treat a distorted image as an image, not as live art. +pub fn is_drawn_live(n: &Node) -> bool { + is_live(n) || n.is_distorted_image() +} + /// Mesh tessellation as flat-filled paths (no stroke): each patch cut `n`×`n`, its quads joined /// where the colour hardly changes ([`GradientMesh::pieces`]). pub fn mesh_quad_nodes(m: &GradientMesh, n: usize) -> Vec { @@ -388,6 +433,7 @@ pub fn expand_live_hooks(n: &Node, hooks: Hooks) -> Vec { NodeKind::Repeat(r) => r.expand(hooks.symbols), NodeKind::PlacedDocument(p) => p.art(n), NodeKind::Intertwine { children } => crate::intertwine::expand(children), + NodeKind::Image(_) => vec![crate::image_quad::distorted_art(n).unwrap_or_else(|| n.clone())], _ => vec![n.clone()], } } @@ -429,7 +475,7 @@ pub fn expand_deep(n: &Node, outline: Outliner) -> Node { /// expands to nothing. pub fn expand_deep_hooks(n: &Node, hooks: Hooks) -> Node { let _generating = Generating::enter(); - let mut out = if is_live(n) { + let mut out = if is_drawn_live(n) { let g = expanded_group_hooks(n, hooks); if !Generating::charge(g.count()) { return Node::new(n.id, NodeKind::Group { children: vec![], clip: false }); @@ -440,7 +486,12 @@ pub fn expand_deep_hooks(n: &Node, hooks: Hooks) -> Node { }; if let Some(ch) = out.children_mut() { for c in ch.iter_mut() { - if subtree_has_live(c) { + // A distorted image with fills, strokes or effects of its own stays an image: whoever + // draws the art draws it with them, as it draws a distorted image anywhere else. + if c.is_distorted_image() && !(c.appearance.items.is_empty() && c.appearance.effects.is_empty()) { + continue; + } + if subtree_has_drawn_live(c) { *c = Arc::new(expand_deep_hooks(c, hooks)); } } @@ -497,6 +548,13 @@ pub fn subtree_has_live(n: &Node) -> bool { any } +/// Does `n` or any descendant draw as evaluated art ([`is_drawn_live`])? +fn subtree_has_drawn_live(n: &Node) -> bool { + let mut any = false; + n.walk(&mut |c| any |= is_drawn_live(c)); + any +} + /// Largest stroke outset in a subtree (for visual bounds of envelopes, blends and repeats, and the /// reach of symbol art), type's character strokes included as type's own visual bounds measure them /// ([`crate::TextObject::char_stroke_outset`]): in an envelope they paint at their own weight diff --git a/crates/doc/src/node/clip.rs b/crates/doc/src/node/clip.rs index b26fa52e1c..25f716460e 100644 --- a/crates/doc/src/node/clip.rs +++ b/crates/doc/src/node/clip.rs @@ -44,8 +44,12 @@ impl Node { } } NodeKind::Image(im) => { - let frame = shapes::rectangle(Rect::new(0.0, 0.0, im.width as f64, im.height as f64)).transformed(im.xf); - out.push((frame.to_bezpath(), FillRule::NonZero)); + // A distorted image's frame joins its corners. + let frame = match self.image_frame().filter(|_| self.is_distorted_image()) { + Some(bp) => bp, + None => shapes::rectangle(Rect::new(0.0, 0.0, im.width as f64, im.height as f64)).transformed(im.xf).to_bezpath(), + }; + out.push((frame, FillRule::NonZero)); } NodeKind::PlacedDocument(p) => { let frame = shapes::rectangle(p.natural()).transformed(p.xf); diff --git a/crates/doc/src/node/extras.rs b/crates/doc/src/node/extras.rs index f953deda71..439d3605fd 100644 --- a/crates/doc/src/node/extras.rs +++ b/crates/doc/src/node/extras.rs @@ -3,6 +3,7 @@ use super::kind::NodeKind; use super::live_shape::LiveShape; use super::opacity::OpacityMask; use super::{Node, PathData}; +use vectorcraft_geom::Point; /// The parts of a [`Node`] that few objects have: kept out of line, so that the nodes without /// them stay small ([`Node::extras`]). @@ -87,6 +88,10 @@ pub struct NodeExtras { /// are applied, one path or compound path per fill and stroke: as the clipping path of a clip group it paints /// those pieces as the path paints its fills and strokes ([`Node::clip_paint`]). pub clip_pieces: bool, + /// As an image after Perspective Distort or Free Distort, where its pixel rectangle's corners + /// (top left, top right, bottom right, bottom left in pixel space) stand on the page when they + /// do not make a parallelogram, which its transform alone could place ([`crate::image_quad`]). + pub image_quad: Option>, } /// No extras: what [`Node::extras`] gives for a node without any. @@ -118,6 +123,7 @@ pub(super) static NO_EXTRAS: NodeExtras = NodeExtras { color_mask: None, warp_piece: false, clip_pieces: false, + image_quad: None, }; /// A node's [`NodeExtras`], if it has any ([`Node::extras`]). Extras that are all unset equal diff --git a/crates/doc/src/node/ops.rs b/crates/doc/src/node/ops.rs index e83aae1b09..20dae6ec4b 100644 --- a/crates/doc/src/node/ops.rs +++ b/crates/doc/src/node/ops.rs @@ -386,6 +386,10 @@ impl Node { .filter(|c| c.visible || !matches!(self.kind, NodeKind::Layer { .. })) .fold(None, |acc, c| vectorcraft_geom::union_opt(acc, c.geometric(symbols))), NodeKind::Text(t) => self.projected(t.bounds()), + // A distorted image is bounded by its corners. + NodeKind::Image(_) if self.is_distorted_image() => { + self.image_corners().map(|q| q[1..].iter().fold(Rect::from_points(q[0], q[0]), |r, p| r.union_pt(*p))) + } NodeKind::Image(im) => Some(im.xf.transform_rect_bbox(Rect::new(0.0, 0.0, im.width as f64, im.height as f64))), NodeKind::SymbolInstance { symbol, xf } => { let art = symbols.and_then(|s| s.art(symbol)).map_or(SYMBOL_SQUARE, |a| a.geometric); @@ -528,6 +532,9 @@ impl Node { } // The path the objects are attached to, before it is transformed. let on_path_before = self.on_path_data().cloned(); + // A distorted image's placement nearest its corners, before they are transformed (`None` + // within when its stored corners are refused, and `None` for anything else). + let image_before = self.extras().image_quad.is_some().then(|| crate::image_quad::nearest_affine(self)); if !self.is_layer() { self.bbox_angle = crate::orient::transformed_angle(self.bbox_angle, a); } @@ -637,7 +644,8 @@ impl Node { { Arc::make_mut(&mut m.art).transform_scaled(a, sc); } - // The area where an Intertwine member is drawn over the others moves with it. + // The area where an Intertwine member is drawn over the others moves with it, and so do a + // distorted image's corners. if let Some(e) = self.extras_if_any() { if let Some(area) = e.intertwine.as_mut() { area.transform(a); @@ -645,6 +653,23 @@ impl Node { for area in &mut e.intertwine_tiers { area.transform(a); } + if let Some(q) = e.image_quad.as_mut() { + for p in q.iter_mut() { + *p = a * *p; + } + } + } + // Corners that a scale squeezes past what a perspective map can place (or that were + // refused already) leave the image placed by its transform: for valid corners, the + // placement that was nearest them, transformed, rather than the rectangle it had before + // it was distorted. + if let Some(before) = image_before + && self.image_quad().is_none() + { + if let (Some(near), NodeKind::Image(im)) = (before, &mut self.kind) { + im.xf = a * near; + } + self.extras_mut().image_quad = None; } } diff --git a/crates/doc/src/node/wire.rs b/crates/doc/src/node/wire.rs index 2b473f0cc7..9027c80b09 100644 --- a/crates/doc/src/node/wire.rs +++ b/crates/doc/src/node/wire.rs @@ -59,6 +59,7 @@ impl Serialize for Node { e.color_mask.is_none(), is_default(&e.warp_piece), is_default(&e.clip_pieces), + e.image_quad.is_none(), ]; let mut st = s.serialize_struct("Node", skips.iter().filter(|s| !**s).count())?; let mut skip = skips.into_iter(); @@ -106,6 +107,7 @@ impl Serialize for Node { field!("color_mask", &e.color_mask); field!("warp_piece", &e.warp_piece); field!("clip_pieces", &e.clip_pieces); + field!("image_quad", &e.image_quad); st.end() } } @@ -257,10 +259,55 @@ pub(super) struct NodeWire { warp_piece: bool, #[serde(default)] clip_pieces: bool, + #[serde(default, deserialize_with = "image_corners")] + image_quad: Option>, +} + +/// A distorted image's corners as a file holds them: a list of exactly four points, else none (the +/// image is then placed by its transform). At most five points of a longer list are kept while it +/// is read. +fn image_corners<'de, D: serde::Deserializer<'de>>(d: D) -> Result>, D::Error> { + use vectorcraft_geom::Point; + struct Corners; + impl<'de> serde::de::Visitor<'de> for Corners { + type Value = Option>; + fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { + f.write_str("a list of points") + } + fn visit_none(self) -> Result { + Ok(None) + } + fn visit_unit(self) -> Result { + Ok(None) + } + fn visit_some>(self, d: D) -> Result { + d.deserialize_seq(Corners) + } + fn visit_seq>(self, mut seq: A) -> Result { + let mut points = Vec::with_capacity(4); + while points.len() < 4 + && let Some(p) = seq.next_element::()? + { + points.push(p); + } + // A fifth entry drops the field, so the rest is skipped without decoding it. + let mut extra = false; + while seq.next_element::()?.is_some() { + extra = true; + } + Ok(if extra { None } else { <[Point; 4]>::try_from(points).ok().map(Box::new) }) + } + } + d.deserialize_option(Corners) } impl From for Node { fn from(w: NodeWire) -> Self { + // Corners an image cannot take are dropped, so a later transform cannot make them its own. + let image_quad = match &w.kind { + NodeKind::Image(im) => w.image_quad.filter(|q| crate::image_quad::check_for(im, q).is_ok()), + _ => None, + }; let extras = NodeExtras { mask: w.mask, trace: w.trace, @@ -289,6 +336,7 @@ impl From for Node { color_mask: w.color_mask, warp_piece: w.warp_piece, clip_pieces: w.clip_pieces, + image_quad, }; Node { id: w.id, diff --git a/crates/doc/src/tests.rs b/crates/doc/src/tests.rs index dcbcd87028..0801187b6d 100644 --- a/crates/doc/src/tests.rs +++ b/crates/doc/src/tests.rs @@ -686,6 +686,43 @@ fn reid_gives_fresh_ids() { assert!(!ids.contains(&a) && !ids.contains(&b)); } +/// A copy of a node in the document takes the Symbol Set Density recorded for it; a node from +/// another document with the same id does not. +#[test] +fn reid_copies_the_set_density_of_the_documents_own_node() { + let (mut d, a, _) = doc_with_rects(); + d.unknown.insert(Document::SYMBOL_SET_DENSITY_KEY.into(), serde_json::json!({ a.0.to_string(): 2.0 })); + let density = |d: &Document, id: NodeId| d.unknown[Document::SYMBOL_SET_DENSITY_KEY].get(id.0.to_string()).cloned(); + let own = d.node(a).cloned().unwrap(); + let copy = d.reid(&own); + assert_eq!(density(&d, copy.id), Some(serde_json::json!(2.0))); + let foreign = Node::group(a, vec![]); + let copy = d.reid(&foreign); + assert_eq!(density(&d, copy.id), None); +} + +/// A pasted copy and its descendants take the densities recorded at Copy, and none where Copy +/// recorded none, whatever [`Document::reid`] found for an identical node in the document. +#[test] +fn carry_set_densities_gives_the_densities_recorded_at_copy() { + let (mut d, a, b) = doc_with_rects(); + d.unknown.insert(Document::SYMBOL_SET_DENSITY_KEY.into(), serde_json::json!({ a.0.to_string(): 2.0 })); + let density = |d: &Document, id: NodeId| d.unknown[Document::SYMBOL_SET_DENSITY_KEY].get(id.0.to_string()).cloned(); + let (na, nb) = (d.node(a).cloned().unwrap(), d.node(b).cloned().unwrap()); + // Copy recorded nothing for `a`: the copy reid gave a density loses it. + let copy = d.reid(&na); + assert_eq!(density(&d, copy.id), Some(serde_json::json!(2.0))); + d.carry_set_densities(&na, ©, &Default::default()); + assert_eq!(density(&d, copy.id), None); + // Copy recorded 7 for `b` inside a group: the group's copy has none, and `b`'s copy has 7. + let g = d.alloc_id(); + let group = Node::group(g, vec![Arc::new(nb)]); + let copy = d.reid(&group); + d.carry_set_densities(&group, ©, &[(b, serde_json::json!(7.0))].into_iter().collect()); + let inner = copy.children().unwrap()[0].id; + assert_eq!((density(&d, copy.id), density(&d, inner)), (None, Some(serde_json::json!(7.0)))); +} + #[test] fn setup_round_trips_and_old_files_load() { let (mut d, _, _) = doc_with_rects(); diff --git a/crates/doc/src/text.rs b/crates/doc/src/text.rs index c6a9860189..107ac1dab9 100644 --- a/crates/doc/src/text.rs +++ b/crates/doc/src/text.rs @@ -38,7 +38,7 @@ pub use tabs_lists::{ Bullet, DEFAULT_TAB_INTERVAL, LIST_HANGING_INDENT, LIST_LEVEL_INDENT, LIST_LEVELS, ListAlign, ListCounts, MAX_LIST_START, NumberStyle, ParaList, TabAlign, TabStop, }; -pub use wrap::{resolve_wrap, wrap_outline, wrap_sources, wrap_work}; +pub use wrap::{resolve_wrap, wrap_copy_units, wrap_outline, wrap_sources, wrap_work}; /// A text object. `runs` split into paragraphs at `\n`. /// diff --git a/crates/doc/src/text/object.rs b/crates/doc/src/text/object.rs index 746c0b69d5..c0e305aeeb 100644 --- a/crates/doc/src/text/object.rs +++ b/crates/doc/src/text/object.rs @@ -451,12 +451,25 @@ impl TextObject { /// fractions of the path. False, changing nothing, for other type, when the anchor doesn't /// exist, a degenerate `xf` or a path that would not be finite. pub fn set_path_handle(&mut self, (si, ai): (usize, usize), out: bool, pos: Point, independent: bool) -> bool { + self.set_path_handle_with_symmetry((si, ai), out, pos, independent, false) + } + /// [`Self::set_path_handle`] with an optional mirror of the opposite handle about the anchor + /// in document space, preserving the anchor kind. `independent` takes precedence, and at an + /// open end of the path, where no segment leaves the anchor on that side, the handle moves as + /// it would without `symmetric`. Both handles are edited in one reshape, using the same validated + /// document-to-text map. + pub fn set_path_handle_with_symmetry(&mut self, (si, ai): (usize, usize), out: bool, pos: Point, independent: bool, symmetric: bool) -> bool { let xf = self.xf; matches!(self.kind, TextKind::OnPath { .. }) && self.reshape_local(|path, to_text| { + let mirror = symmetric && !independent && path.subpaths.get(si).is_some_and(|sp| sp.has_segment(ai, !out)); let Some(a) = path.anchor_mut(si, ai) else { return false }; let mut drawn = a.transform(xf); drawn.set_handle(out, pos, independent); + if mirror { + let opposite = drawn.p - (pos - drawn.p); + if out { drawn.h_in = opposite } else { drawn.h_out = opposite } + } *a = drawn.transform(to_text); true }) diff --git a/crates/doc/src/text/tests.rs b/crates/doc/src/text/tests.rs index 63b763423d..1a3229138e 100644 --- a/crates/doc/src/text/tests.rs +++ b/crates/doc/src/text/tests.rs @@ -669,6 +669,34 @@ fn area_type() -> TextObject { t } +#[test] +fn a_wrap_object_below_every_area_type_object_makes_no_outline() { + use crate::{Appearance, Document, Node, NodeKind}; + let mut d = Document::new(300.0, 300.0); + let l = d.layers[0].id; + let wrap = |d: &mut Document, r: Rect| { + let id = d.alloc_id(); + let mut n = Node::path(id, vectorcraft_geom::shapes::rectangle(r), Appearance::default_art()); + n.extras_mut().wrap = Some(TextWrap::default()); + n + }; + // Bottom to top: a wrap object, the area type, then a wrap object. + let below = wrap(&mut d, Rect::new(0.0, 0.0, 250.0, 250.0)); + d.insert(Some(l), 9, below).unwrap(); + let id = d.alloc_id(); + d.insert(Some(l), 9, Node::new(id, NodeKind::Text(Box::new(area_type())))).unwrap(); + let above = wrap(&mut d, Rect::new(60.0, 40.0, 80.0, 60.0)); + d.insert(Some(l), 9, above).unwrap(); + wrap::OUTLINES_MADE.with(|c| c.set(0)); + let mut sources = 0; + wrap_sources(&d, |_, objects, shapes| { + sources += 1; + assert_eq!((objects.len(), shapes.len()), (1, 1)); + }); + assert_eq!(sources, 1); + assert_eq!(wrap::OUTLINES_MADE.with(|c| c.get()), 1, "only the wrap object above the type is outlined"); +} + #[test] fn area_resizes_its_frame_and_keeps_its_type() { let mut t = area_type(); diff --git a/crates/doc/src/text/wrap.rs b/crates/doc/src/text/wrap.rs index 15a0fbbd40..33fdcb4687 100644 --- a/crates/doc/src/text/wrap.rs +++ b/crates/doc/src/text/wrap.rs @@ -7,6 +7,12 @@ use vectorcraft_geom::{PathData, shapes}; use super::{TextKind, TextObject, WrapShape}; use crate::{Document, Node, NodeId, NodeKind}; +#[cfg(test)] +thread_local! { + /// How many wrap outlines [`each_text`] has made on this thread (for tests). + pub(super) static OUTLINES_MADE: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + /// Outline of a wrap object in document coordinates: its paths, or its bounds for other art. fn outline(n: &Node, out: &mut PathData) { match &n.kind { @@ -66,10 +72,45 @@ fn collect<'a>(n: &'a Node, out: &mut Vec>) { } } +/// The anchors and subpaths [`outline`] would collect for wrap object `n`, counted without copying +/// them. +fn outline_size(n: &Node) -> (usize, usize) { + match &n.kind { + NodeKind::Path { path, guide: false, .. } => path + .subpaths + .iter() + .filter(|sp| sp.closed || sp.anchors.len() > 2) + .fold((0usize, 0usize), |(a, s), sp| (a.saturating_add(sp.anchors.len()), s.saturating_add(1))), + NodeKind::Compound { children, .. } | NodeKind::Group { children, clip: false } => children + .iter() + .filter(|c| c.visible) + .map(|c| outline_size(c)) + .fold((0, 0), |(a, s), (ca, cs)| (a.saturating_add(ca), s.saturating_add(cs))), + NodeKind::Group { children, clip: true } => children.first().map_or((0, 0), |c| outline_size(c)), + // A rectangle of the object's bounds. + _ => { + if n.geometric_bounds().is_some() { + (4, 1) + } else { + (0, 0) + } + } + } +} + /// How much [`resolve_wrap`] would copy into the wrap shapes of every area text object in `doc`: /// each wrap object's outline (its anchors, plus one for the shape) once for each area text object /// below it in its layer. pub fn wrap_work(doc: &Document) -> usize { + work(doc, false) +} + +/// [`wrap_work`], with one more for each subpath of each outline, empty ones included. +pub fn wrap_copy_units(doc: &Document) -> usize { + work(doc, true) +} + +fn work(doc: &Document, count_subpaths: bool) -> usize { let mut total = 0usize; for layer in &doc.layers { let mut items = vec![]; @@ -78,11 +119,10 @@ pub fn wrap_work(doc: &Document) -> usize { for it in items.iter().rev() { match it { Item::Wrap(n) => { - let mut pd = PathData::default(); - outline(n, &mut pd); - if !pd.is_empty() { - let anchors: usize = pd.subpaths.iter().map(|sp| sp.anchors.len()).sum(); - above = above.saturating_add(anchors.saturating_add(1)); + let (anchors, subpaths) = outline_size(n); + if anchors > 0 { + let subpaths = if count_subpaths { subpaths } else { 0 }; + above = above.saturating_add(anchors).saturating_add(subpaths).saturating_add(1); } } Item::Text(_) => total = total.saturating_add(above), @@ -99,9 +139,15 @@ fn each_text<'a>(layer: &'a Node, mut f: impl FnMut(&'a Node, &[(&'a Node, WrapS let mut items = vec![]; collect(layer, &mut items); let mut above: Vec<(&Node, WrapShape)> = vec![]; - for it in items.iter().rev() { + // A wrap object below every area text object of the layer wraps none of them: its outline is + // not made. + let first_text = items.iter().position(|it| matches!(it, Item::Text(_))); + for (i, it) in items.iter().enumerate().rev() { match it { + Item::Wrap(_) if first_text.is_none_or(|t| i < t) => {} Item::Wrap(n) => { + #[cfg(test)] + OUTLINES_MADE.with(|c| c.set(c.get() + 1)); let mut pd = PathData::default(); outline(n, &mut pd); if !pd.is_empty() { diff --git a/crates/effects/src/catalog.rs b/crates/effects/src/catalog.rs index 7bba8d44a0..9d9810c240 100644 --- a/crates/effects/src/catalog.rs +++ b/crates/effects/src/catalog.rs @@ -111,6 +111,8 @@ fn lengths_of(id: &str) -> Lengths { "sketch.tornEdges" => always(&["smoothness"]), "sketch.waterPaper" => always(&["fiberLength"]), TRAP => always(&["thickness", "precision"]), + // The Pathfinder Options' refit tolerance. + id if crate::takes_pathfinder_options(id) => always(&["precision"]), RASTERIZE => always(&["addAround"]), // The points one unit of the filter measures. crate::SVG_FILTER => always(&["scale"]), @@ -189,7 +191,7 @@ pub fn effect_catalog() -> Vec { EXTRUDE, "Extrude & Bevel…", &["Effect", "3D and Materials"], - "{depth: pt (0..2000, 50), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none), bevelWidth: pt (0..1000, 4), bevelHeight: pt (0..1000, 4), bevelRepeat: integer (1..32, 1), bevelSpace: % (0..90, 0; flat between repeats), bevelInside: bool (false: added around the shape; true: carved into it), bevelBothSides: bool (false), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the caps and the side, see threeD.mapGraphic: symbol: name of a document symbol, face: front|back|side (front; the back reads left to right as seen from behind; side is the walls and bevels), x: pt (0; the offset of the graphic's center from the center of the object's bounds, in the face's own plane; on the side from the middle of the side unrolled flat, along the outline, clockwise from its top), y: pt (0; on the side from the front toward the back), scale: % (1..10000, 100; of the symbol's own size), rotation: degrees (-360..360, 0; counterclockwise); drawn turned, foreshortened and shaded with the face and clipped to it: on a cap of a solid object only, and on the side of a solid or hollow object wrapped around it and drawn only where its outside faces the viewer), render: object ({mode: shaded}; mode: shaded|wireframe, as Revolve's)}. The front face is the art, extruded backwards about the centre of its bounds; painted with the top fill (else the top stroke).", + "{depth: pt (0..2000, 50), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none; or custom, a bevel of the user's own drawn by bevelProfile), bevelWidth: pt (0..1000, 4), bevelHeight: pt (0..1000, 4), bevelRepeat: integer (1..32, 1), bevelSpace: % (0..90, 0; flat between repeats), bevelInside: bool (false: added around the shape; true: carved into it), bevelBothSides: bool (false), bevelName: string (a custom bevel's name), bevelProfile: [[x, y], …] (a custom bevel's 2 to 64 points, shares 0..1 of the width and height from [0, 0] at the cap's edge to [1, 1] at the side wall, joined by straight lines; effect.apply and effect.setParams also take bevel {custom: name}, a bevel of the bevels file (threeD.bevels.list), and store it as bevel custom with its bevelName and bevelProfile), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the caps and the side, see threeD.mapGraphic: symbol: name of a document symbol, face: front|back|side (front; the back reads left to right as seen from behind; side is the walls and bevels), x: pt (0; the offset of the graphic's center from the center of the object's bounds, in the face's own plane; on the side from the middle of the side unrolled flat, along the outline, clockwise from its top), y: pt (0; on the side from the front toward the back), scale: % (1..10000, 100; of the symbol's own size), rotation: degrees (-360..360, 0; counterclockwise); drawn turned, foreshortened and shaded with the face and clipped to it: on a cap of a solid object only, and on the side of a solid or hollow object wrapped around it and drawn only where its outside faces the viewer), render: object ({mode: shaded}; mode: shaded|wireframe, as Revolve's)}. The front face is the art, extruded backwards about the centre of its bounds; painted with the top fill (else the top stroke).", json!({"depth":50.0,"twist":0.0,"taper":100.0,"cap":true,"bevel":"none","bevelWidth":4.0,"bevelHeight":4.0,"bevelRepeat":1,"bevelSpace":0.0,"bevelInside":false,"bevelBothSides":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"graphics":[],"render":{"mode":"shaded"}}), ), g( @@ -210,7 +212,7 @@ pub fn effect_catalog() -> Vec { CLASSIC_EXTRUDE, "Extrude & Bevel (Classic)…", &["Effect", "3D and Materials", "3D (Classic)"], - "{depth: pt (0..2000, 50), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none), bevelHeight: pt (1..100, 4; the bevel is as wide as it is tall), bevelInside: bool (false: added around the shape; true: carved into it), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: wireframe|none|diffuse|plastic (plastic; wireframe draws the edges of every face, hidden ones included, and fills none; none keeps the paint unlit; diffuse lights the faces softly; plastic adds a glossy highlight), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, every face whichever way it faces), highlightIntensity: % (0..100, 60; plastic only), highlightSize: % (0..100, 90; 100 broad, 0 a small spot; plastic only), blendSteps: integer (1..256, 25; how many levels the shading and the highlight are rounded to), shadingColor: black|custom|none|blackOverprint (black; the color the faces darken toward; none keeps the paint and adds only the highlight; blackOverprint keeps the paint and draws the shading over it as overprinting black, on the black plate, with no highlight), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), preserveSpotColors: bool (false; a color linked to a spot or global swatch stays a tint of that swatch, lighter where the highlight is, with black multiplied and overprinting where the faces darken, so a spot color keeps its plate; it does nothing while shadingColor is custom, and with blackOverprint every face keeps its paint and swatch link whether it is on or off), drawHiddenFaces: bool (false; also draws the faces turned away, behind the others), mapArt: array of 0..64 objects ([]; Map Art, see threeD.mapArt: surface: integer (1..100000; the numbered surface, one map for a surface), symbol: name of a document symbol, x: pt (-1000000..1000000, 0; the offset of the art's center from the center of the surface laid out flat), y: pt (-1000000..1000000, 0), scaleX: % (1..10000, 100; of the symbol's own width), scaleY: % (1..10000, 100), rotation: degrees (-360..360, 0; counterclockwise); the surfaces are numbered through the object's solids in the order they are built: each solid's front cap and back cap (none on a hollow solid, cap false), then each side wall from corner to corner of the outline, then the bevel above each wall; a map past the object's surfaces draws nothing; wireframe draws no mapped art), mapShade: bool (false; Shade Artwork: the mapped art takes the tone and highlight of its face), mapInvisible: bool (false; Invisible Geometry: with at least one map, only the mapped art is drawn)}. The front face is the art, extruded backwards about the center of its bounds; a solid is built for the top fill and for each stroke, each in its own paint. The defaults, the surface numbering and the limits are VectorCraft's own.", + "{depth: pt (0..2000, 50), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none; or custom, a bevel of the user's own drawn by bevelProfile), bevelHeight: pt (1..100, 4; the bevel is as wide as it is tall), bevelInside: bool (false: added around the shape; true: carved into it), bevelName: string (a custom bevel's name), bevelProfile: [[x, y], …] (a custom bevel's points, as for threeD.extrude; bevel {custom: name} takes a bevel of the bevels file), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), surface: wireframe|none|diffuse|plastic (plastic; wireframe draws the edges of every face, hidden ones included, and fills none; none keeps the paint unlit; diffuse lights the faces softly; plastic adds a glossy highlight), lights: null or array of 1..10 objects (intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, behind: bool; overrides the single-light fields; the lights add up; color and softness are not used), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 100), ambient: % (0..100, 50; Ambient Light, every face whichever way it faces), highlightIntensity: % (0..100, 60; plastic only), highlightSize: % (0..100, 90; 100 broad, 0 a small spot; plastic only), blendSteps: integer (1..256, 25; how many levels the shading and the highlight are rounded to), shadingColor: black|custom|none|blackOverprint (black; the color the faces darken toward; none keeps the paint and adds only the highlight; blackOverprint keeps the paint and draws the shading over it as overprinting black, on the black plate, with no highlight), shadingCustom: #rrggbb (#000000; the color shadingColor custom darkens toward), preserveSpotColors: bool (false; a color linked to a spot or global swatch stays a tint of that swatch, lighter where the highlight is, with black multiplied and overprinting where the faces darken, so a spot color keeps its plate; it does nothing while shadingColor is custom, and with blackOverprint every face keeps its paint and swatch link whether it is on or off), drawHiddenFaces: bool (false; also draws the faces turned away, behind the others), mapArt: array of 0..64 objects ([]; Map Art, see threeD.mapArt: surface: integer (1..100000; the numbered surface, one map for a surface), symbol: name of a document symbol, x: pt (-1000000..1000000, 0; the offset of the art's center from the center of the surface laid out flat), y: pt (-1000000..1000000, 0), scaleX: % (1..10000, 100; of the symbol's own width), scaleY: % (1..10000, 100), rotation: degrees (-360..360, 0; counterclockwise); the surfaces are numbered through the object's solids in the order they are built: each solid's front cap and back cap (none on a hollow solid, cap false), then each side wall from corner to corner of the outline, then the bevel above each wall; a map past the object's surfaces draws nothing; wireframe draws no mapped art), mapShade: bool (false; Shade Artwork: the mapped art takes the tone and highlight of its face), mapInvisible: bool (false; Invisible Geometry: with at least one map, only the mapped art is drawn)}. The front face is the art, extruded backwards about the center of its bounds; a solid is built for the top fill and for each stroke, each in its own paint. The defaults, the surface numbering and the limits are VectorCraft's own.", json!({"depth":50.0,"cap":true,"bevel":"none","bevelHeight":4.0,"bevelInside":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"surface":"plastic","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":100.0,"ambient":50.0,"highlightIntensity":60.0,"highlightSize":90.0,"blendSteps":25,"shadingColor":"black","shadingCustom":"#000000","preserveSpotColors":false,"drawHiddenFaces":false,"mapArt":[],"mapShade":false,"mapInvisible":false}), ), g( @@ -832,15 +834,11 @@ pub fn effect_catalog() -> Vec { } for (id, label, _) in PATHFINDER_EFFECTS { if id == "pathfinder.softMix" { - v.push(g( - id, - label, - PATHFINDER, - "{mixingRate?: 1..100 % (50)} blend overlapping fills in CMYK bottom to top (groups and layers: live Pathfinder over the members)", - json!({"mixingRate": 50.0}), - )); + v.push(g(id, label, PATHFINDER, crate::group::SOFT_MIX_PARAMS_DOC, json!({"mixingRate": 50.0}))); } else { - v.push(g(id, label, PATHFINDER, "{} (groups and layers: live Pathfinder over the members)", json!({}))); + // No dialog defaults, so the Effect menu applies it directly; effect.apply fills its + // Pathfinder Options in. + v.push(g(id, label, PATHFINDER, crate::group::PATHFINDER_PARAMS_DOC, json!({}))); } } v.extend(crate::addons::color::catalog()); diff --git a/crates/effects/src/group.rs b/crates/effects/src/group.rs index a6f5af916b..aeffaacfb6 100644 --- a/crates/effects/src/group.rs +++ b/crates/effects/src/group.rs @@ -51,6 +51,80 @@ fn op_of(id: &str) -> Option { PATHFINDER_EFFECTS.iter().find(|e| e.0 == id).map(|e| e.2) } +/// Does effect `id` keep Pathfinder Options of its own ([`PathfinderEffectOptions`]): one of +/// [`PATHFINDER_EFFECTS`] (Trap has options of its own)? +pub fn takes_pathfinder_options(id: &str) -> bool { + op_of(id).is_some() +} + +/// The parameters holding a Pathfinder effect's Pathfinder Options. +pub const PATHFINDER_OPTION_KEYS: [&str; 3] = ["precision", "removeRedundantPoints", "removeUnpainted"]; + +/// The range of a Pathfinder effect's `precision` (pt), the Pathfinder panel's range. +pub const PATHFINDER_EFFECT_PRECISION: std::ops::RangeInclusive = 0.001..=10.0; + +/// The documentation of [`PATHFINDER_OPTION_KEYS`], as a literal for `concat!`. +macro_rules! options_doc { + () => { + "precision?: pt 0.001..10 (effect.apply: Pathfinder Options › Precision; 0.01 when missing; results are refit to within it and pieces thinner than it are dropped), removeRedundantPoints?: bool (effect.apply: Pathfinder Options › Remove Redundant Points; false when missing; results lose the anchors that don't change their shape to within precision), removeUnpainted?: bool (effect.apply: Pathfinder Options › Divide and Outline Will Remove Unpainted Artwork; false when missing; Divide and Outline leave out the pieces of members with no visible fill, a compound shape's area going by the shape's own fill, except that Divide keeps every piece when the group or compound shape has a visible fill of its own; the other operations ignore it)" + }; +} + +/// The documentation of [`PATHFINDER_OPTION_KEYS`], shared by the Pathfinder effects' parameters. +pub const PATHFINDER_OPTIONS_DOC: &str = options_doc!(); + +/// The parameters of a Pathfinder effect other than Soft Mix. +pub const PATHFINDER_PARAMS_DOC: &str = concat!("{", options_doc!(), "} (groups and layers: live Pathfinder over the members)"); + +/// The parameters of Effect › Pathfinder › Soft Mix. +pub const SOFT_MIX_PARAMS_DOC: &str = concat!( + "{mixingRate?: 1..100 % (50), ", + options_doc!(), + "} blend overlapping fills in CMYK bottom to top (groups and layers: live Pathfinder over the members)" +); + +/// The Pathfinder Options a Pathfinder effect evaluates with, read from its parameters. An effect +/// without them (saved before effects kept their own) evaluates as it did then: the default +/// precision, with no points or pieces removed. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct PathfinderEffectOptions { + /// Refit tolerance of the results, in points ([`PATHFINDER_EFFECT_PRECISION`]). + pub precision: f64, + /// Drop anchors that don't change a result's shape. + pub remove_redundant_points: bool, + /// Divide and Outline leave out the pieces of members with no visible fill. + pub remove_unpainted: bool, +} + +impl Default for PathfinderEffectOptions { + fn default() -> Self { + PathfinderEffectOptions { precision: po::DEFAULT_PRECISION, remove_redundant_points: false, remove_unpainted: false } + } +} + +impl PathfinderEffectOptions { + /// The options in `p`: a missing or non-numeric value takes its default and a precision out of + /// range its nearest bound, so a live effect always evaluates. + pub fn from_params(p: &Value) -> Self { + let d = PathfinderEffectOptions::default(); + let (lo, hi) = (*PATHFINDER_EFFECT_PRECISION.start(), *PATHFINDER_EFFECT_PRECISION.end()); + PathfinderEffectOptions { + precision: crate::util::num(p, "precision", d.precision).clamp(lo, hi), + remove_redundant_points: crate::util::flag(p, "removeRedundantPoints", d.remove_redundant_points), + remove_unpainted: crate::util::flag(p, "removeUnpainted", d.remove_unpainted), + } + } + + /// These options as the parameters [`PATHFINDER_OPTION_KEYS`] name. + pub fn to_params(self) -> Value { + serde_json::json!({ + "precision": self.precision, + "removeRedundantPoints": self.remove_redundant_points, + "removeUnpainted": self.remove_unpainted, + }) + } +} + /// Does `n` (a group or layer) carry a visible Pathfinder effect, or is it a compound shape? pub fn has_pathfinder(n: &Node) -> bool { n.is_compound_shape() @@ -503,6 +577,23 @@ pub fn pathfinder_children(doc: Option<&Document>, group: &Node, hook: Option Option { + let a = area_style.as_ref().filter(|_| s.id == group.id && s.appearance.items.is_empty())?; + let mut a = a.clone(); + (a.opacity, a.blend) = (s.opacity, s.blend); + Some(a) + }; let mut stack: Vec> = if group.is_compound_shape() { // The group's own appearance paints the area ([`evaluate_container`]), so the art has none. match compound_shape_area(doc, group, hook) { @@ -535,6 +626,7 @@ pub fn pathfinder_children(doc: Option<&Document>, group: &Node, hook: Option, group: &Node, hook: Option = parts.iter().map(|(p, r)| (p, *r)).collect(); let key = sources.len() as u64; if let Some(top) = lv.pop() { - shapes.push(po::Shape::new(po::unite_all(&refs), FillRule::NonZero, key)); + shapes.push(po::Shape::new(po::unite_all_with(&refs, options.precision), FillRule::NonZero, key)); sources.push(top); } } else { @@ -574,24 +666,40 @@ pub fn pathfinder_children(doc: Option<&Document>, group: &Node, hook: Option !own_fill, + PathfinderOp::Outline => true, + _ => false, + }; + let fill_sources: Vec> = sources.iter().map(style_of).collect(); + let fill_source = |k: u64| fill_sources[k as usize].as_ref().unwrap_or(&sources[k as usize]); + po::pathfinder_with(op, &shapes, options.precision) .into_iter() - .filter(|r| !r.path.is_empty()) - .map(|r| Arc::new(styled(&sources[r.key as usize], r.path, op == PathfinderOp::Outline))) + .filter(|r| !r.path.is_empty() && !(unpainted && !has_visible_fill(fill_source(r.key)))) + .map(|r| { + let outline = op == PathfinderOp::Outline; + let src = if outline { fill_source(r.key) } else { &sources[r.key as usize] }; + Arc::new(styled(src, tidy(r.path), outline)) + }) .collect() }; } @@ -676,6 +784,11 @@ pub fn paints(item: &AppearanceItem) -> bool { } } +/// Has `n` a visible fill that paints, as the Pathfinder panel's Remove Unpainted Artwork counts it? +fn has_visible_fill(n: &Node) -> bool { + n.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Fill(f) if f.visible && !f.paint.is_none())) +} + /// Do the own fills or strokes of `n`, a group or layer, paint anything? pub(crate) fn has_own_paint(n: &Node) -> bool { is_container(n) && n.appearance.items.iter().any(paints) diff --git a/crates/effects/src/group/tests.rs b/crates/effects/src/group/tests.rs index 3b8addadea..1c62508347 100644 --- a/crates/effects/src/group/tests.rs +++ b/crates/effects/src/group/tests.rs @@ -213,6 +213,81 @@ fn divide_and_outline_draw_nothing_for_unpainted_members() { } } +/// With Remove Unpainted Artwork, Divide and Outline keep the area of a compound shape whose own +/// appearance has a visible fill and leave out the area of one without. +#[test] +fn remove_unpainted_keeps_a_filled_compound_shapes_area() { + for effect in ["pathfinder.divide", "pathfinder.outline"] { + for filled in [true, false] { + let mut g = compound_shape(ShapeMode::Add); + if !filled { + g.appearance = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0).into(); + } + g.appearance.effects.push(Effect { id: effect.into(), params: serde_json::json!({"removeUnpainted": true}), visible: true }); + let out = pathfinder_children(None, &g, None).unwrap(); + assert_eq!(!out.is_empty(), filled, "{effect}, filled {filled}: {out:#?}"); + } + } +} + +/// Outline strokes a compound shape's area in the shape's own fill (its top visible one that +/// paints), with Remove Unpainted Artwork on or off, and Divide leaves the area's pieces +/// unpainted for the shape's fill to paint. +#[test] +fn outline_strokes_a_compound_shapes_area_in_its_fill() { + let green = Paint::solid(Color::rgb(0.0, 1.0, 0.0)); + for (remove, covered) in [(false, false), (true, false), (false, true), (true, true)] { + for effect in ["pathfinder.divide", "pathfinder.outline"] { + let mut g = compound_shape(ShapeMode::Add); + if covered { + // A hidden fill and an unpainted fill above the green one. + let mut hidden = FillLayer::new(Paint::solid(Color::rgb(1.0, 0.0, 0.0))); + hidden.visible = false; + let mut a = (*g.appearance).clone(); + a.insert_item(a.items.len(), AppearanceItem::Fill(hidden)); + a.insert_item(a.items.len(), AppearanceItem::Fill(FillLayer::new(Paint::None))); + g.appearance = a.into(); + } + g.appearance.effects.push(Effect { id: effect.into(), params: serde_json::json!({"removeUnpainted": remove}), visible: true }); + let out = pathfinder_children(None, &g, None).unwrap(); + assert!(!out.is_empty(), "{effect}, remove {remove}"); + for n in &out { + if effect == "pathfinder.outline" { + assert_eq!(n.appearance.stroke_paint(), green, "{effect}, remove {remove}: {n:#?}"); + assert!(n.appearance.fill_paint().is_none(), "{effect}, remove {remove}: {n:#?}"); + } else { + assert!(n.appearance.items.is_empty(), "{effect}, remove {remove}: {n:#?}"); + } + } + } + } +} + +/// With Remove Unpainted Artwork, Divide keeps the pieces of an unfilled member when its group's +/// own visible fill paints them and leaves them out when the group has no fill. Outline leaves out +/// the member's segments either way. +#[test] +fn remove_unpainted_keeps_members_a_groups_own_fill_paints() { + let unfilled = Arc::new(Node::path( + NodeId(2), + shapes::rectangle(Rect::new(5.0, 0.0, 15.0, 10.0)), + Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0), + )); + for effect in ["pathfinder.divide", "pathfinder.outline"] { + for filled in [true, false] { + let mut g = Node::group(NodeId(10), vec![sq(1, 0.0, Color::rgb(1.0, 0.0, 0.0)), unfilled.clone()]); + if filled { + g.appearance = Appearance::basic(Paint::solid(Color::rgb(0.0, 1.0, 0.0)), Paint::None, 0.0).into(); + } + g.appearance.effects.push(Effect { id: effect.into(), params: serde_json::json!({"removeUnpainted": true}), visible: true }); + let out = pathfinder_children(None, &g, None).unwrap(); + assert!(out.iter().any(|n| n.id == NodeId(1)), "{effect}, filled {filled}: {out:#?}"); + let kept = filled && effect == "pathfinder.divide"; + assert_eq!(out.iter().any(|n| n.id == NodeId(2)), kept, "{effect}, filled {filled}: {out:#?}"); + } + } +} + /// Returns an "H" in blue type at 100 pt on a baseline at y = 80, with its stems on either /// side of x = 100. fn type_h() -> Node { diff --git a/crates/effects/src/lib.rs b/crates/effects/src/lib.rs index fff4705333..c46ab0c76e 100644 --- a/crates/effects/src/lib.rs +++ b/crates/effects/src/lib.rs @@ -75,8 +75,9 @@ pub use bake::{ }; pub use clip::{WarpSeams, clip_outline, knockout_silhouette, reshaped_clip_outline, warp_pieces_translucent}; pub use group::{ - OutlineHook, PATHFINDER_EFFECTS, compound_shape_area, compound_shape_art, evaluate_container, has_container_appearance, has_pathfinder, - is_pathfinder, member_leaves, member_shapes, paints, pathfinder_children, pinned_container_appearance, shape_art, + OutlineHook, PATHFINDER_EFFECT_PRECISION, PATHFINDER_EFFECTS, PATHFINDER_OPTION_KEYS, PATHFINDER_OPTIONS_DOC, PathfinderEffectOptions, + compound_shape_area, compound_shape_art, evaluate_container, has_container_appearance, has_pathfinder, is_pathfinder, member_leaves, + member_shapes, paints, pathfinder_children, pinned_container_appearance, shape_art, takes_pathfinder_options, }; pub use lighting_presets::{LIGHTING_PRESETS, LightingPreset, lighting_preset_params, matching_lighting_preset}; pub use live::{expand_live, expand_live_deep, expanded_live_group, outline_object, text_outliner}; @@ -96,11 +97,11 @@ pub use revolve::{ CLASSIC_REVOLVE, REVOLVE, has_revolve, is_revolve, revolve_art, revolve_art_in, revolve_options, validate_revolve, validate_revolve_in, }; pub use solids::{ - CLASSIC_EXTRUDE, CLASSIC_ROTATE, EXTRUDE, GRAPHICS, GraphicFrame, INFLATE, MAX_GRAPHICS, MappedGraphic, MeshGraphics, RENDER, RENDER_MODES, - ROTATE, ROTATE_SURFACES, ROTATION_PRESETS, SHADING_COLORS, SOLIDS, SolidMesh, THREE_D_TYPES, classic_extrude_options, classic_shading, - extrude_options, graphic_bounds, graphic_frame, graphic_symbols, has_solid, inflate_options, is_classic_three_d, is_three_d, mapped_graphics, - mesh_graphics_art, missing_symbol, names_graphic_symbol, rename_graphic_symbol, rename_graphic_symbol_in, renders_wireframe, solid_art, - solid_art_in, takes_graphics, three_d_meshes, three_d_meshes_in, three_d_meshes_of, three_d_meshes_of_in, three_d_params_as, + BEVEL_NAME, BEVEL_PROFILE, CLASSIC_EXTRUDE, CLASSIC_ROTATE, EXTRUDE, GRAPHICS, GraphicFrame, INFLATE, MAX_GRAPHICS, MappedGraphic, MeshGraphics, + RENDER, RENDER_MODES, ROTATE, ROTATE_SURFACES, ROTATION_PRESETS, SHADING_COLORS, SOLIDS, SolidMesh, THREE_D_TYPES, classic_extrude_options, + classic_shading, extrude_options, graphic_bounds, graphic_frame, graphic_symbols, has_solid, inflate_options, is_classic_three_d, is_three_d, + mapped_graphics, mesh_graphics_art, missing_symbol, names_graphic_symbol, rename_graphic_symbol, rename_graphic_symbol_in, renders_wireframe, + solid_art, solid_art_in, takes_graphics, three_d_meshes, three_d_meshes_in, three_d_meshes_of, three_d_meshes_of_in, three_d_params_as, three_d_wireframe_in, validate_solid, validate_solid_in, validate_three_d, validate_three_d_at, validate_three_d_at_in, validate_three_d_in, validate_three_d_params, view_options, with_graphic, }; @@ -115,8 +116,8 @@ pub use solids::{ pub use stylize::{ScribbleSetting, scribble_setting_id, scribble_settings}; pub use svg_filter::SVG_FILTER; pub use trap::TRAP; -pub use vectorcraft_three_d::Mesh; pub use vectorcraft_three_d::PlanarFace; +pub use vectorcraft_three_d::{BevelProfile, Mesh}; pub use warp::{WARP_NET, WarpNet, WarpStyle, map_version, warp_point, warp_version}; mod catalog; diff --git a/crates/effects/src/params.rs b/crates/effects/src/params.rs index 1e3c8c1d31..ab588838a6 100644 --- a/crates/effects/src/params.rs +++ b/crates/effects/src/params.rs @@ -120,7 +120,10 @@ pub fn new_effect(id: &str, params: &Value) -> Option { /// Scale the distance parameters of `e` by `s` (Scale Strokes & Effects; see /// [`EffectInfo::lengths`]), and its sizes in raster pixels ([`crate::raster_px_range`]), which /// keep their share of the object so. A distance left at its default is written out scaled; one -/// the effect doesn't have (Outline Stroke's weight following its stroke) stays absent. +/// the effect doesn't have (Outline Stroke's weight following its stroke) stays absent. A Pathfinder +/// effect without a `precision` gets the precision it evaluates with, scaled. Values are scaled +/// as stored, out of range or not, so a scale and its inverse restore them; evaluation applies +/// each effect's range. pub fn scale_effect(e: &mut Effect, s: f64) { let Some(info) = catalog_index().get(e.id.as_str()) else { return }; let merged = merged_params(&e.id, &e.params); @@ -128,7 +131,9 @@ pub fn scale_effect(e: &mut Effect, s: f64) { let mut keys: Vec<&str> = info.lengths.keys(relative).collect(); keys.extend(merged.as_object().into_iter().flat_map(|m| m.keys()).map(String::as_str).filter(|k| crate::raster_px_range(&e.id, k).is_some())); for k in keys { - let v = util::num(&merged, k, f64::NAN); + let missing = + if k == "precision" && crate::takes_pathfinder_options(&e.id) { crate::PathfinderEffectOptions::default().precision } else { f64::NAN }; + let v = util::num(&merged, k, missing); if v.is_finite() { if !e.params.is_object() { e.params = Value::Object(Map::new()); diff --git a/crates/effects/src/reshape.rs b/crates/effects/src/reshape.rs index 85c36f2d89..a57c2085f6 100644 --- a/crates/effects/src/reshape.rs +++ b/crates/effects/src/reshape.rs @@ -1248,15 +1248,20 @@ fn as_art_opts( let fx = geometry_effects(n); let mut art = match &n.kind { NodeKind::Image(im) => { - let frame = shapes::rectangle(Rect::new(0.0, 0.0, im.width as f64, im.height as f64)).transformed(im.xf); + // A distorted image's frame joins its corners. + let frame = match n.image_frame().filter(|_| n.is_distorted_image()) { + Some(bp) => PathData::from_bezpath(&bp), + None => shapes::rectangle(Rect::new(0.0, 0.0, im.width as f64, im.height as f64)).transformed(im.xf), + }; let mut image = Node::new(n.id, n.kind.clone()); // Its pixels draw as the image's do: colorized by a grayscale image's fill color, - // smoothed or not, and with its color mask's masked pixels. + // smoothed or not, with its color mask's masked pixels, and distorted. { let mut e = image.extras_mut(); e.colorize = n.extras().colorize.clone(); e.pixelated = n.extras().pixelated; e.color_mask = n.extras().color_mask.clone(); + e.image_quad = n.extras().image_quad.clone(); } let clipped = || { let mut clip = Node::path(n.id, frame.clone(), Appearance::default()); @@ -1276,6 +1281,17 @@ fn as_art_opts( clipped() } else { let opaque = std::cell::OnceCell::new(); + // A distorted image's opaque area, traced in its pixels, goes to the page through + // its projective map. + let opaque_on_page = || match n.image_map().filter(|_| n.is_distorted_image()) { + Some(map) => { + let plain = ImageObject { xf: Affine::IDENTITY, ..(**im).clone() }; + let piece = f64::from(im.width.max(im.height).max(1)) / 64.0; + opaque_area(&[symbols, paint_doc], &plain) + .map(|p| vectorcraft_doc::live::map_nonlinear(&p, piece, |q| map.apply(q).unwrap_or(q))) + } + None => opaque_area(&[symbols, paint_doc], im), + }; let rows = |items: Vec| { let mut out = vec![]; let mut items = items.into_iter().peekable(); @@ -1285,7 +1301,7 @@ fn as_art_opts( while let Some(next) = items.next_if(|i| follows_opaque_area(i) == follows) { run.push(next); } - let path = if follows { opaque.get_or_init(|| opaque_area(&[symbols, paint_doc], im)).as_ref() } else { None }; + let path = if follows { opaque.get_or_init(opaque_on_page).as_ref() } else { None }; let path = path.unwrap_or(&frame); if !path.is_empty() { out.push(Arc::new(Node::path(n.id, path.clone(), Appearance { items: run, ..Default::default() }))); @@ -3718,8 +3734,21 @@ fn restore_warped_images(n: &mut Node, warped: &WarpedImages, cut: bool) { // The pieces start from the image as it was placed when it took its first warp. let first = warps.first().map(|(_, at)| ImageObject { xf: *at, ..(**own).clone() }); let map = warped_map(warps, own.xf); + // A placement with no inverse cannot take a distorted image's corners back. + let det = own.xf.determinant(); + let back = warps.first().filter(|_| det.is_finite() && det != 0.0).map(|(_, at)| *at * own.xf.inverse()).filter(Affine::is_finite); + let distorted = image.extras().image_quad.is_some(); *c = Arc::new(match (first, map) { - (Some(first), Some(map)) if cut => { + (Some(first), Some(map)) if cut && (back.is_some() || !distorted) => { + // A distorted image's corners go back to where they stood at its first warp, as + // its placement does: the moves since then are in `map`. + if let Some(back) = back + && let Some(q) = image.extras_if_any().and_then(|e| e.image_quad.as_mut()) + { + for p in q.iter_mut() { + *p = back * *p; + } + } let pixelated = image.extras().pixelated; vectorcraft_doc::live::mesh_warp_image(&image, &first, &*map, WARP_IMAGE_CELLS, pixelated, false) } @@ -3787,6 +3816,12 @@ fn copy_placed(n: &mut Node, m: Affine, copies: usize, scaling: vectorcraft_doc: NodeKind::SymbolInstance { xf: at, .. } => *at = xf * *at, _ => {} } + // A distorted image's corners move with it. + if let Some(q) = one.extras_if_any().and_then(|e| e.image_quad.as_mut()) { + for p in q.iter_mut() { + *p = xf * *p; + } + } // The placed gradients of its own fills and strokes move with it, as a path's do. if xf != Affine::IDENTITY && one.appearance.has_positioned_gradient() { one.appearance.transform_gradients(xf); diff --git a/crates/effects/src/solids.rs b/crates/effects/src/solids.rs index 93de078d84..5d1493fcd7 100644 --- a/crates/effects/src/solids.rs +++ b/crates/effects/src/solids.rs @@ -8,7 +8,7 @@ use vectorcraft_doc::{Appearance, AppearanceItem, Document, Effect, Node, NodeId use vectorcraft_geom::{BezPath, FillRule, PathData, Point, Rect, Vec2}; use vectorcraft_pathops::BoolOp; use vectorcraft_three_d::{ - Bevel, BevelShape, DepthPlane, Extrude, Facet, Inflate, MAX_OBJECT_FACES, Mesh, MeshedSolid, PlanarFace, SolidFaces, View, + Bevel, BevelProfile, BevelShape, DepthPlane, Extrude, Facet, Inflate, MAX_OBJECT_FACES, Mesh, MeshedSolid, PlanarFace, SolidFaces, View, }; #[cfg(test)] @@ -72,7 +72,9 @@ pub const THREE_D_TYPES: [(&str, &str); 4] = [("plane", ROTATE), ("extrude", EXT /// The parameters of 3D effect `to` for an effect `from` with `params`, as switching the object /// type keeps them: every setting `to` takes keeps its value from `params` (the defaults of `from` /// under them), each rotation angle wrapped into -180° to 180° when `to` is not Revolve, and the -/// settings only `to` takes start at their defaults. Settings `to` does not take are dropped. +/// settings only `to` takes start at their defaults. Settings `to` does not take are dropped; a +/// custom bevel's name and points ([`BEVEL_NAME`], [`BEVEL_PROFILE`]) go with `bevel` when `to` +/// takes one. pub fn three_d_params_as(from: &str, params: &Value, to: &str) -> Value { let current = crate::merged_params(from, params); let mut out = crate::default_params(to).and_then(|v| v.as_object().cloned()).unwrap_or_default(); @@ -81,6 +83,13 @@ pub fn three_d_params_as(from: &str, params: &Value, to: &str) -> Value { value.clone_from(v); } } + if out.contains_key("bevel") { + for key in [BEVEL_NAME, BEVEL_PROFILE] { + if let Some(v) = current.get(key).filter(|v| !v.is_null()) { + out.insert(key.into(), v.clone()); + } + } + } if to != crate::REVOLVE { for key in ["rotationX", "rotationY", "rotationZ"] { if let Some(a) = out.get(key).and_then(Value::as_f64).filter(|a| !(-180.0..=180.0).contains(a)) { @@ -170,14 +179,66 @@ pub fn view_options(p: &Value) -> View { } } -/// Extrude & Bevel's parameters. `bevel` is `"none"` or a [`BevelShape`] id. +/// The custom bevel's name parameter: the name the bevels file gave it, kept for the menus. +pub const BEVEL_NAME: &str = "bevelName"; +/// The custom bevel's points parameter: `[[across, down], …]`, shares of the bevel's width and +/// height from the cap's edge `[0, 0]` to the side wall `[1, 1]` (a copy of the bevel's path, so +/// the document draws it without the bevels file). +pub const BEVEL_PROFILE: &str = "bevelProfile"; + +/// The points of `v`, a [`BEVEL_PROFILE`] value; `None` unless it is an array of `[x, y]` number +/// pairs that make a [`BevelProfile`]. +fn bevel_profile(v: &Value) -> Option { + let list = v.as_array().filter(|a| a.len() <= BevelProfile::MAX_POINTS)?; + let pts: Option> = list + .iter() + .map(|pt| match pt.as_array().map(Vec::as_slice) { + Some([x, y]) => Some((x.as_f64()?, y.as_f64()?)), + _ => None, + }) + .collect(); + BevelProfile::new(&pts?) +} + +/// The bevel shape of parameters `p`: `bevel` `"none"` (none), a built-in [`BevelShape`] id, or +/// `"custom"` with its points in [`BEVEL_PROFILE`] (none when they do not make a profile). +pub(crate) fn bevel_shape(p: &Value) -> Option { + match text(p, "bevel", "none") { + "custom" => p.get(BEVEL_PROFILE).and_then(bevel_profile).map(BevelShape::Custom), + id => BevelShape::parse(id), + } +} + +/// Check the custom bevel parameters of `p`: `bevel` `"custom"` needs [`BEVEL_PROFILE`], whose +/// points, when given, must make a profile, and [`BEVEL_NAME`] is a string. +fn validate_bevel(p: &Value) -> Result<(), String> { + let most = BevelProfile::MAX_POINTS; + if let Some(v) = p.get(BEVEL_PROFILE) + && !v.is_null() + && bevel_profile(v).is_none() + { + return Err(format!( + "{BEVEL_PROFILE} must be 2 to {most} [x, y] points, each share between 0 and 1, from [0, 0] (the cap's edge) to [1, 1] (the side wall)" + )); + } + if text(p, "bevel", "none") == "custom" && p.get(BEVEL_PROFILE).is_none_or(Value::is_null) { + return Err(format!("bevel custom needs {BEVEL_PROFILE}, the bevel's points")); + } + if p.get(BEVEL_NAME).is_some_and(|v| !v.is_string() && !v.is_null()) { + return Err(format!("{BEVEL_NAME} must be a string")); + } + Ok(()) +} + +/// Extrude & Bevel's parameters. `bevel` is `"none"`, a [`BevelShape`] id, or `"custom"` with +/// its points in [`BEVEL_PROFILE`]. pub fn extrude_options(p: &Value) -> Extrude { Extrude { depth: num(p, "depth", 50.0), twist: num(p, "twist", 0.0), taper: num(p, "taper", 100.0) / 100.0, cap: flag(p, "cap", true), - bevel: BevelShape::parse(text(p, "bevel", "none")).map(|shape| Bevel { + bevel: bevel_shape(p).map(|shape| Bevel { shape, width: num(p, "bevelWidth", 4.0), height: num(p, "bevelHeight", 4.0), @@ -354,12 +415,12 @@ fn validate_solid_params(id: &str, p: &Value) -> Result<(), String> { graphics::validate(id, p)?; wireframe::validate_render(id, p)?; if let Some(v) = p.get("bevel") - && !v.as_str().is_some_and(|s| s == "none" || BevelShape::parse(s).is_some()) + && !v.as_str().is_some_and(|s| s == "none" || s == "custom" || BevelShape::parse(s).is_some()) { let names: Vec<_> = BevelShape::ALL.iter().map(|b| b.id()).collect(); - return Err(format!("bevel must be none or one of {}", names.join(", "))); + return Err(format!("bevel must be none or one of {}, or custom with {BEVEL_PROFILE}", names.join(", "))); } - Ok(()) + validate_bevel(p) } /// The name an error gives 3D effect `id`. diff --git a/crates/effects/src/solids/classic.rs b/crates/effects/src/solids/classic.rs index 609743fe03..88764122d4 100644 --- a/crates/effects/src/solids/classic.rs +++ b/crates/effects/src/solids/classic.rs @@ -7,7 +7,7 @@ use serde_json::Value; use vectorcraft_doc::color::{BlendMode, Color, Paint}; use vectorcraft_doc::{Appearance, AppearanceItem, FillLayer, Node}; use vectorcraft_geom::Rect; -use vectorcraft_three_d::{Bevel, BevelShape, ClassicShading, ClassicSurface, Extrude, Facet, Light}; +use vectorcraft_three_d::{Bevel, ClassicShading, ClassicSurface, Extrude, Facet, Light}; use super::graphics::map_art::{self, MapArt, MapBudget, SolidLayout}; use crate::util::{flag, num, text}; @@ -44,13 +44,7 @@ pub fn classic_extrude_options(p: &Value) -> Extrude { Extrude { depth: num(p, "depth", 50.0), cap: flag(p, "cap", true), - bevel: BevelShape::parse(text(p, "bevel", "none")).map(|shape| Bevel { - shape, - width: height, - height, - inside: flag(p, "bevelInside", false), - ..Bevel::default() - }), + bevel: super::bevel_shape(p).map(|shape| Bevel { shape, width: height, height, inside: flag(p, "bevelInside", false), ..Bevel::default() }), hidden: flag(p, "drawHiddenFaces", false) || classic_shading(p).surface == ClassicSurface::Wireframe, // The numbered surfaces are laid out only for an effect that maps art onto them. map_surfaces: !map_art::surface_maps(p).is_empty(), @@ -119,9 +113,15 @@ const FLAGS: [&str; 7] = ["cap", "bevelInside", "lightBehind", "drawHiddenFaces" /// Check Extrude & Bevel (Classic)'s parameters `p` (its defaults filled in): every key is one of /// its parameters, numbers are in range, flags are true or false, `surface`, `shadingColor` and /// `shadingCustom` name a surface, a shading color and a #rrggbb color, and `mapArt` holds valid -/// maps. +/// maps. A custom bevel's name and points ([`super::BEVEL_NAME`], [`super::BEVEL_PROFILE`]) are +/// parameters too, checked with Extrude & Bevel's. pub fn validate(p: &Value) -> Result<(), String> { - validate_classic(CLASSIC_EXTRUDE, p, &RANGES, &FLAGS)?; + let mut rest = p.clone(); + if let Some(m) = rest.as_object_mut() { + m.remove(super::BEVEL_NAME); + m.remove(super::BEVEL_PROFILE); + } + validate_classic(CLASSIC_EXTRUDE, &rest, &RANGES, &FLAGS)?; map_art::validate(CLASSIC_EXTRUDE, p) } diff --git a/crates/effects/src/solids/source.rs b/crates/effects/src/solids/source.rs index d71b2993af..b789a05782 100644 --- a/crates/effects/src/solids/source.rs +++ b/crates/effects/src/solids/source.rs @@ -8,7 +8,7 @@ use std::borrow::Cow; use std::sync::Arc; use vectorcraft_doc::{Appearance, AppearanceItem, Document, FillLayer, Node, NodeKind}; -use vectorcraft_geom::{FillRule, PathData, Point, Rect, SubPath}; +use vectorcraft_geom::{FillRule, PathData, Rect, SubPath}; use vectorcraft_pathops as po; use super::{MAX_MEMBERS, Scope, geometry, is_container, members, profile, region, reshape_members, solid_paints}; @@ -144,18 +144,17 @@ impl Resolver<'_> { } /// Does the plain image `c` lie wholly outside what the clips around it show together, each - /// clipping path with its own fill rule? Its frame, the pixel rectangle as its transform places - /// it, is cut to each clip in turn until nothing is left. An error when a cut fails or the cuts - /// pass [`MAX_IMAGE_CUTS`]: the image may show, so it can't be left out. + /// clipping path with its own fill rule? Its frame, the quadrilateral of its corners + /// ([`Node::image_corners`]: a distorted image's corners, else the pixel rectangle as its + /// transform places it), is cut to each clip in turn until nothing is left. An error when a + /// cut fails or the cuts pass [`MAX_IMAGE_CUTS`]: the image may show, so it can't be left out. fn hidden(&mut self, c: &Node) -> Result { let Some(shown) = &self.shown else { return Ok(false) }; - let NodeKind::Image(im) = &c.kind else { return Ok(false) }; + let Some(corners) = c.image_corners() else { return Ok(false) }; let Some(b) = c.visual_bounds() else { return Ok(true) }; if b.intersect(shown.bounds).area() <= 0.0 { return Ok(true); } - let (w, h) = (f64::from(im.width), f64::from(im.height)); - let corners = [(0.0, 0.0), (w, 0.0), (w, h), (0.0, h)].map(|(x, y)| im.xf * Point::new(x, y)); if corners.iter().any(|p| !p.x.is_finite() || !p.y.is_finite()) { return Err(image_refusal(self.label)); } diff --git a/crates/effects/src/solids/tests.rs b/crates/effects/src/solids/tests.rs index 518870dff2..f3054d85cf 100644 --- a/crates/effects/src/solids/tests.rs +++ b/crates/effects/src/solids/tests.rs @@ -1646,6 +1646,58 @@ fn parameters_are_validated_and_lengths_scale_with_the_object() { assert!(extrude_options(&json!({})).bevel.is_none()); } +/// `bevel` custom draws the points of `bevelProfile` in both Extrude & Bevels, with the other bevel +/// settings; bad points, a custom bevel without points and a name that is not a string are refused. +#[test] +fn custom_bevels_draw_their_points_and_bad_points_are_refused() { + let n = square_node(); + let notch = json!([[0, 0], [0.2, 0.6], [0.7, 0.4], [1, 1]]); + let custom = json!({"bevel": "custom", "bevelName": "Notch", "bevelProfile": notch, "bevelWidth": 10, "bevelRepeat": 2, "bevelBothSides": true}); + let b = extrude_options(&custom).bevel.unwrap(); + assert!(matches!(b.shape, BevelShape::Custom(_))); + assert_eq!((b.width, b.repeat, b.both_sides), (10.0, 2, true)); + let points: Vec<(f64, f64)> = match b.shape { + BevelShape::Custom(p) => p.points().collect(), + _ => vec![], + }; + assert_eq!(points.len(), 4); + assert!((points[2].0 - 0.7).abs() < 1e-4 && (points[2].1 - 0.4).abs() < 1e-4, "{points:?}"); + assert!(matches!(classic_extrude_options(&custom).bevel.map(|b| b.shape), Some(BevelShape::Custom(_)))); + for id in [EXTRUDE, CLASSIC_EXTRUDE] { + let classic_params = json!({"bevel": "classic", "bevelHeight": 10}); + let custom_params = json!({"bevel": "custom", "bevelProfile": notch, "bevelHeight": 10, "bevelName": "Notch"}); + assert!(validate_solid(&n, id, &custom_params).is_ok(), "{id}"); + let art = |p: &Value| { + let mut n = square_node(); + n.appearance.effects.push(fx(id, p.clone())); + solid_art(&n).unwrap() + }; + assert_ne!(art(&classic_params), art(&custom_params), "{id}"); + for (bad, err) in [ + (json!({"bevel": "custom"}), "bevel custom needs bevelProfile"), + (json!({"bevel": "custom", "bevelProfile": [[0, 0]]}), "bevelProfile must be 2 to 64"), + (json!({"bevel": "custom", "bevelProfile": [[0.1, 0], [1, 1]]}), "bevelProfile must be 2 to 64"), + (json!({"bevel": "custom", "bevelProfile": [[0, 0], [2, 0.5], [1, 1]]}), "bevelProfile must be 2 to 64"), + (json!({"bevel": "custom", "bevelProfile": [[0, 0], ["a", 0.5], [1, 1]]}), "bevelProfile must be 2 to 64"), + (json!({"bevel": "custom", "bevelProfile": "0,0 1,1"}), "bevelProfile must be 2 to 64"), + (json!({"bevel": "custom", "bevelProfile": notch, "bevelName": 3}), "bevelName must be a string"), + ] { + let e = validate_solid(&n, id, &bad).unwrap_err(); + assert!(e.contains(err), "{id} {bad}: {e}"); + } + } + // A loaded file whose points do not make a profile draws no bevel. + assert!(extrude_options(&json!({"bevel": "custom", "bevelProfile": [[0, 0]]})).bevel.is_none()); + // Changing the type keeps the custom bevel where the new effect takes a bevel, and drops it + // where it does not. + let classic = three_d_params_as(EXTRUDE, &custom, CLASSIC_EXTRUDE); + assert_eq!((&classic["bevel"], &classic[BEVEL_NAME], &classic[BEVEL_PROFILE]), (&json!("custom"), &json!("Notch"), ¬ch)); + assert!(validate_solid(&n, CLASSIC_EXTRUDE, &classic).is_ok()); + assert_eq!(three_d_params_as(CLASSIC_EXTRUDE, &classic, EXTRUDE)[BEVEL_PROFILE], notch); + let inflate = three_d_params_as(EXTRUDE, &custom, INFLATE); + assert!(inflate.get(BEVEL_PROFILE).is_none() && inflate.get(BEVEL_NAME).is_none()); +} + #[test] fn inflate_reads_twist_taper_and_cap() { let o = inflate_options(&json!({"twist": 90, "taper": 40, "cap": false})); diff --git a/crates/effects/src/tests.rs b/crates/effects/src/tests.rs index 2a34fb1d07..348d21ba38 100644 --- a/crates/effects/src/tests.rs +++ b/crates/effects/src/tests.rs @@ -504,6 +504,38 @@ fn warped_images_keep_document_keys_and_hidden_images_apart() { } } +/// A distorted image that a later effect leaves with no area after its warp is not cut, and its +/// corners stay finite. +#[test] +fn a_distorted_image_left_with_no_area_after_its_warp_keeps_finite_corners() { + use std::rc::Rc; + use std::sync::Arc; + + use vectorcraft_doc::NodeId; + let lift: crate::reshape::WarpMap = Rc::new(|p: Point| Point::new(p.x, p.y - p.x * 0.1)); + let mut image = (*warp_test_image(2)).clone(); + image.set_image_corners([(10.0, 0.0), (30.0, 0.0), (40.0, 40.0), (0.0, 40.0)].map(|(x, y)| Point::new(x, y))).unwrap(); + let mut art = Node::group(NodeId(1), vec![Arc::new(image)]); + let mut warped = crate::reshape::WarpedImages::new(); + warped.reserve(&art); + crate::reshape::mark_warped_images(&mut art, &lift, &std::collections::HashSet::new(), false, &mut 0, &mut warped); + // A later effect squeezes the placement flat. + if let Some(c) = art.children_mut() + && let NodeKind::Image(im) = &mut Arc::make_mut(&mut c[0]).kind + { + im.xf = Affine::scale_non_uniform(1.0, 0.0); + } + crate::reshape::cut_warped_images_within(&mut art, &warped, usize::MAX); + let mut finite = true; + art.walk(&mut |c| { + if let Some(q) = c.extras().image_quad.as_deref() { + finite &= q.iter().all(|p| p.x.is_finite() && p.y.is_finite()); + } + }); + assert!(finite); + assert_eq!(warp_test_images(&art).0, 1, "not cut"); +} + /// An image whose frame keeps its shape because the warp would pass the anchor budget keeps its /// pixels as they are; within the budget, both bend. #[test] @@ -2121,3 +2153,27 @@ fn color_halftones_radius_is_in_raster_pixels_not_a_distance() { crate::scale_effect(&mut e, 2.0); assert_eq!((e.params["maxRadius"].as_f64(), e.params["channel1"].as_f64()), (Some(20.0), Some(108.0))); } + +#[test] +fn a_pathfinder_effects_precision_is_a_distance_that_scales_with_the_object() { + for (id, _, _) in PATHFINDER_EFFECTS { + assert!(is_length(id, "precision", false), "{id}"); + assert_eq!(length_range(id, "precision"), Some(PATHFINDER_EFFECT_PRECISION), "{id}"); + assert!(!is_length(id, "removeRedundantPoints", false) && !is_length(id, "removeUnpainted", false), "{id}"); + // Scale Strokes & Effects scales the tolerance with the geometry it is refit to. + let mut e = crate::new_effect(id, &json!({"precision": 0.5, "removeUnpainted": true})).unwrap(); + crate::scale_effect(&mut e, 4.0); + assert_eq!(e.params["precision"].as_f64(), Some(2.0), "{id}"); + assert_eq!(e.params["removeUnpainted"], json!(true), "{id}"); + // An effect saved without the options scales the precision it evaluates with. + let mut e = crate::new_effect(id, &json!({})).unwrap(); + crate::scale_effect(&mut e, 3.0); + let scaled = e.params["precision"].as_f64().unwrap_or(f64::NAN); + assert!((scaled - PathfinderEffectOptions::default().precision * 3.0).abs() < 1e-12, "{id}: {scaled}"); + // A scale past the range and its inverse restore the precision, as with other distances. + let mut e = crate::new_effect(id, &json!({"precision": 8.0})).unwrap(); + crate::scale_effect(&mut e, 2.0); + crate::scale_effect(&mut e, 0.5); + assert_eq!(e.params["precision"].as_f64(), Some(8.0), "{id}"); + } +} diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 9a1531ede9..4f0d2bad63 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -8,6 +8,7 @@ pub mod arrowheads; mod artboardalign; mod assets; mod attributes; +pub mod bevels; pub mod brushlib; mod brushsym; mod buildcmds; @@ -321,6 +322,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(draw2::specs()); v.extend(xform::specs()); v.extend(effectcmd::specs()); + v.extend(bevels::specs()); v.extend(wireframe::specs()); v.extend(pathops::specs()); v.extend(compoundshape::specs()); @@ -890,6 +892,9 @@ pub use compoundshape::OPEN_PATHS_ADD_NO_AREA; /// Pathfinder Options (`Prefs::pathfinder`). pub use pathops::{PATHFINDER_PRECISION_RANGE, PathfinderOptions}; +/// The Pathfinder Options a new Pathfinder effect takes (`effect.apply`). +pub use effectcmd::pathfinder_effect_options; + /// The Attributes panel's state ([`Session::attributes_info`]) and how many recent URLs it keeps. pub use attributes::RECENT_URLS; pub use overprint::AttributesInfo; @@ -906,6 +911,10 @@ pub use gradpresets::{GradientPreset, GradientPresetEntry}; /// A saved Image Trace preset ([`crate::Prefs::trace_presets`]), and a change to the saved presets. pub use buildcmds::{TracePreset, TracePresetChange}; +/// The `format`, extensions and largest size of the tracing presets files +/// `imageTrace.presets.export` writes and `imageTrace.presets.import` reads. +pub use buildcmds::{TRACE_PRESET_EXTS, TRACE_PRESET_FORMAT, TRACE_PRESET_MAX_BYTES}; + /// An Image Trace made off the UI thread, and what it traced (#3098). pub use buildcmds::{TraceRun, Traced, image_trace_target}; diff --git a/crates/engine/src/cmd/addons/cutting/weed/geometry.rs b/crates/engine/src/cmd/addons/cutting/weed/geometry.rs index 0db89fb2ee..cb2c1c071d 100644 --- a/crates/engine/src/cmd/addons/cutting/weed/geometry.rs +++ b/crates/engine/src/cmd/addons/cutting/weed/geometry.rs @@ -109,11 +109,11 @@ impl<'a> Reader<'a> { Ok(union(parts)) } } - NodeKind::Image(im) => { - let (w, h) = (f64::from(im.width), f64::from(im.height)); - let corners = [Point::new(0.0, 0.0), Point::new(w, 0.0), Point::new(w, h), Point::new(0.0, h)].map(|p| im.xf * p); - self.polygon(&corners) - } + // A distorted image's frame joins its corners. + NodeKind::Image(_) => match n.image_corners() { + Some(corners) => self.polygon(&corners), + None => Ok(None), + }, // An instance of a symbol the document doesn't have draws nothing. NodeKind::SymbolInstance { .. } => match vectorcraft_render::effects::outline_object(Some(self.doc), n) { Some(art) => self.node(&art, depth + 1), diff --git a/crates/engine/src/cmd/addons/cutting/weed/tests.rs b/crates/engine/src/cmd/addons/cutting/weed/tests.rs index 69114f8991..4af36f30ee 100644 --- a/crates/engine/src/cmd/addons/cutting/weed/tests.rs +++ b/crates/engine/src/cmd/addons/cutting/weed/tests.rs @@ -663,6 +663,29 @@ fn an_image_is_measured_by_its_frame_as_turned() { assert!((end - (300.0 - (y - (300.0 - half)))).abs() < 0.01, "{end} at {y}"); } +#[test] +fn a_distorted_image_is_measured_by_the_frame_through_its_corners() { + let mut s = session(); + let im = vectorcraft_doc::ImageObject { + key: "image".into(), + width: 100, + height: 100, + xf: Affine::IDENTITY, + link: None, + placement: Default::default(), + pixels: None, + }; + insert(&mut s, |id| { + let mut n = Node::new(id, NodeKind::Image(Box::new(im))); + n.set_image_corners([Point::new(40.0, 0.0), Point::new(60.0, 0.0), Point::new(100.0, 100.0), Point::new(0.0, 100.0)]).unwrap(); + n + }); + let (b, end) = diamond_weeding(&mut s); + assert!((b.x0 + 10.0).abs() < 1e-3 && (b.y1 - 110.0).abs() < 1e-3, "{b:?}"); + // A quarter of the box down (y = 20), the line meets the side from (40, 0) to (0, 100). + assert!((end - 32.0).abs() < 0.01, "{end}"); +} + #[test] fn a_placed_file_is_measured_by_the_art_it_shows() { let dir = crate::tests_links::Folder::new("weed-placed"); diff --git a/crates/engine/src/cmd/appearance.rs b/crates/engine/src/cmd/appearance.rs index 6d2c7fd18f..3b23d62634 100644 --- a/crates/engine/src/cmd/appearance.rs +++ b/crates/engine/src/cmd/appearance.rs @@ -29,6 +29,7 @@ use vectorcraft_color::{BlendMode, Paint}; use vectorcraft_doc::appearance::SharedStack; use vectorcraft_doc::{Appearance, AppearanceItem, CharStyle, Document, FillLayer, Node, NodeKind, ParaStyle, StrokeLayer}; use vectorcraft_geom::Rect; +use vectorcraft_tools::builder::{edges, faces, is_live_paint}; use super::edit::{outermost, roots_of, selected_roots}; use super::opacitymask::percent; @@ -48,7 +49,7 @@ pub fn specs() -> Vec { "Add New Fill", ["Window", "Appearance"], Some("Cmd+/"), - "{ids?|id?, target?: \"object\"|\"contents\"} add a fill on top of each selected object's own stack, on an image right below its Contents row, with its top fill's paint (type without one: its characters' fill; else the default fill). With a fill row active (appearance.setActiveItem), no `ids`, no `id` and no `target: \"contents\"`, the new fill takes that row's paint, goes right above it, and becomes the active row; appearance.duplicateItem copies a whole row. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind (of a line, what the edit changes, and the row it adds when that row becomes the line's topmost visible row of its kind)", + "{ids?|id?, target?: \"object\"|\"contents\"} add a fill on top of each selected object's own stack, on an image right below its Contents row, with its top fill's paint (type without one: its characters' fill; else the default fill). In the contents of a Live Paint group the fill goes on its faces only, and its hidden source paths, like every contents edit, are left as they are. With a fill row active (appearance.setActiveItem), no `ids`, no `id` and no `target: \"contents\"`, the new fill takes that row's paint, goes right above it, and becomes the active row; appearance.duplicateItem copies a whole row. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind (of a line, what the edit changes, and the row it adds when that row becomes the line's topmost visible row of its kind)", has_doc, |s, p| add_item(s, p, true) ), @@ -57,7 +58,7 @@ pub fn specs() -> Vec { "Add New Stroke", ["Window", "Appearance"], Some("Cmd+Alt+/"), - "{ids?|id?, target?} add a stroke on top of each selected object's own stack, on an image right below its Contents row, with its top stroke's paint (else the default stroke) and that stroke's weight when it has paint, at least 1 pt. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind (of a line, what the edit changes, and the row it adds when that row becomes the line's topmost visible row of its kind)", + "{ids?|id?, target?} add a stroke on top of each selected object's own stack, on an image right below its Contents row, with its top stroke's paint (else the default stroke) and that stroke's weight when it has paint, at least 1 pt. In the contents of a Live Paint group the stroke goes on its edges only, and its hidden source paths are left as they are. On a path directly in a graph series (a series group's id stands for those paths), the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind (of a line, what the edit changes, and the row it adds when that row becomes the line's topmost visible row of its kind)", has_doc, |s, p| add_item(s, p, false) ), @@ -129,7 +130,7 @@ pub fn specs() -> Vec { "Eyedropper", [], None, - "{source: id, ids?, pickUp?, apply? (trees as eyedropper.setOptions, merged over the Eyedropper Options for this call), reverse?: bool, append?: bool, defaultsOnly?: bool} copy the attributes both picked up and applied (by default the whole appearance stack, opacity and blend mode, and from type to type the character and paragraph attributes using effective character dimensions while preserving target transforms) from `source` to ids (default: highlighted characters while editing type, after Select All in a frame of threaded text the text of the story's frames, leaving out `source`, otherwise the object selection; highlighted characters reject enabled non-neutral object transparency), the fill, stroke and weight also to the paint defaults; `defaultsOnly` updates only paint defaults and cannot be combined with ids, reverse or append; `reverse` (Alt-click) copies from the first selected object (or ids) onto `source` instead, or with nothing selected what the Eyedropper picked up last (a click without Alt); `append` (Shift+Alt-click) adds the source's fills, strokes and effects on top of each target's stack; placed gradients land at the same place relative to each target's bounds (defaults: fitted to new art); with an object of a dynamic symbol instance selected by Direct Selection and no ids, reverse, append or defaultsOnly, that object takes the source's fill and stroke (solid, none, gradient or pattern) for this instance only, as the Eyedropper Options allow, and a source that is not a path, compound path or type, or options that pick up neither color, are refused. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, the graph stores, for every label of its kind, the character attributes the pick gives all of its text, its object opacity and blend mode when transparency is applied, and with `append` its topmost visible fill and stroke rows of the kinds it adds; on a graph's axis line, tick mark or radar ring, its topmost visible fill and stroke rows, and when transparency is applied its object opacity and blend mode, for every line of its kind (a pick of some attributes without `append`: what it changes, and the paint, stroke weight and row transparency it applies to the topmost visible rows; with `append`: only the kinds of row it adds) → {ids}", + "{source: id, ids?, pickUp?, apply? (trees as eyedropper.setOptions, merged over the Eyedropper Options for this call), reverse?: bool, append?: bool, defaultsOnly?: bool} copy the attributes both picked up and applied (by default the whole appearance stack, opacity and blend mode, and from type to type the character and paragraph attributes using effective character dimensions while preserving target transforms) from `source` to ids (default: highlighted characters while editing type, after Select All in a frame of threaded text the text of the story's frames, leaving out `source`, otherwise the object selection; highlighted characters reject enabled non-neutral object transparency), the fill, stroke and weight also to the paint defaults; `defaultsOnly` updates only paint defaults and cannot be combined with ids, reverse or append; `reverse` (Alt-click) copies from the first selected object (or ids) onto `source` instead, or with nothing selected what the Eyedropper picked up last (a click without Alt); `append` (Shift+Alt-click) adds the source's fills, strokes and effects on top of each target's stack; a whole Live Paint group (selected, in ids, or `source` with `reverse`) takes the fill attributes on its faces and the stroke attributes on its edges (a whole-appearance pick: every fill row on each face and every stroke row on each edge, which keep their rows of the other kind and their effects; `append` adds the source's rows but not its object effects to them), and its hidden source paths keep their paint; a whole Live Paint group picked up (`source`, or selected first with `reverse`) gives its first face's fills with its first edge's strokes above them and the group's own opacity, blend mode and effects; placed gradients land at the same place relative to each target's bounds (defaults: fitted to new art); with an object of a dynamic symbol instance selected by Direct Selection and no ids, reverse, append or defaultsOnly, that object takes the source's fill and stroke (solid, none, gradient or pattern) for this instance only, as the Eyedropper Options allow, and a source that is not a path, compound path or type, or options that pick up neither color, are refused. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions, and the art of a graph design in a series, which is left out: docs/mcp.md); on a graph label, the graph stores, for every label of its kind, the character attributes the pick gives all of its text, its object opacity and blend mode when transparency is applied, and with `append` its topmost visible fill and stroke rows of the kinds it adds; on a graph's axis line, tick mark or radar ring, its topmost visible fill and stroke rows, and when transparency is applied its object opacity and blend mode, for every line of its kind (a pick of some attributes without `append`: what it changes, and the paint, stroke weight and row transparency it applies to the topmost visible rows; with `append`: only the kinds of row it adds) → {ids}", has_doc, copy_from ), @@ -280,7 +281,8 @@ impl ItemTarget { /// [`ItemTarget::targets`] of a fill (`fill`) or a stroke edit: on the topmost fill or stroke, a /// Live Paint group stands for its faces in a fill edit and for its edges in a stroke edit - /// ([`super::paint::live_paint_parts_skipped`]). + /// ([`super::paint::live_paint_parts_skipped`]); an item edit with `target: "contents"` leaves out + /// the parts of the other kind the same way ([`contents_skipped`]). pub(crate) fn targets_for(self, s: &Session, p: &Value, fill: bool) -> Result> { Ok(self.targets_and_skipped(s, p, fill)?.0) } @@ -290,13 +292,16 @@ impl ItemTarget { /// to new art. pub(crate) fn targets_and_skipped(self, s: &Session, p: &Value, fill: bool) -> Result<(Vec, bool)> { let mut ids = self.targets(s, p)?; - let mut skipped_any = false; - if self == ItemTarget::Top { - let skipped = super::paint::live_paint_parts_skipped(&s.doc()?.doc, &super::targets(s, p)?, fill); - let before = ids.len(); - ids.retain(|id| !skipped.contains(id)); - skipped_any = ids.len() != before; - } + // An item edit of the contents of a Live Paint group goes to its parts of the edited kind too. + let skipped = if self == ItemTarget::Top { + super::paint::live_paint_parts_skipped(&s.doc()?.doc, &super::targets(s, p)?, fill) + } else { + contents_skipped(s, p, fill)? + }; + let before = ids.len(); + ids.retain(|id| !skipped.contains(id)); + // A contents edit already leaves hidden source paths out of `ids`, so `skipped` is checked on its own too. + let skipped_any = ids.len() != before || !skipped.is_empty(); Ok((ids, skipped_any)) } @@ -491,15 +496,37 @@ pub(crate) fn subject_roots(s: &Session) -> Result> { /// Objects whose own appearance stack a command edits: `ids`/`id` (layers too; an id inside /// another given one is dropped), else the [`subject_roots`]; with `target: "contents"` the painted -/// objects inside the groups and layers among them ([`leaf_targets`]). +/// objects inside the groups and layers among them ([`leaf_targets`]), without the hidden source paths +/// of Live Paint groups. pub(crate) fn appearance_targets(s: &Session, p: &Value) -> Result> { - let roots = if p.get("ids").is_none() && p.get("id").is_none() { - subject_roots(s)? + let roots = appearance_roots(s, p)?; + if !targets_contents(p)? { + return Ok(roots); + } + let (_, _, hidden) = super::paint::live_paint_split(&s.doc()?.doc, &roots); + let mut ids = leaf_targets(s, &roots)?; + ids.retain(|id| !hidden.contains(id)); + Ok(ids) +} + +/// The objects [`appearance_targets`] starts from: `ids`/`id`, else the [`subject_roots`]. +fn appearance_roots(s: &Session, p: &Value) -> Result> { + if p.get("ids").is_none() && p.get("id").is_none() { + subject_roots(s) } else { let d = &s.doc()?.doc; - outermost(d, targets(s, p)?.into_iter().filter(|id| d.node(*id).is_some()).collect()) - }; - if targets_contents(p)? { leaf_targets(s, &roots) } else { Ok(roots) } + Ok(outermost(d, targets(s, p)?.into_iter().filter(|id| d.node(*id).is_some()).collect())) + } +} + +/// The parts of the Live Paint groups whose contents `p` targets (`target: "contents"`) that a fill +/// (`fill`) or stroke edit of those contents leaves as they are: their edges or faces. Empty without +/// `target: "contents"`. +pub(crate) fn contents_skipped(s: &Session, p: &Value, fill: bool) -> Result> { + if !targets_contents(p)? { + return Ok(HashSet::new()); + } + Ok(super::paint::live_paint_parts_skipped(&s.doc()?.doc, &appearance_roots(s, p)?, fill)) } /// The refusal of an appearance edit whose targets are all the art of graph designs drawn in graph series. @@ -897,7 +924,26 @@ fn set_active_item(s: &mut Session, p: &Value) -> Result { } fn add_item(s: &mut Session, p: &Value, fill: bool) -> Result { - let ids = require_targets(s, p, if fill { "appearance.addFill" } else { "appearance.addStroke" })?; + let cmd = if fill { "appearance.addFill" } else { "appearance.addStroke" }; + let mut ids = row_targets(s, p, cmd)?; + if ids.is_empty() { + // A selected Live Paint group left with only its hidden source paths has nothing to edit: it is + // still a selection, so the edit changes nothing. + let roots = appearance_roots(s, p)?; + if targets_contents(p)? && !roots.is_empty() && !super::paint::live_paint_split(&s.doc()?.doc, &roots).2.is_empty() { + return ok(); + } + return Err(bad(cmd, "select objects or give ids")); + } + // In the contents of a Live Paint group, a new fill goes on its faces and a new stroke on its edges; + // with no part of that kind, nothing changes. + let skipped = contents_skipped(s, p, fill)?; + if !skipped.is_empty() { + ids.retain(|id| !skipped.contains(id)); + if ids.is_empty() { + return ok(); + } + } let defaults = s.paint.clone(); // The panel's active Fill row, when the new fill goes on the selection: the new fill takes that // row's paint, right above it in each target that has it (others take their top fill's paint). @@ -1779,7 +1825,23 @@ fn copy_from(s: &mut Session, p: &Value) -> Result { // Reversed, the first selected object's attributes go onto the clicked object; with nothing // selected, what the Eyedropper picked up last does (#4382). let (source, mut targets) = if reverse { - let source = match leaf_targets(s, &selected)?.into_iter().next() { + // The selected objects are tried in order: a Live Paint group with a look is picked up as a whole + // ([`live_paint_look`]), any other object gives its first painted leaf, and a group with nothing to pick + // up (its hidden source paths are not what it draws) passes to the next object. + let d = &s.doc()?.doc; + let mut first = None; + for root in &selected { + if d.node(*root).and_then(live_paint_look).is_some() { + first = Some(*root); + break; + } + let (_, _, hidden) = super::paint::live_paint_split(d, &[*root]); + if let Some(leaf) = leaf_targets(s, &[*root])?.into_iter().find(|id| !hidden.contains(id)) { + first = Some(leaf); + break; + } + } + let source = match first { Some(first) => Some(first), None if s.eyedropper_sample.is_some() => None, None => return Err(bad(C, "select the object to copy from")), @@ -1788,10 +1850,45 @@ fn copy_from(s: &mut Session, p: &Value) -> Result { } else { (Some(clicked), leaf_targets(s, &selected)?) }; - targets.retain(|id| Some(*id) != source); + // A whole Live Paint group takes the fill attributes on its faces and the stroke attributes on its edges, and its + // hidden source paths keep their paint. + let roots = if reverse { vec![clicked] } else { selected }; + let (faces, edges, hidden) = super::paint::live_paint_split(&s.doc()?.doc, &roots); + // Some(true) for a face, Some(false) for an edge. + let part_of = |id: &NodeId| { + if faces.contains(id) { + Some(true) + } else if edges.contains(id) { + Some(false) + } else { + None + } + }; + let attrs_for = |id: &NodeId| { + let mut a = attrs; + match part_of(id) { + Some(true) => a.appearance.stroke = StrokeAttrs::NONE, + Some(false) => a.appearance.fill = FillAttrs::NONE, + None => {} + } + a + }; + // A pick of the whole appearance gives a face every fill row and an edge every stroke row. + let whole = attrs.appearance.fill == FillAttrs::ALL && attrs.appearance.stroke == StrokeAttrs::ALL; + // A source that is a Live Paint group is not one of its own targets: neither are its faces and edges. + let mut inside_source = HashSet::new(); + if let Some(n) = source.and_then(|id| s.doc().ok()?.doc.node(id)).filter(|n| is_live_paint(n)) { + n.walk(&mut |c| { + inside_source.insert(c.id); + }); + } + targets.retain(|id| Some(*id) != source && !hidden.contains(id) && !inside_source.contains(id)); let mut targets = without_design_art(&s.doc()?.doc, targets, C)?; let node = match source { - Some(id) => Arc::new(s.doc()?.doc.node(id).ok_or(EngineError::NoNode(id))?.clone()), + Some(id) => { + let n = s.doc()?.doc.node(id).ok_or(EngineError::NoNode(id))?; + Arc::new(live_paint_look(n).unwrap_or_else(|| n.clone())) + } None => s.eyedropper_sample.clone().ok_or_else(|| bad(C, "select the object to copy from"))?, }; let picked = Picked::of(&node); @@ -1919,7 +2016,17 @@ fn copy_from(s: &mut Session, p: &Value) -> Result { super::overprint::edit_counted(s, "Eyedropper", |d| { for id in &targets { if let Some(n) = d.node_mut(*id) { - picked.apply(n, &attrs, append, characters.get(id)); + match part_of(id) { + Some(fill) if whole && !append => picked.apply_rows(n, &attrs, fill), + // `append` does not add the picked object effects to a face or edge, as a whole pick keeps the part's + // own; a row's effects go with the row. + Some(_) => { + let effects = n.appearance.effects.len(); + picked.apply(n, &attrs_for(id), append, characters.get(id)); + n.appearance.effects.truncate(effects); + } + None => picked.apply(n, &attrs_for(id), append, characters.get(id)), + } } } check_text_bounds(d)?; @@ -2170,6 +2277,52 @@ impl Picked { } super::object::snap_if_aligned(n); } + + /// A whole pick ([`Self::apply`] with every fill and stroke attribute) onto a Live Paint face + /// (`fill`) or edge: the face's fills (the edge's strokes) become the picked ones, and its rows of + /// the other kind and its effects stay as they are. + fn apply_rows(&self, n: &mut Node, a: &EyedropperAttrs, fill: bool) { + if a.appearance.transparency { + n.opacity = self.opacity; + n.blend = self.blend; + } + let taken: Vec = self.placed(n.geometric_bounds()).items.into_iter().filter(|it| it.is_fill() == fill).collect(); + // The picked rows go where the part's first row of that kind was, the other rows keep their order; without + // such a row, fills go to the bottom and strokes to the top. + let items = &n.appearance.items; + let at = items.iter().position(|it| it.is_fill() == fill); + let at = at.map_or(if fill { 0 } else { items.iter().filter(|it| it.is_fill() != fill).count() }, |i| { + items.iter().take(i).filter(|it| it.is_fill() != fill).count() + }); + let mut kept: Vec = items.iter().filter(|it| it.is_fill() != fill).cloned().collect(); + kept.splice(at..at, taken); + n.appearance.items = kept; + super::object::snap_if_aligned(n); + } +} + +/// What the Eyedropper picks up from a whole Live Paint group `n`: its first face (else its first edge) with that +/// face's fills and the first edge's strokes above them, their gradients placed as on those parts, and the group's +/// own opacity, blend mode and effects. None for any other object, and for a group with no face and no edge. +fn live_paint_look(n: &Node) -> Option { + if !is_live_paint(n) { + return None; + } + let (face, edge) = (faces(n).first().copied(), edges(n).first().copied()); + let mut look = (**face.or(edge)?).clone(); + let rows = |part: Option<&Arc>, fill: bool| -> Vec { + part.map(|p| p.appearance.items.iter().filter(|it| it.is_fill() == fill).cloned().collect()).unwrap_or_default() + }; + // The edge's stroke gradients, placed relative to the look's bounds as they are to the edge's. + let mut strokes = Appearance { items: rows(edge, false), ..Default::default() }; + if let (Some(from), Some(to)) = (edge.and_then(|e| e.geometric_bounds()), look.geometric_bounds()) { + strokes.rebase_gradients(from, to); + } + look.appearance.items = rows(face, true).into_iter().chain(strokes.items).collect(); + look.appearance.effects = n.appearance.effects.clone(); + look.opacity = n.opacity; + look.blend = n.blend; + Some(look) } /// The focal (topmost) fill and stroke attributes `a` of `from` onto `to`. Taking a colour creates diff --git a/crates/engine/src/cmd/arrowheads.rs b/crates/engine/src/cmd/arrowheads.rs index 340cf98459..cef54db187 100644 --- a/crates/engine/src/cmd/arrowheads.rs +++ b/crates/engine/src/cmd/arrowheads.rs @@ -378,13 +378,14 @@ impl Session { } } -fn same_file(a: &str, b: &str) -> bool { +pub(super) fn same_file(a: &str, b: &str) -> bool { let canon = |p: &str| std::fs::canonicalize(p).unwrap_or_else(|_| std::path::PathBuf::from(p)); std::path::Path::new(a) == std::path::Path::new(b) || canon(a) == canon(b) } -/// The document in the arrowheads file at `path`; `None` when there is no file. -fn read(path: &str) -> std::result::Result, String> { +/// The document in the arrowheads file at `path` (or another such file of the user's, as the +/// bevels file); `None` when there is no file. +pub(super) fn read(path: &str) -> std::result::Result, String> { let size = match std::fs::metadata(path) { Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None), Err(e) => return Err(format!("{path}: {e}")), @@ -412,13 +413,13 @@ fn skipped(s: &Session) -> Vec { /// The arrowheads file at `path` checked for reading against the automation roots in force: an agent /// confined to read roots reaches the file only inside them. The error names the file by its file /// name outside them. -fn may_reach(path: &str) -> Result<()> { +pub(super) fn may_reach(path: &str) -> Result<()> { crate::file_access::check_read(path).map_err(|e| super::fileio::naming_in_error(EngineError::Other(e), path)) } /// `msg`, an error about the arrowheads file at `path`, as the request being served may see it: the /// file named whole inside the read roots, else by its file name. -fn shown_error(msg: &str, path: Option<&str>) -> String { +pub(super) fn shown_error(msg: &str, path: Option<&str>) -> String { let Some(path) = path else { return msg.to_string() }; match super::fileio::naming_in_error(EngineError::Other(msg.to_string()), path) { EngineError::Other(m) => m, diff --git a/crates/engine/src/cmd/bevels.rs b/crates/engine/src/cmd/bevels.rs new file mode 100644 index 0000000000..3fcaa1094c --- /dev/null +++ b/crates/engine/src/cmd/bevels.rs @@ -0,0 +1,378 @@ +//! Custom bevels for Extrude & Bevel and Extrude & Bevel (Classic). The bevels file is a native +//! document kept next to the preferences ([`Session::attach_bevels_file`]). Each of its symbols +//! whose art is one open path is one bevel, listed by the symbol's name after the built-in shapes +//! in the Bevel Shape menus. The path runs from its first anchor, at the cap's edge, to its last, +//! at the side wall: across the page is across the bevel's width and down the page is along its +//! height, whichever way the path is drawn, and points past its ends are held to them. Curves are +//! cut into straight lines, at most [`BevelProfile::MAX_POINTS`] points in all. Saving the file +//! reloads the bevels. An effect that uses a custom bevel carries a copy of its points +//! (`bevelProfile`), so its document draws it anywhere. + +use std::sync::Arc; + +use serde_json::{Value, json}; +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::{Appearance, Document, Node, NodeId, NodeKind, Symbol}; +use vectorcraft_geom::{Affine, PathData, PathEl, Point, SubPath}; +use vectorcraft_render::effects::{BEVEL_NAME, BEVEL_PROFILE, BevelProfile}; + +use super::arrowheads::{may_reach, read, same_file, shown_error}; +use super::{CommandSpec, Result, Session, always, bad, cmd}; + +/// The bevels file's name, in the folder of the preferences. +pub const FILE_NAME: &str = "Bevels.vectorcraft"; +/// The most bevels read from the file; symbols past it are skipped. +pub const MAX_BEVELS: usize = 256; +/// The most anchors a bevel's path may have; a symbol past it is skipped. +pub const MAX_ANCHORS: usize = 4096; +/// The most points a bevel's path is cut into before it is simplified; a symbol past it is skipped. +pub const MAX_LINE_POINTS: usize = 8192; +/// The most point-to-line distances simplifying the bevels of one file may measure; a symbol that +/// needs more than is left is skipped as too detailed. +pub const MAX_SIMPLIFY_WORK: u64 = 40_000_000; + +pub fn specs() -> Vec { + vec![ + cmd!( + query "threeD.bevels.list", + "Bevels", + [], + None, + "{} → {bevels: [{name (effect.apply and effect.setParams take Extrude & Bevel's and Extrude & Bevel (Classic)'s `bevel` as {custom: name}), points: [[x, y]…] (shares of the bevel's width and height from the cap's edge [0, 0] to the side wall [1, 1])}], file: the bevels file's path or null (no file here, as on the web), skipped: [{name, reason}] symbols of the file that are not bevels, error: why the file could not be read, or null} the custom bevels, listed after the built-in shapes in the Bevel Shape menus", + always, + list + ), + cmd!( + "threeD.bevels.edit", + "Edit Bevels", + [], + None, + "{} open the bevels file (a native document next to the preferences; created first with one example bevel when it is missing). Each symbol in it whose art is one open path is one custom bevel named after the symbol: the path runs from its first anchor at the cap's edge to its last at the side wall, across the page across the bevel's width and down the page along its height. Saving the file reloads the bevels → {path, created: whether the file was made now}", + has_file, + edit + ), + cmd!( + "threeD.bevels.reload", + "Reload Bevels", + [], + None, + "{} read the bevels file again (a save of it from VectorCraft does this already) → {count, skipped: [{name, reason}]}", + has_file, + reload + ), + ] +} + +/// A custom bevel: its name and its points, (share of the width, share of the height). +#[derive(Clone, Debug, PartialEq)] +pub struct CustomBevel { + pub name: String, + pub points: Vec<(f64, f64)>, +} + +impl CustomBevel { + /// The points as `bevelProfile` holds them. + pub fn profile_json(&self) -> Value { + json!(self.points.iter().map(|&(x, y)| [x, y]).collect::>()) + } +} + +/// The custom bevels read from the bevels file. +#[derive(Default)] +pub struct Bevels { + path: Option, + bevels: Vec>, + skipped: Vec<(String, String)>, + error: Option, +} + +impl Bevels { + /// The bevels file's path; `None` without one (the web, runs without preferences). + pub fn path(&self) -> Option<&str> { + self.path.as_deref() + } + /// The bevels, in the order of the file's symbols. + pub fn bevels(&self) -> &[Arc] { + &self.bevels + } + /// Bevel `name`. + pub fn get(&self, name: &str) -> Option> { + self.bevels.iter().find(|b| b.name == name).cloned() + } + fn set(&mut self, read: Read) { + (self.bevels, self.skipped) = (read.bevels.into_iter().map(Arc::new).collect(), read.skipped); + self.error = None; + } +} + +/// The bevels a document holds, and the symbols that are not bevels with the reason. +#[derive(Debug, Default)] +pub struct Read { + pub bevels: Vec, + pub skipped: Vec<(String, String)>, +} + +/// The bevels of document `doc`: one per symbol, up to [`MAX_BEVELS`] (see the module docs). +pub fn bevels_of(doc: &Document) -> Read { + bevels_within(doc, MAX_SIMPLIFY_WORK) +} + +/// [`bevels_of`] with `work` point-to-line distances to simplify the paths with. +pub fn bevels_within(doc: &Document, mut work: u64) -> Read { + let mut out = Read::default(); + for (i, sym) in doc.symbols.iter().enumerate() { + if i >= MAX_BEVELS { + out.skipped.push((sym.name.clone(), format!("only the first {MAX_BEVELS} symbols are read"))); + continue; + } + if out.bevels.iter().any(|b| b.name == sym.name) { + out.skipped.push((sym.name.clone(), "another symbol has this name".into())); + continue; + } + match points_of(&sym.art, &mut work) { + Ok(points) => out.bevels.push(CustomBevel { name: sym.name.clone(), points }), + Err(why) => out.skipped.push((sym.name.clone(), why.into())), + } + } + out +} + +/// The one open path of art `n`: `n` itself, or the one member of groups that hold one member each. +fn open_path(n: &Node) -> Option<&PathData> { + match &n.kind { + NodeKind::Path { path, guide: false, .. } if path.subpaths.len() == 1 && !path.subpaths[0].closed => Some(path), + NodeKind::Group { children, clip: false } if children.len() == 1 => open_path(&children[0]), + _ => None, + } +} + +/// The profile points of a bevel symbol's art `n` (see the module docs), simplified within `work` +/// point-to-line distances, which it uses up. +fn points_of(n: &Node, work: &mut u64) -> std::result::Result, &'static str> { + let path = open_path(n).ok_or("its art is not one open path")?; + if path.anchor_count() > MAX_ANCHORS { + return Err("its path has too many anchors for a bevel"); + } + let mut line: Vec = vec![]; + let tolerance = path.bounds().map_or(1.0, |b| b.width().hypot(b.height()) / 2000.0).max(1e-9); + // One segment at a time, so a path past the limit stops being cut at the segment that passes it. + let mut at: Option = None; + for &el in path.to_bezpath().elements() { + if line.len() > MAX_LINE_POINTS { + return Err("its path is too detailed for a bevel"); + } + match (el, at) { + (PathEl::MoveTo(p), _) => line.push(p), + (_, Some(start)) => vectorcraft_geom::flatten([PathEl::MoveTo(start), el], tolerance, |e| { + if let PathEl::LineTo(p) = e { + line.push(p); + } + }), + (_, None) => {} + } + at = el.end_point().or(at); + } + if line.len() > MAX_LINE_POINTS { + return Err("its path is too detailed for a bevel"); + } + let (Some(&first), Some(&last)) = (line.first(), line.last()) else { return Err("its path has no length") }; + let (dx, dy) = (last.x - first.x, last.y - first.y); + let size = path.bounds().map_or(0.0, |b| b.width().hypot(b.height())); + if !(dx.abs() > size * 1e-6 && dy.abs() > size * 1e-6 && size.is_finite()) { + return Err("its ends are not apart both across and down"); + } + let mut pts: Vec<(f64, f64)> = line.iter().map(|p| (((p.x - first.x) / dx).clamp(0.0, 1.0), ((p.y - first.y) / dy).clamp(0.0, 1.0))).collect(); + pts.dedup_by(|a, b| (a.0 - b.0).abs() < 1e-9 && (a.1 - b.1).abs() < 1e-9); + if pts.len() < 2 { + return Err("its ends are not apart both across and down"); + } + // The ends map to the corners exactly. + let last = pts.len() - 1; + (pts[0], pts[last]) = ((0.0, 0.0), (1.0, 1.0)); + let pts = simplified(&pts, work).ok_or("its path is too detailed for a bevel")?; + BevelProfile::new(&pts).ok_or("its path is too detailed for a bevel")?; + Ok(pts) +} + +/// `pts` with the fewest points the Ramer-Douglas-Peucker rule keeps at a tolerance (from a +/// thousandth of the bevel, doubled until they fit) that leaves at most +/// [`BevelProfile::MAX_POINTS`]. The first and last points are always kept. `None` when that +/// measures more point-to-line distances than `work` has left. +fn simplified(pts: &[(f64, f64)], work: &mut u64) -> Option> { + let mut eps = 1e-3; + loop { + let out = rdp(pts, eps, work)?; + if out.len() <= BevelProfile::MAX_POINTS || eps > 2.0 { + return Some(out); + } + eps *= 2.0; + } +} + +/// The points of `pts` Ramer-Douglas-Peucker keeps at tolerance `eps`; `None` when that measures +/// more point-to-line distances than `work` has left. +fn rdp(pts: &[(f64, f64)], eps: f64, work: &mut u64) -> Option> { + if pts.len() < 3 { + return Some(pts.to_vec()); + } + let mut keep = vec![false; pts.len()]; + keep[0] = true; + keep[pts.len() - 1] = true; + let mut stack = vec![(0, pts.len() - 1)]; + while let Some((a, b)) = stack.pop() { + *work = work.checked_sub((b - a).saturating_sub(1) as u64)?; + let (p, q) = (pts[a], pts[b]); + let (vx, vy) = (q.0 - p.0, q.1 - p.1); + let len = vx.hypot(vy); + let far = (a + 1..b) + .map(|i| { + let (wx, wy) = (pts[i].0 - p.0, pts[i].1 - p.1); + let d = if len > 0.0 { (vx * wy - vy * wx).abs() / len } else { wx.hypot(wy) }; + (i, d) + }) + .fold(None, |best: Option<(usize, f64)>, (i, d)| if best.is_none_or(|(_, bd)| d > bd) { Some((i, d)) } else { best }); + if let Some((i, d)) = far + && d > eps + { + keep[i] = true; + stack.push((a, i)); + stack.push((i, b)); + } + } + Some(pts.iter().zip(keep).filter_map(|(p, k)| k.then_some(*p)).collect()) +} + +/// The document a missing bevels file starts as: one example bevel, a chamfer with a notch. +pub fn starter() -> Document { + let mut doc = Document::new(612.0, 792.0); + doc.title = "Bevels".into(); + let name = "Example Bevel"; + let pts = [Point::new(0.0, 0.0), Point::new(10.0, 40.0), Point::new(55.0, 30.0), Point::new(100.0, 100.0)]; + let art = + Node::path(NodeId(0), PathData::single(SubPath::polyline(&pts, false)), Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0)); + let art = doc.reid(&art); + doc.symbols.push(Symbol { name: name.into(), art: Arc::new(art), dynamic: false }); + let id = doc.alloc_id(); + let instance = Node::new(id, NodeKind::SymbolInstance { symbol: name.into(), xf: Affine::translate((256.0, 346.0)) }); + let layer = doc.layers.first().map(|l| l.id); + let _ = doc.insert(layer, 0, instance); + doc +} + +impl Session { + /// Keep the custom bevels in the file at `path` and read the bevels it holds (none while it is + /// missing; an unreadable file is reported by `threeD.bevels.list`). + pub fn attach_bevels_file(&mut self, path: String) { + self.bevels.path = Some(path); + self.reload_bevels(); + } + + /// Read the bevels file again. + fn reload_bevels(&mut self) { + let Some(path) = self.bevels.path.clone() else { return }; + match read(&path) { + Ok(Some(doc)) => self.bevels.set(bevels_of(&doc)), + Ok(None) => self.bevels.set(Read::default()), + Err(e) => { + self.bevels.set(Read::default()); + self.bevels.error = Some(e); + } + } + } + + /// A document was saved to `path`: when that is the bevels file, its bevels are read back from + /// what was written. + pub(crate) fn bevels_saved(&mut self, path: &str) { + if self.bevels.path.as_deref().is_some_and(|b| same_file(b, path)) { + self.reload_bevels(); + } + } +} + +/// The command parameter that holds the points a custom bevel given by name had when the command +/// ran. The journal records it, so a replay draws the same bevel after the bevels file changes or +/// loses that name. +pub const SAVED_BEVEL: &str = "savedBevel"; + +/// `params` of an effect with `bevel` given as `{custom: name}`: the bevel of the bevels file named +/// so, stored as `bevel` `"custom"` with its `bevelName` and `bevelProfile`. The command's +/// [`SAVED_BEVEL`] points (`p`), when given, are used in place of the file's, and the points used +/// join the journal entry as [`SAVED_BEVEL`]. Other values are left for the effect to check. +pub(crate) fn resolve_custom(s: &mut Session, p: &Value, params: &mut Value, cmd: &str) -> Result<()> { + let Some(Value::Object(o)) = params.get("bevel") else { return Ok(()) }; + let name = match (o.len(), o.get("custom")) { + (1, Some(Value::String(name))) => name.clone(), + _ => return Err(bad(cmd, "bevel: give a shape id, or {custom: name} for a bevel of the bevels file (threeD.bevels.list)")), + }; + let points = match p.get(SAVED_BEVEL).filter(|v| !v.is_null()) { + Some(saved) => saved.clone(), + None => s.bevels.get(&name).ok_or_else(|| bad(cmd, format!("no custom bevel {name} (see threeD.bevels.list)")))?.profile_json(), + }; + s.note_journal(SAVED_BEVEL, points.clone()); + params["bevel"] = json!("custom"); + params[BEVEL_NAME] = json!(name); + params[BEVEL_PROFILE] = points; + Ok(()) +} + +fn has_file(s: &Session) -> std::result::Result<(), String> { + if s.bevels.path.is_some() { Ok(()) } else { Err("no bevels file here".into()) } +} + +fn skipped(s: &Session) -> Vec { + s.bevels.skipped.iter().map(|(name, reason)| json!({"name": name, "reason": reason})).collect() +} + +fn list(s: &mut Session, _: &Value) -> Result { + let bevels: Vec = s.bevels.bevels.iter().map(|b| json!({"name": b.name, "points": b.profile_json()})).collect(); + // Under automation read roots, a file outside them is not shown and its error names it by its file name. + let path = s.bevels.path.as_deref(); + let file = path.filter(|p| crate::file_access::check_read(p).is_ok()); + let error = s.bevels.error.as_deref().map(|e| shown_error(e, path)); + Ok(json!({"bevels": bevels, "file": file, "skipped": skipped(s), "error": error})) +} + +fn reload(s: &mut Session, _: &Value) -> Result { + const C: &str = "threeD.bevels.reload"; + if let Some(path) = &s.bevels.path { + may_reach(path)?; + } + s.reload_bevels(); + if let Some(e) = &s.bevels.error { + return Err(bad(C, e.clone())); + } + Ok(json!({"count": s.bevels.bevels.len(), "skipped": skipped(s)})) +} + +fn edit(s: &mut Session, _: &Value) -> Result { + const C: &str = "threeD.bevels.edit"; + let path = s.bevels.path.clone().ok_or_else(|| bad(C, "no bevels file here"))?; + // Checked before anything is made, brought to the front or opened. + may_reach(&path)?; + if let Some(dir) = std::path::Path::new(&path).parent() { + let dir = dir.to_string_lossy(); + std::fs::create_dir_all(&*dir).map_err(|e| super::fileio::naming_in_error(bad(C, format!("{dir}: {e}")), &dir))?; + } + // Made only when no file is there, also when another run makes one at the same moment. + let bytes = vectorcraft_format::save_file(&starter()); + let created = match crate::file_access::unconfined(|| super::fileio::write_new_file(&path, &bytes)) { + Ok(()) => true, + Err(_) if std::path::Path::new(&path).exists() => false, + Err(e) => return Err(bad(C, e.to_string())), + }; + if created { + s.reload_bevels(); + } + // Already open: that document comes to the front. + let open = s.documents().iter().position(|st| st.path.as_deref().is_some_and(|p| same_file(p, &path))); + match open { + Some(i) => { + s.set_active(i); + } + None => { + // Opened in the request's own scope, so the document keeps the roots it was opened under. + s.execute("document.open", &json!({ "path": path }))?; + } + } + Ok(json!({"path": path, "created": created})) +} diff --git a/crates/engine/src/cmd/brushlib.rs b/crates/engine/src/cmd/brushlib.rs index 9866d7d9af..fc5bbe120a 100644 --- a/crates/engine/src/cmd/brushlib.rs +++ b/crates/engine/src/cmd/brushlib.rs @@ -177,6 +177,7 @@ pub const BUILTIN: &[BuiltinBrushLibrary] = &[ BuiltinBrushLibrary { id: "bristle-brushes", name: "Bristle Brushes", make: bristle_brushes }, BuiltinBrushLibrary { id: "paint", name: "Paint", make: paint }, BuiltinBrushLibrary { id: "pattern-borders", name: "Pattern Borders", make: pattern_borders }, + BuiltinBrushLibrary { id: "decorative", name: "Decorative", make: decorative }, BuiltinBrushLibrary { id: "scatter-shapes", name: "Scatter Shapes", make: scatter_shapes }, BuiltinBrushLibrary { id: "stipple", name: "Stipple", make: stipple }, BuiltinBrushLibrary { id: "game-trails", name: "Game Trails", make: game_trails }, @@ -186,6 +187,8 @@ pub const BUILTIN: &[BuiltinBrushLibrary] = &[ BuiltinBrushLibrary { id: "engraving", name: "Engraving", make: engraving }, BuiltinBrushLibrary { id: "arrows", name: "Arrows", make: arrows }, BuiltinBrushLibrary { id: "image-brush", name: "Image Brush", make: image_brush }, + BuiltinBrushLibrary { id: "artistic", name: "Artistic Brushes", make: artistic }, + BuiltinBrushLibrary { id: "vector-packs", name: "Vector Packs", make: vector_packs }, ]; /// Built-in library `id`, made once. @@ -239,6 +242,42 @@ fn art(name: &str, art: Node, colorization: Colorization) -> Brush { Brush { name: name.into(), kind: BrushKind::Art(ArtBrush { art, colorization, ..Default::default() }) } } +/// Artistic: four original vector compositions that stretch along a path and take its color. +fn artistic() -> BrushLibrary { + let orbit = group(vec![ + black(band(100.0, 1.4, 64, |x| 3.0 * (x * std::f64::consts::TAU / 40.0).sin())), + black(band(100.0, 1.4, 64, |x| -3.0 * (x * std::f64::consts::TAU / 40.0).sin())), + ]); + let mut petals = vec![black(band(100.0, 0.8, 4, |_| 0.0))]; + for i in 0..6 { + let x = 9.0 + 16.0 * i as f64; + let side = if i % 2 == 0 { 1.0 } else { -1.0 }; + petals.push(black(polygon(&[(x - 6.0, 0.0), (x - 2.0, 5.0 * side), (x + 5.0, 7.0 * side), (x + 2.0, 2.0 * side)]))); + } + let mut lattice = vec![black(band(100.0, 0.9, 4, |_| 0.0))]; + for i in 0..5 { + let x = 20.0 * i as f64; + lattice.push(black(polygon(&[(x, -4.0), (x + 1.0, -4.0), (x + 20.0, 4.0), (x + 19.0, 4.0)]))); + lattice.push(black(polygon(&[(x, 4.0), (x + 1.0, 4.0), (x + 20.0, -4.0), (x + 19.0, -4.0)]))); + } + let mut facets = Vec::new(); + for i in 0..8 { + let x = 12.5 * i as f64; + let high = if i % 2 == 0 { 6.0 } else { 3.5 }; + facets.push(black(polygon(&[(x, -high), (x + 11.0, -high / 2.0), (x + 12.5, 0.0), (x + 11.0, high / 2.0), (x, high)]))); + } + built( + "Artistic Brushes", + Document::new(100.0, 100.0), + vec![ + art("Orbit Lines", orbit, Colorization::Tints), + art("Petal Garland", group(petals), Colorization::Tints), + art("Lattice Braid", group(lattice), Colorization::Tints), + art("Facet Sweep", group(facets), Colorization::Tints), + ], + ) +} + /// Original fine-line art for an engraving-style brush library. fn engraving() -> BrushLibrary { let lines = |count: usize, width: f64, spacing: f64| { @@ -653,6 +692,47 @@ fn pattern_borders() -> BrushLibrary { built("Pattern Borders", Document::new(100.0, 100.0), brushes) } +/// Decorative: repeating plant, flower and hanging ornaments drawn as original vector tiles. +/// Every tile joins the next at x = 0 and 48 so open and closed paths stay continuous. +fn decorative() -> BrushLibrary { + let stem = || black(shapes::rectangle(Rect::new(0.0, -0.65, 48.0, 0.65))); + let vine = group(vec![ + stem(), + black(polygon(&[(8.0, -0.2), (12.0, -5.0), (24.0, -8.0), (20.0, -1.0)])), + black(polygon(&[(28.0, 0.2), (32.0, 5.0), (44.0, 8.0), (40.0, 1.0)])), + ]); + let mut blossoms = vec![stem()]; + for x in [12.0, 36.0] { + for (dx, dy) in [(0.0, -4.0), (4.0, 0.0), (0.0, 4.0), (-4.0, 0.0)] { + blossoms.push(black(shapes::ellipse(Rect::new(x + dx - 2.5, dy - 2.5, x + dx + 2.5, dy + 2.5)))); + } + blossoms.push(black(shapes::ellipse(Rect::new(x - 1.3, -1.3, x + 1.3, 1.3)))); + } + let flowers = group(blossoms); + let pennants = group(vec![ + black(shapes::rectangle(Rect::new(0.0, -5.2, 48.0, -4.2))), + black(polygon(&[(4.0, -4.2), (20.0, -4.2), (12.0, 10.0)])), + black(polygon(&[(28.0, -4.2), (44.0, -4.2), (36.0, 10.0)])), + ]); + let lanterns = group(vec![ + black(shapes::rectangle(Rect::new(0.0, -5.0, 48.0, -4.0))), + black(shapes::rectangle(Rect::new(11.4, -4.0, 12.6, -1.0))), + black(shapes::ellipse(Rect::new(7.0, -1.0, 17.0, 9.0))), + black(shapes::rectangle(Rect::new(35.4, -4.0, 36.6, -1.0))), + black(shapes::ellipse(Rect::new(31.0, -1.0, 41.0, 9.0))), + ]); + built( + "Decorative", + Document::new(100.0, 100.0), + vec![ + border("Leaf Vine", vine, None, PatternFit::Stretch), + border("Blossom Chain", flowers, None, PatternFit::Stretch), + border("Pennant Garland", pennants, None, PatternFit::Stretch), + border("Lantern String", lanterns, None, PatternFit::Stretch), + ], + ) +} + fn scatter(name: &str, art: Node, s: Scatter) -> Brush { Brush { name: name.into(), kind: BrushKind::Scatter(Scatter { art, ..s }) } } @@ -787,6 +867,38 @@ fn scatter_shapes() -> BrushLibrary { built("Scatter Shapes", doc, brushes) } +/// Vector Packs: four original, editable vector marks that follow the stroke color. +fn vector_packs() -> BrushLibrary { + let compass = group(vec![black(shapes::star(Point::ZERO, 10.0, 3.0, 8, 0.0)), black(shapes::ellipse(Rect::new(-1.5, -1.5, 1.5, 1.5)))]); + let sprig = group(vec![ + black(polygon(&[(-0.7, 10.0), (0.7, 10.0), (0.7, -10.0), (-0.7, -10.0)])), + black(polygon(&[(0.0, 5.0), (5.0, 2.0), (7.0, -1.0), (3.0, 0.0)])), + black(polygon(&[(0.0, 0.0), (-5.0, -3.0), (-7.0, -6.0), (-3.0, -5.0)])), + black(polygon(&[(0.0, -5.0), (5.0, -8.0), (7.0, -10.0), (3.0, -9.0)])), + ]); + let diamond = group(vec![ + black(polygon(&[(-9.0, 0.0), (-1.0, -9.0), (-1.0, -1.0)])), + black(polygon(&[(1.0, -9.0), (9.0, 0.0), (1.0, -1.0)])), + black(polygon(&[(9.0, 0.0), (1.0, 9.0), (1.0, 1.0)])), + black(polygon(&[(-1.0, 9.0), (-9.0, 0.0), (-1.0, 1.0)])), + ]); + let tide = group(vec![ + black(band(20.0, 1.2, 32, |x| -3.0 + 2.0 * (x * std::f64::consts::TAU / 20.0).sin())), + black(band(20.0, 1.2, 32, |x| 3.0 + 2.0 * (x * std::f64::consts::TAU / 20.0).sin())), + ]); + let settings = Scatter { size: (90.0, 110.0), spacing: (130.0, 160.0), colorization: Colorization::Tints, ..Default::default() }; + built( + "Vector Packs", + Document::new(100.0, 100.0), + vec![ + scatter("Compass Rose", compass, settings.clone()), + scatter("Botanical Sprig", sprig, settings.clone()), + scatter("Facet Diamond", diamond, settings.clone()), + scatter("Tide Crest", tide, settings), + ], + ) +} + /// Stipple: original dot-based scatter brushes for fine and broad shading along a path. fn stipple() -> BrushLibrary { let dot = |x: f64, y: f64, r: f64, opacity: f32| { @@ -1076,10 +1188,14 @@ pub fn library(s: &Session, key: &str) -> Option<(LibraryInfo, Arc return Some(found); } if let Some(b) = BUILTIN.iter().find(|b| b.id == key) { - return Some((builtin_info(b), builtin_library(key)?)); + return Some((builtin_info(b), builtin_library(b.id)?)); } - let id = libraries(s).into_iter().find(|l| l.name.eq_ignore_ascii_case(key))?.id; - library(s, &id) + if let Some(id) = libraries(s).into_iter().find(|l| l.name.eq_ignore_ascii_case(key)).map(|l| l.id) { + return library(s, &id); + } + // Keep the short built-in alias, but let a user or loaded library own its display name. + let b = key.eq_ignore_ascii_case("Artistic").then(|| BUILTIN.iter().find(|b| b.id == "artistic")).flatten()?; + Some((builtin_info(b), builtin_library(b.id)?)) } fn library_param(s: &Session, p: &Value, cmd: &str) -> Result<(LibraryInfo, Arc)> { diff --git a/crates/engine/src/cmd/brushsym.rs b/crates/engine/src/cmd/brushsym.rs index 6c0f651c00..fbd4512fa3 100644 --- a/crates/engine/src/cmd/brushsym.rs +++ b/crates/engine/src/cmd/brushsym.rs @@ -362,7 +362,7 @@ pub fn specs() -> Vec { "Symbol Sprayer", [], None, - "{points: [[x,y]…] (a third number is not used; one that isn't a number is an error), name?, radius?: 40, density?: 1..10 (5), scale?: 1, alt?: bool (remove instances), attributes?: {scrunch?, size?, spin?, screen?, stain?, style?: average|userDefined (average)}, color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), style?: name} spray instances into a symbol set → {id, count}. Each of `attributes` says what a new instance takes: average, the mean of the selected set's instances within `radius` of the stroke point (their spacing along the stroke, size, rotation, opacity, and the stain or style of the nearest one that has one at the mean amount), and with none there the symbol's size, no rotation, full opacity and no stain or style; or userDefined: spacing from the symbol's size and `density`, the symbol's size times `scale`, turned the way the stroke runs there (not turned for one point), full opacity, stained in full with `color` (default: the fill color), and the fill of graphic style `style` (default: the first style after the default one) in full; a `style` the document does not have is then an error. The stain and the style are both the instance's fill, and the style replaces the stain. Another key or value in `attributes` is an error", + "{points: [[x,y]…] (a third value is a number or null and is not used), name?, radius?: 40, density?: 1..10 (5; a number outside 1..10 is taken as the nearer end), scale?: 1, alt?: bool (remove instances), attributes?: {scrunch?, size?, spin?, screen?, stain?, style?: average|userDefined (average)}, color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), style?: name} spray instances into a symbol set → {id, count}. Each of `attributes` says what a new instance takes: average, the mean of the selected set's instances within `radius` of the stroke point (their spacing along the stroke, size, rotation, opacity, and the stain or style of the nearest one that has one with an amount above 0, at the mean amount), and with none there the symbol's size, no rotation, full opacity and no stain or style; or userDefined: spacing from the symbol's size and `density`, the symbol's size times `scale`, turned the way the stroke runs there (not turned for one point), full opacity, stained in full with `color` (default: the fill color), and the fill of graphic style `style` (default: the first style after the default one) in full; a `style` the document does not have is then an error. The stain and the style are both the instance's fill, and the style replaces the stain. Another key or value in `attributes` is an error", has_doc, symbol_spray ), @@ -380,7 +380,7 @@ pub fn specs() -> Vec { "Symbolism Tool", [], None, - "{tool: shift|scrunch|size|spin|stain|screen|style, points: [[x,y,pressure?]…] (pen pressure 0..1, default 1), radius?: 40, intensity?: 1..10 (5), usePressure?: bool (each point's pressure is the intensity there, in place of `intensity`), method?: userDefined|average|random (userDefined; not used by shift), proportional?: bool (size; true), affectsDensity?: bool (size; false), alt?: bool, color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), style?: name} adjust instances near the points (selection, else all) → {count}. `method` userDefined changes each instance by the tool's amount at its distance from the point; random gives each instance its own share of that amount for the whole stroke, from none to twice it (spin: a turn either way); average moves each instance's value toward the mean of the instances within `radius` of the point (scrunch: its distance from their middle toward their mean distance; size: the geometric mean of their sizes; spin: their mean direction; stain and style: their mean amount; screen: their mean opacity), and `alt` does not reverse it; average leaves an instance without a size (a scale of 0) as it is. With `proportional` false a drag resizes along its own direction (a level drag the width, an upright one the height; the first point takes the direction to the second) and one point resizes both; average resizes both whatever `proportional` is. With `affectsDensity` an instance also moves away from the point as it grows and toward it as it shrinks. An instance counts only when it changes, and no undo step is added when none does (none under the brush, average with each already at the mean, or each already at the tool's limit). A `method` that is none of the three, or a pressure that isn't a number, is an error", + "{tool: shift|scrunch|size|spin|stain|screen|style, points: [[x,y,pressure?]…] (pen pressure 0..1, default 1), radius?: 40, intensity?: 1..10 (5), usePressure?: bool (each point's pressure is the intensity there, in place of `intensity`), method?: userDefined|average|random (userDefined; not used by shift), proportional?: bool (size; true), affectsDensity?: bool (size; false), alt?: bool, shift?: bool (shift, size, stain and style; false), color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), style?: name (a graphic style's; left out, or naming no style in the document, the first style after the default one)} adjust instances near the points (selection, else all) → {count}. `method` userDefined changes each instance by the tool's amount at its distance from the point; random gives each instance its own share of that amount for the whole stroke, from none to twice it (spin: a turn either way; style without `shift`: from none to the userDefined amount); average moves each instance's value toward the mean of the instances within `radius` of the point (scrunch: its distance from their middle toward their mean distance; size: the geometric mean of their sizes; spin: their mean direction; stain and style: their mean amount; screen: their mean opacity), and `alt` does not reverse it; average leaves an instance without a size as it is. With `proportional` false a drag resizes along its own direction, the width by the drag's horizontal share and the height by its vertical share (a level drag the width, an upright one the height, a 45° drag both alike; the first point takes the direction to the second) and one point resizes both; average resizes both whatever `proportional` is. With `affectsDensity` an instance also moves away from the point as it grows and toward it as it shrinks. The style goes on by the brush's strength at each sample, and a stroke's samples add up. With `alt` and without `shift`, userDefined and random style remove all of an instance's appearance items under the brush at once, whatever the brush's strength. `shift` is the tool's Shift form: shift brings the instances within `radius` of any point one place forward among their siblings (with `alt`, one place backward), once for the stroke, and does not move them; size keeps the instances where they are, `affectsDensity` included; stain and style keep each instance's amount and move its paint toward `color` or the style (stain by the tool's amount at its distance from the point, style by the brush's strength there), whatever `method` is, and leave an instance without a stain or style as it is, and `alt` has no effect. An instance counts only when it changes, and no undo step is added when none does (none under the brush, average with each already at the mean, each already at the tool's limit, or shift with nothing to move or change). A `method` that is none of the three, or a pressure that isn't a number, is an error", has_doc, symbol_adjust ), diff --git a/crates/engine/src/cmd/brushsym/symbolism.rs b/crates/engine/src/cmd/brushsym/symbolism.rs index 0199b7b13d..21fe71a644 100644 --- a/crates/engine/src/cmd/brushsym/symbolism.rs +++ b/crates/engine/src/cmd/brushsym/symbolism.rs @@ -86,8 +86,9 @@ pub(super) fn spacing(density: f64) -> f64 { } /// The document key that holds each symbol set's Symbol Set Density: `{set id: density}`, written -/// when the Symbol Sprayer creates a set and when `symbol.setDensity` spaces it. -const SET_DENSITY_KEY: &str = "symbolSetDensity"; +/// when the Symbol Sprayer creates a set and when `symbol.setDensity` spaces it, and copied to a +/// copy of a set by [`Document::reid`]. +const SET_DENSITY_KEY: &str = Document::SYMBOL_SET_DENSITY_KEY; /// The Symbol Set Density symbol set `set` was created at or last given (None when not recorded). fn set_density_of(d: &Document, set: NodeId) -> Option { @@ -261,7 +262,10 @@ pub(super) fn mean(looks: &[&Look], at: Point, with_gap: bool) -> Option { cos += l.angle.cos(); opacity += l.opacity; middle += l.center.to_vec2(); - if let Some((p, o)) = &l.fill { + // A fill at no opacity shows nothing: it is no stain or style, and its paint is not taken. + if let Some((p, o)) = &l.fill + && *o > 0.0 + { amount += o; let far = l.center.distance(at); if paint.is_none_or(|(_, nearest)| far < nearest) { diff --git a/crates/engine/src/cmd/brushsym/symbols.rs b/crates/engine/src/cmd/brushsym/symbols.rs index 6f1b96b52f..14e52ffe4f 100644 --- a/crates/engine/src/cmd/brushsym/symbols.rs +++ b/crates/engine/src/cmd/brushsym/symbols.rs @@ -118,6 +118,20 @@ fn instances_of(d: &Document, name: Option<&str>) -> Vec { v } +/// The symbol instances in `nodes` and inside them, each once, in the order a walk of each node in +/// turn first reaches them. +fn instances_in<'a>(nodes: impl IntoIterator) -> Vec { + let (mut v, mut seen) = (vec![], std::collections::HashSet::new()); + for n in nodes { + n.walk(&mut |c| { + if matches!(c.kind, NodeKind::SymbolInstance { .. }) && seen.insert(c.id) { + v.push(c.id); + } + }); + } + v +} + /// The symbols an instance in `n` (its opacity masks included) places, pushed onto `out`. fn art_symbols(n: &Node, out: &mut Vec) { vectorcraft_doc::swatches::walk_with_masks(n, &mut |m| { @@ -917,11 +931,12 @@ fn samples(p: &Value, cmd: &str) -> Result> { let a = p.get("points").and_then(Value::as_array).ok_or_else(|| bad(cmd, "missing points [[x,y]…]"))?; let mut v = Vec::with_capacity(a.len()); for q in a { - let (Some(x), Some(y)) = (q.get(0).and_then(Value::as_f64), q.get(1).and_then(Value::as_f64)) else { continue }; + // The pressure is checked first: a point skipped for its coordinates still has a bad one refused. let pressure = match q.get(2) { None | Some(Value::Null) => 1.0, Some(f) => f.as_f64().filter(|f| f.is_finite()).ok_or_else(|| bad(cmd, format!("a point's pressure must be a number, not {f}")))?, }; + let (Some(x), Some(y)) = (q.get(0).and_then(Value::as_f64), q.get(1).and_then(Value::as_f64)) else { continue }; v.push((Point::new(x, y), pressure.clamp(0.0, 1.0))); } if v.is_empty() || v.iter().any(|(q, _)| !q.x.is_finite() || !q.y.is_finite()) { @@ -930,13 +945,15 @@ fn samples(p: &Value, cmd: &str) -> Result> { Ok(v) } -/// The fill of the graphic style `p` names with `style`, else of the document's first style after -/// the default one. +/// The fill of the graphic style `p` names with `style`, else (no name, or one the document has no +/// style for, such as the Symbol Styler's style from another document) of the document's first +/// style after the default one. fn style_paint(d: &Document, p: &Value) -> Option { - match str_param(p, "style") { - Some(n) => d.graphic_styles.iter().find(|g| g.name == n).map(|g| g.appearance.fill_paint()), - None => d.graphic_styles.get(1).or(d.graphic_styles.first()).map(|g| g.appearance.fill_paint()), - } + str_param(p, "style") + .and_then(|n| d.graphic_styles.iter().find(|g| g.name == n)) + .or(d.graphic_styles.get(1)) + .or(d.graphic_styles.first()) + .map(|g| g.appearance.fill_paint()) } /// Deterministic per-point jitter in [-1, 1]² (so previews re-applied on the snapshot agree). @@ -976,7 +993,7 @@ pub(super) fn symbol_spray(s: &mut Session, p: &Value) -> Result { } let style = style_paint(&st.doc, p); // Style: User Defined uses the style `style` names, so one the document does not have is an error. - if let Some(n) = str_param(p, "style").filter(|_| !modes.style && style.is_none()) { + if let Some(n) = str_param(p, "style").filter(|n| !modes.style && !st.doc.graphic_styles.iter().any(|g| g.name == *n)) { return Err(bad(C, format!("unknown graphic style `{n}`"))); } let size = natural_size(&st.doc, &name); @@ -1129,6 +1146,7 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result { let use_pressure = switch_or(p, "usePressure", false, C)?; let proportional = switch_or(p, "proportional", true, C)?; let affects_density = switch_or(p, "affectsDensity", false, C)?; + let shift = switch_or(p, "shift", false, C)?; // The Symbol Shifter has no Method. let method = if tool == "shift" { method_param(p, C).map(|_| Method::UserDefined)? } else { method_param(p, C)? }; // Refused while an object of a dynamic instance's art is selected: the instance stays as it is. @@ -1141,20 +1159,8 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result { let style_paint = style_paint(&st.doc, p); let candidates: Vec = { let d = &st.doc; - let mut v = vec![]; - if st.selection.is_empty() { - v = instances_of(d, None); - } else { - for id in &st.selection.objects { - if let Some(n) = d.node(*id) { - n.walk(&mut |c| { - if matches!(c.kind, NodeKind::SymbolInstance { .. }) && !v.contains(&c.id) { - v.push(c.id); - } - }); - } - } - } + let mut v = + if st.selection.is_empty() { instances_of(d, None) } else { instances_in(st.selection.objects.iter().filter_map(|id| d.node(*id))) }; let editable = d.editable(); v.retain(|id| editable(*id)); v @@ -1172,12 +1178,39 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result { // for the whole stroke (and for every preview of it). let first = pts.first().map_or(Point::ZERO, |(q, _)| *q); let share = |id: NodeId| if method == Method::Random { jitter(id.0 as usize, first).0 + 1.0 } else { 1.0 }; + // Shift with the Symbol Shifter: the instances under the brush come one place forward among + // their siblings (with `alt`, go one place backward), once for the whole stroke. + if tool == "shift" && shift { + let count = crate::cmd::colorcmds::edit_if_changed(s, label, |_, d| { + let under: std::collections::HashSet = candidates + .iter() + .copied() + .filter(|id| { + d.node(*id).and_then(instance_center).is_some_and(|c| { + pts.iter().any(|(q, pressure)| (if use_pressure { *pressure } else { intensity }) > 0.0 && c.distance(*q) < radius) + }) + }) + .collect(); + let moved = restack(d, &under, alt)?; + Ok((moved, moved > 0)) + })?; + return Ok(json!({ "count": count })); + } + // Shift with the Symbol Stainer or the Symbol Styler: the paint an instance's stain or style + // moves toward, and the share of the brush's strength it moves by. Shift with the Symbol Sizer + // keeps the instances where they are, Resizing Affects Density included. + let recolor = match tool.as_str() { + "stain" if shift => Some((Paint::solid(color), 0.15)), + "style" if shift => Some((style_paint.clone().unwrap_or(Paint::solid(color)), 1.0)), + _ => None, + }; + let spread = affects_density && !shift; // No undo step when no instance changes (none under the brush, or Average with each at the mean). let count = crate::cmd::colorcmds::edit_if_changed(s, label, |orig, d| { let mut touched = std::collections::BTreeSet::new(); let mut sides = Sides::new(); for (j, (q, pressure)) in pts.iter().enumerate() { - let delta = if j > 0 { *q - pts[j - 1].0 } else { Vec2::ZERO }; + let delta = j.checked_sub(1).and_then(|i| pts.get(i)).map_or(Vec2::ZERO, |(prev, _)| *q - *prev); // Use Pressure Pen: the pen's pressure at the point is the intensity there. let strength = if use_pressure { *pressure } else { intensity }; // Average: the mean of the instances under the brush, as they are at this point. @@ -1198,6 +1231,14 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result { if w <= 0.0 { continue; } + // Shift with the Symbol Stainer or the Symbol Styler: the instance keeps the amount + // of its stain or style, and its paint moves toward the color or the style. An + // instance without one, or without a size, is left as it is. + if let Some((to, step)) = &recolor { + let fill = d.node(*id).and_then(|n| look(d, n, &mut sides)).and_then(|l| l.fill); + touched.extend(recolor_keeping_amount(d, *id, fill, to, step * w).then_some(*id)); + continue; + } // Average needs the instance's own values, so it leaves an instance without a size // as it is; the other methods change it as before. // The instance's own values are read for Average only. @@ -1261,8 +1302,9 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result { }; n.transform(about(Affine::scale_non_uniform(kx, ky)), false); // Resizing Affects Density: instances move away from the brush's center as - // they grow and toward it as they shrink. - if affects_density { + // they grow and toward it as they shrink. Shift keeps the instances where + // they are, so the set's density stays as it was. + if spread { n.transform(Affine::translate((c - *q) * ((kx * ky).sqrt() - 1.0)), false); } } @@ -1280,9 +1322,10 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result { "stain" | "style" => { let paint = if tool == "style" { style_paint.clone().unwrap_or(Paint::solid(color)) } else { Paint::solid(color) }; let (paint, o) = match &avg { - // Toward the mean amount, keeping the stain or style the instance has. + // Toward the mean amount, keeping the stain or style the instance has + // (one at no opacity is none). Some((t, look)) => { - let (own, cur) = look.fill.clone().map_or((None, 0.0), |(p, o)| (Some(p), o)); + let (own, cur) = look.fill.clone().filter(|(_, o)| *o > 0.0).map_or((None, 0.0), |(p, o)| (Some(p), o)); (own.or(t.paint.clone()).unwrap_or(paint), (cur + (t.amount - cur) * w.min(1.0)) as f32) } // Alt with the Symbol Styler removes the instance's appearance. @@ -1292,11 +1335,11 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result { } None => { let cur = n.appearance.fill().filter(|f| f.paint == paint).map(|f| f.opacity).unwrap_or(0.0); + // The style goes on gradually, by the brush's strength there: in + // full at the center at full intensity or pressure. let step = match (tool.as_str(), method) { - // Random: the instance's share of the style, scaled by the - // brush strength there. - ("style", Method::Random) => (share / 2.0 * w.min(1.0)) as f32, - ("style", _) => 1.0, + ("style", Method::Random) => (w * share / 2.0) as f32, + ("style", _) => w as f32, _ => (0.15 * w * share) as f32, }; (paint, if alt { cur - step } else { cur + step }) @@ -1324,9 +1367,108 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result { } } } - // An instance the stroke moved away and back again is not counted. + // An instance the stroke moved away and back again, or reached but left as it was (at a + // limit already), is not counted. touched.retain(|id| d.node(*id) != orig.node(*id)); Ok((touched.len(), !touched.is_empty())) })?; Ok(json!({ "count": count })) } + +/// Move the paint of instance `id`'s stain or style (`fill`, its topmost fill with the amount) +/// toward `to` by `t`. The fill keeps its amount and everything else it has, and the instance's +/// other appearance items stay as they are. A paint with no form between it and `to` (a solid +/// color and a pattern, say) takes `to` at once, so repeated strokes below half strength still +/// reach it. An instance without a stain or style, or one whose paint does not change, is left as +/// it is. Returns whether it changed. +fn recolor_keeping_amount(d: &mut Document, id: NodeId, fill: Option<(Paint, f64)>, to: &Paint, t: f64) -> bool { + use vectorcraft_doc::blend::lerp_paint; + let Some((own, _)) = fill.filter(|(_, o)| *o > 0.0) else { return false }; + let t = t.clamp(0.0, 1.0) as f32; + let mut paint = lerp_paint(&own, to, t); + // `lerp_paint` switches such a pair halfway, so just below half it still gives `own`. + if paint == own && t > 0.0 && lerp_paint(&own, to, 0.49) == own { + paint = to.clone(); + } + if paint == own { + return false; + } + let Some(f) = d.node_mut(id).and_then(|n| n.appearance.fill_mut()) else { return false }; + f.paint = paint; + true +} + +/// Bring each of `ids` one place forward among its siblings past a sibling that is not one of them +/// (`back`: one place backward). Ones already in front of (behind) every other sibling stay, and +/// so do the clipping path of a clip group and the ruler guides above a layer's art. Returns how +/// many moved. +fn restack(d: &mut Document, ids: &std::collections::HashSet, back: bool) -> Result { + let parents: std::collections::BTreeSet> = ids.iter().map(|id| d.parent_of(*id)).collect(); + let mut moved = 0; + for par in parents { + let floor = usize::from(par.and_then(|p| d.node(p)).is_some_and(Node::clips)); + let ch = d.children_mut(par)?; + let len = Node::guide_run_start(ch); + if len <= floor + 1 { + continue; + } + let picked = |n: &Arc| ids.contains(&n.id); + if back { + for i in floor + 1..len { + if picked(&ch[i]) && !picked(&ch[i - 1]) { + ch.swap(i - 1, i); + moved += 1; + } + } + } else { + for i in (floor..len - 1).rev() { + if picked(&ch[i]) && !picked(&ch[i + 1]) { + ch.swap(i, i + 1); + moved += 1; + } + } + } + } + Ok(moved) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn instance(id: u64) -> Arc { + Arc::new(Node::new(NodeId(id), NodeKind::SymbolInstance { symbol: "Dot".into(), xf: Affine::IDENTITY })) + } + + /// The instances come out in the order a search of the list built so far gives: nested + /// groups, a group listed twice, a member listed after its group and one listed before it. + #[test] + fn instances_in_matches_searching_the_list_so_far() { + let groups: Vec = (0..40u64) + .map(|g| { + let base = g * 100; + let mut children: Vec> = (0..40).map(|i| instance(base + i)).collect(); + let inner = (40..50).map(|i| instance(base + i)).collect(); + children.insert(20, Arc::new(Node::group(NodeId(base + 90), inner))); + children.push(Arc::new(Node::group(NodeId(base + 91), vec![]))); + Node::group(NodeId(base + 99), children) + }) + .collect(); + let early = Node::new(NodeId(1_245), NodeKind::SymbolInstance { symbol: "Dot".into(), xf: Affine::IDENTITY }); + let late = Node::new(NodeId(305), NodeKind::SymbolInstance { symbol: "Dot".into(), xf: Affine::IDENTITY }); + let nodes: Vec<&Node> = std::iter::once(&early).chain(&groups).chain([&groups[0], &late, &groups[7]]).collect(); + let mut searched = vec![]; + for n in &nodes { + n.walk(&mut |c| { + if matches!(c.kind, NodeKind::SymbolInstance { .. }) && !searched.contains(&c.id) { + searched.push(c.id); + } + }); + } + let found = instances_in(nodes.iter().copied()); + assert_eq!(found, searched); + assert_eq!(found.len(), 2_000); + assert_eq!(found[0], NodeId(1_245)); + assert!(instances_in([]).is_empty()); + } +} diff --git a/crates/engine/src/cmd/buildcmds.rs b/crates/engine/src/cmd/buildcmds.rs index 1e6739b6c7..f8de8f7b01 100644 --- a/crates/engine/src/cmd/buildcmds.rs +++ b/crates/engine/src/cmd/buildcmds.rs @@ -42,8 +42,12 @@ pub(crate) use live_paint::{LivePaintMove, check_part_name, clear_part_name, iso use live_paint::{lp_expand, lp_fill, lp_gap_options, lp_info, lp_make, lp_merge, lp_release, lp_stroke_edge}; use shape_builder::{sb_merge, sb_regions}; pub(crate) use trace::TracePresetChanges; -pub use trace::{TracePreset, TracePresetChange, TraceRun, Traced, image_trace_target}; -use trace::{trace_expand, trace_make, trace_presets_delete, trace_presets_save, trace_release, trace_set_view}; +pub use trace::{ + TRACE_PRESET_EXTS, TRACE_PRESET_FORMAT, TRACE_PRESET_MAX_BYTES, TracePreset, TracePresetChange, TraceRun, Traced, image_trace_target, +}; +use trace::{ + trace_expand, trace_make, trace_presets_delete, trace_presets_export, trace_presets_import, trace_presets_save, trace_release, trace_set_view, +}; /// Name of an Image Trace group. pub const TRACE_NAME: &str = "Image Trace"; @@ -208,6 +212,24 @@ pub fn specs() -> Vec { always, trace_presets_delete ), + cmd!( + query "imageTrace.presets.import", + "Import Image Trace Presets", + [], + None, + "{path? | data?: file text | dataBase64?, replace?: false (true: a preset whose name a saved preset has replaces that preset's settings; false: it is skipped)} add the presets of a .vctracepresets file (as imageTrace.presets.export writes, at most 4 MiB and 1,000 presets) to the saved ones → {imported: [names added], replaced: [names], skipped: [names]}; every preset is checked first, and a file with a built-in preset's or Custom's name, two presets of one name, a preset without a name or with settings imageTrace.presets.save refuses, or a newer version changes nothing", + always, + trace_presets_import + ), + cmd!( + query "imageTrace.presets.export", + "Export Image Trace Presets", + [], + None, + "{names?: [saved preset names] (default: every saved preset; built-in ones are refused), path?} write the saved tracing presets as a .vctracepresets file (JSON: format, version 1, presets: [{name, params}]) → {path, count}; without path → {data: the file's text, count}; more than 1,000 presets, or a file over 4 MiB, is refused, as imageTrace.presets.import would refuse it", + always, + trace_presets_export + ), ] } diff --git a/crates/engine/src/cmd/buildcmds/trace.rs b/crates/engine/src/cmd/buildcmds/trace.rs index f0f2557ded..c3e7a84296 100644 --- a/crates/engine/src/cmd/buildcmds/trace.rs +++ b/crates/engine/src/cmd/buildcmds/trace.rs @@ -58,9 +58,10 @@ fn view_param(cmd: &str, p: &Value) -> Result> { v.as_str().and_then(TraceView::from_id).map(Some).ok_or_else(|| bad(cmd, format!("view must be one of {}", ids()))) } -/// The `split` param (the Split view's divider, 0 to 1), if given. +/// The `split` param (the Split view's divider, 0 to 1), if given. A null divider is an error, as +/// any other value that is not such a number is; only an omitted one keeps the divider. fn split_param(cmd: &str, p: &Value) -> Result> { - let Some(v) = p.get("split").filter(|v| !v.is_null()) else { return Ok(None) }; + let Some(v) = p.get("split") else { return Ok(None) }; v.as_f64().filter(|f| (0.0..=1.0).contains(f)).map(Some).ok_or_else(|| bad(cmd, "split must be a number from 0 to 1")) } @@ -167,6 +168,9 @@ pub(super) fn trace_presets_save(s: &mut Session, p: &Value) -> Result { if old.is_none() && new_name.is_some() { return Err(bad(C, format!("no saved preset named `{name}` to rename"))); } + if old.is_none() && s.prefs.trace_presets.len() >= TRACE_PRESET_MAX_COUNT { + return Err(bad(C, format!("{TRACE_PRESET_MAX_COUNT} tracing presets are saved, the most there can be: delete one first"))); + } // A saved preset changes from its own settings unless `preset` says where to start. let mut q = p.clone(); if let (Some(old), Some(o), None) = (&old, q.as_object_mut(), preset) { @@ -202,6 +206,162 @@ pub(super) fn trace_presets_delete(s: &mut Session, p: &Value) -> Result Ok(json!({ "deleted": deleted })) } +/// The `format` of a tracing presets file, also its extension. +pub const TRACE_PRESET_FORMAT: &str = "vctracepresets"; + +/// The extensions of tracing presets files (opening one imports it). +pub const TRACE_PRESET_EXTS: &[&str] = &[TRACE_PRESET_FORMAT]; + +/// The `version` `imageTrace.presets.export` writes; `imageTrace.presets.import` reads files of +/// this version and earlier ones. +const TRACE_PRESET_VERSION: u64 = 1; + +/// The largest tracing presets file `imageTrace.presets.import` reads. +pub const TRACE_PRESET_MAX_BYTES: usize = 4 << 20; + +/// The most presets one tracing presets file may hold, and the most tracing presets that can be +/// saved (so every saved preset fits in one exported file). +const TRACE_PRESET_MAX_COUNT: usize = 1000; + +pub(super) fn trace_presets_export(s: &mut Session, p: &Value) -> Result { + const C: &str = "imageTrace.presets.export"; + let presets: Vec<&TracePreset> = match p.get("names").filter(|v| !v.is_null()) { + Some(Value::Array(names)) => { + let mut out: Vec<&TracePreset> = vec![]; + for n in names { + let n = n.as_str().ok_or_else(|| bad(C, "`names` must hold preset names"))?; + if tr::preset(n).is_some() { + return Err(bad(C, format!("`{n}` is a built-in preset: only saved presets are exported"))); + } + let q = s.trace_preset(n).ok_or_else(|| bad(C, format!("no saved preset named `{n}`")))?; + if !out.iter().any(|o| o.name == q.name) { + out.push(q); + } + } + out + } + Some(_) => return Err(bad(C, "`names` must be an array of preset names")), + None => s.prefs.trace_presets.iter().collect(), + }; + if presets.is_empty() { + return Err(bad(C, "no saved tracing presets to export")); + } + // A file is written only when `imageTrace.presets.import` can read it back. + let count = presets.len(); + if count > TRACE_PRESET_MAX_COUNT { + return Err(bad(C, format!("{count} presets are more than one file holds ({TRACE_PRESET_MAX_COUNT}): export fewer with `names`"))); + } + let rows: Vec = presets.iter().map(|q| json!({"name": q.name, "params": q.params})).collect(); + let file = json!({"format": TRACE_PRESET_FORMAT, "version": TRACE_PRESET_VERSION, "presets": rows}); + let text = serde_json::to_string_pretty(&file).map_err(|e| EngineError::Other(e.to_string()))?; + if text.len() > TRACE_PRESET_MAX_BYTES { + return Err(bad(C, format!("the file would be larger than {} MiB: export fewer with `names`", TRACE_PRESET_MAX_BYTES >> 20))); + } + match opt_str(C, p, "path")? { + Some(path) => { + crate::cmd::fileio::write_file(path, text.as_bytes())?; + Ok(json!({"path": path, "count": count})) + } + None => Ok(json!({"data": text, "count": count})), + } +} + +/// The bytes of the tracing presets file `p` names (`path`, `data` or `dataBase64`), at most +/// [`TRACE_PRESET_MAX_BYTES`] of them. +fn trace_preset_file(c: &str, p: &Value) -> Result> { + let too_big = || bad(c, format!("the file is larger than {} MiB", TRACE_PRESET_MAX_BYTES >> 20)); + let bytes = match (opt_str(c, p, "path")?, opt_str(c, p, "data")?, opt_str(c, p, "dataBase64")?) { + (Some(path), ..) => crate::cmd::fileio::read_file_head(path, TRACE_PRESET_MAX_BYTES + 1)?, + (None, Some(text), _) => { + if text.len() > TRACE_PRESET_MAX_BYTES { + return Err(too_big()); + } + text.as_bytes().to_vec() + } + (None, None, Some(b64)) => { + if vectorcraft_format::base64_decoded_len(b64) > TRACE_PRESET_MAX_BYTES as u64 { + return Err(too_big()); + } + vectorcraft_format::base64_decode(b64).ok_or_else(|| bad(c, "bad dataBase64"))? + } + _ => return Err(bad(c, "give `path`, `data` or `dataBase64`")), + }; + if bytes.len() > TRACE_PRESET_MAX_BYTES { + return Err(too_big()); + } + Ok(bytes) +} + +pub(super) fn trace_presets_import(s: &mut Session, p: &Value) -> Result { + const C: &str = "imageTrace.presets.import"; + let replace = switch_or(p, "replace", false, C)?; + let bytes = trace_preset_file(C, p)?; + let not_file = |why: String| bad(C, format!("not a tracing presets file: {why}")); + let file: Value = serde_json::from_slice(&bytes).map_err(|e| not_file(e.to_string()))?; + if file["format"] != TRACE_PRESET_FORMAT { + return Err(not_file(format!("format `{}`", file["format"].as_str().unwrap_or_default()))); + } + match file["version"].as_u64() { + Some(v) if (1..=TRACE_PRESET_VERSION).contains(&v) => {} + Some(v) => return Err(bad(C, format!("the file's version {v} is newer than this version of VectorCraft reads ({TRACE_PRESET_VERSION})"))), + None => return Err(not_file("no `version`".into())), + } + let rows = file["presets"].as_array().ok_or_else(|| not_file("no `presets` list".into()))?; + if rows.len() > TRACE_PRESET_MAX_COUNT { + return Err(bad(C, format!("the file holds {} presets, more than {TRACE_PRESET_MAX_COUNT}", rows.len()))); + } + // Every preset is checked before any is saved, so a file with a fault changes nothing. + let mut presets: Vec = Vec::with_capacity(rows.len()); + for (i, row) in rows.iter().enumerate() { + let name = row["name"].as_str().map(str::trim).unwrap_or_default(); + if name.is_empty() { + return Err(bad(C, format!("preset {} has no name", i + 1))); + } + if tr::preset(name).is_some() || name.eq_ignore_ascii_case("Custom") { + return Err(bad(C, format!("`{name}` is the name of a built-in preset: rename it in the file"))); + } + if presets.iter().any(|q| q.name.eq_ignore_ascii_case(name)) { + return Err(bad(C, format!("the file holds two presets named `{name}`"))); + } + let params = match row.get("params").filter(|v| v.is_object()) { + Some(params) => trace_params(s, C, &json!({"preset": "Default", "params": params})).map_err(|e| match e { + EngineError::BadParams { msg, .. } => bad(C, format!("`{name}`: {msg}")), + e => e, + })?, + None => return Err(bad(C, format!("`{name}` has no `params`"))), + }; + presets.push(TracePreset { name: name.to_string(), params }); + } + let added = presets.iter().filter(|q| s.trace_preset_index(&q.name).is_none()).count(); + if s.prefs.trace_presets.len() + added > TRACE_PRESET_MAX_COUNT { + return Err(bad( + C, + format!("the file's {added} new presets would make more than {TRACE_PRESET_MAX_COUNT} saved tracing presets: delete some first"), + )); + } + let (mut imported, mut replaced, mut skipped) = (vec![], vec![], vec![]); + for preset in presets { + let name = preset.name.clone(); + match s.trace_preset_index(&name) { + Some(i) if replace => { + let Some(slot) = s.prefs.trace_presets.get_mut(i) else { continue }; + // The saved preset keeps its name as it was saved. + let kept = slot.name.clone(); + *slot = TracePreset { name: kept.clone(), params: preset.params }; + s.trace_preset_changes.note(TracePresetChange { revision: 0, name: kept.clone(), renamed_from: None, deleted: false }); + replaced.push(kept); + } + Some(_) => skipped.push(name), + None => { + s.prefs.trace_presets.push(preset); + s.trace_preset_changes.note(TracePresetChange { revision: 0, name: name.clone(), renamed_from: None, deleted: false }); + imported.push(name); + } + } + } + Ok(json!({"imported": imported, "replaced": replaced, "skipped": skipped})) +} + /// The string `key` of `p` (`None` when it is missing or null); any other type is an error of /// command `c`. fn opt_str<'a>(c: &str, p: &'a Value, key: &str) -> Result> { @@ -649,7 +809,16 @@ fn prepare(s: &Session, c: &str, p: &Value) -> Result { None if is(tr::preset(named)) || is(tr::enhanced_preset(named)) => named.to_string(), None => "Custom".to_string(), }; + // The image (inside a trace group, or selected directly). let (target, image) = target_image(s, c, p)?; + // The traced shapes are placed by the image's transform, which a distortion overrides: the + // command stops before any pixels are read. + let distorted = s.doc()?.doc.node(target).is_some_and(|n| { + n.is_distorted_image() || (is_trace_group(n) && n.children().and_then(|c| c.first()).is_some_and(|i| i.is_distorted_image())) + }); + if distorted { + return Err(crate::cmd::xform::distorted_image_error(c, target)); + } if by_color && s.doc()?.doc.node(target).is_some_and(vectorcraft_render::effects::has_pathfinder) { return Err(bad(c, LIVE_PATHFINDER_BY_COLOR)); } diff --git a/crates/engine/src/cmd/clipboard.rs b/crates/engine/src/cmd/clipboard.rs index c42289ccc7..c6c1da2980 100644 --- a/crates/engine/src/cmd/clipboard.rs +++ b/crates/engine/src/cmd/clipboard.rs @@ -19,7 +19,7 @@ use std::sync::Arc; use serde_json::{Value, json}; use vectorcraft_brush::Brush; use vectorcraft_color::Swatch; -use vectorcraft_doc::{Document, GraphicStyle, ImageBlob, Node, NodeId, NodeKind, PatternDef, Selection, Symbol, TextStyleDef}; +use vectorcraft_doc::{Document, GraphDesign, GraphicStyle, ImageBlob, Node, NodeId, NodeKind, PatternDef, Selection, Symbol, TextStyleDef}; use vectorcraft_geom::{PathData, Rect}; pub use flavours::{AI, BITMAP, EMF, EPS, FILE_HEAD, Flavour, PASTE_ORDER, PDF, PNG, SVG, TEXT, file_flavour, is_address, names_a_picture}; @@ -94,6 +94,9 @@ pub struct Clipboard { pub para_styles: Vec, /// Brushes the objects' strokes use. pub brushes: Vec, + /// Graph designs the copied graphs draw their columns, bars or markers with. Pasting adds the + /// ones the document lacks; a design the document has under the same name stays as it is. + pub graph_designs: Vec, /// The artboard the objects were copied from (none when they lie on no artboard; the first of /// [`Self::artboards`] when there are any): Paste on All Artboards keeps their offset to it. pub source_artboard: Option, @@ -109,6 +112,9 @@ pub struct Clipboard { /// The selected ruler guides copied with (or without) the objects (#3226), as canvas guides on /// no layer: pasting puts them on the layer new art goes to, moved as the objects are. pub guides: Vec, + /// The Symbol Set Density recorded at Copy for each copied symbol set, by its id in + /// [`Self::nodes`]: a pasted set packs from it. + pub set_densities: BTreeMap, /// The RGB and CMYK profiles the objects' colors showed through in the document they were /// copied from (its assigned profiles, else the working spaces then), by name; none for objects /// from outside an open document. Paste compares them with the destination's @@ -392,7 +398,7 @@ impl Clipboard { if self.source_doc == Some(st.uid) && !self.colors_converted { return vec![]; } - self.conflicts(&st.doc, &self.used()) + self.conflicts(&st.doc, &self.used(&st.doc)) } /// A standalone document holding the objects and their resources (SVG export). @@ -405,6 +411,7 @@ impl Clipboard { d.graphic_styles.extend(self.graphic_styles.iter().cloned()); d.char_styles = self.char_styles.clone().into(); d.para_styles = self.para_styles.clone().into(); + d.graph_designs = self.graph_designs.clone(); if !self.brushes.is_empty() { let mut lib = vectorcraft_brush::library(&d); // Each brush's place in the library by name: finding it by scanning the growing list @@ -466,6 +473,7 @@ impl Clipboard { char_styles: d.char_styles.to_vec(), para_styles: d.para_styles.to_vec(), brushes: vectorcraft_brush::library(&d), + graph_designs: d.graph_designs.clone(), images: self.images.clone(), symbol_options: self.symbol_options.clone(), source_artboard: self.source_artboard, @@ -484,6 +492,7 @@ impl Clipboard { }) .collect(), guides: self.guides.clone(), + set_densities: self.set_densities.clone(), source_profiles: self.source_profiles.clone(), colors_converted: self.colors_converted, } diff --git a/crates/engine/src/cmd/clipboard/resources.rs b/crates/engine/src/cmd/clipboard/resources.rs index 583341f2a4..c20c763495 100644 --- a/crates/engine/src/cmd/clipboard/resources.rs +++ b/crates/engine/src/cmd/clipboard/resources.rs @@ -1,8 +1,9 @@ //! The document resources copied objects use, and adding them to the document they're pasted into. //! //! Objects refer to resources by name (image blobs, symbols, patterns, swatches, character and -//! paragraph styles, brushes) and to graphic styles by id. Copy follows those references, also -//! through the symbols, patterns, styles and brush art it finds, and keeps what they lead to. +//! paragraph styles, brushes, graph designs) and to graphic styles by id. Copy follows those +//! references, also through the symbols, patterns, styles, brush art and graph design art it finds, +//! and keeps what they lead to. //! //! Pasting matches each resource by name: an identical one in the document is used, a missing one //! is added, and a different one of the same name is added under a free name, which the pasted @@ -22,8 +23,8 @@ use vectorcraft_brush::Brush; use vectorcraft_color::{Color, Paint, Swatch}; use vectorcraft_doc::text::{KINSOKU_NAME_MAX, KINSOKU_SETS_MAX}; use vectorcraft_doc::{ - Appearance, AppearanceItem, Document, Effect, GraphicStyle, Kinsoku, KinsokuSet, Node, NodeKind, PatternDef, Symbol, SymbolExportType, - SymbolNineSlice, SymbolRegistration, TextStyleDef, + Appearance, AppearanceItem, Document, Effect, GraphDesign, GraphicStyle, Kinsoku, KinsokuSet, Node, NodeKind, PatternDef, Symbol, + SymbolExportType, SymbolNineSlice, SymbolRegistration, TextStyleDef, }; use super::super::brushsym::{set_natural_size, stored_natural_size}; @@ -44,6 +45,7 @@ enum Res { ParaStyle, Brush, GraphicStyle, + GraphDesign, } impl Res { @@ -57,6 +59,7 @@ impl Res { Res::ParaStyle => "paraStyle", Res::Brush => "brush", Res::GraphicStyle => "graphicStyle", + Res::GraphDesign => "graphDesign", } } } @@ -139,6 +142,10 @@ fn node_refs(n: &Node, f: Visit) { for s in [&l.values_para, &l.categories_para, &l.legend_para].into_iter().flatten().filter_map(|pa| pa.style_name.as_ref()) { f(Ref::Name(Res::ParaStyle, s)); } + // The designs its series draw their markers, columns or bars with. + for d in g.series_markers.iter().flatten().chain(g.series_columns.iter().flatten().map(|c| &c.design)) { + f(Ref::Name(Res::GraphDesign, d)); + } } match &m.kind { NodeKind::Text(t) => { @@ -217,6 +224,7 @@ struct Defs<'a> { char_styles: &'a [TextStyleDef], para_styles: &'a [TextStyleDef], brushes: Brushes<'a>, + graph_designs: &'a [GraphDesign], /// Where each name is defined, built the first time a kind is followed. index: DefIndex, } @@ -236,6 +244,7 @@ struct DefIndex { char_styles: OnceCell, para_styles: OnceCell, brushes: OnceCell, + graph_designs: OnceCell, } /// The items of `list` named `name`, in order, `index` holding their positions (built from @@ -279,6 +288,7 @@ impl<'a> Defs<'a> { char_styles: &d.char_styles, para_styles: &d.para_styles, brushes: Brushes::Lazy(d, brushes), + graph_designs: &d.graph_designs, index: DefIndex::default(), } } @@ -376,6 +386,7 @@ impl Used { Res::ParaStyle => todo.extend(named(&ix.para_styles, defs.para_styles, |s| &s.name, name).map(|s| Source::Attrs(&s.attrs))), // A scatter or art brush's art, a pattern brush's tiles. Res::Brush => todo.extend(named(&ix.brushes, defs.brushes.get(), |b| &b.name, name).flat_map(|b| b.art().into_iter().map(Source::Node))), + Res::GraphDesign => todo.extend(named(&ix.graph_designs, defs.graph_designs, |g| &g.name, name).map(|g| Source::Node(&g.art))), _ => {} } } @@ -406,7 +417,7 @@ pub struct ArtResources { /// The resources `art` uses in `doc`, through the definitions they lead to as Copy follows them /// ([`Used`]): images, symbols, patterns (tile type, overlap and spacing too), swatches (linked /// colours, tints, gradient swatches; colour groups' included), character and paragraph styles, -/// brushes and graphic styles, and the document's Spot Colors option. Art and image bytes count +/// brushes, graph designs and graphic styles, and the document's Spot Colors option. Art and image bytes count /// by identity, the other definitions by their saved form: working the key out walks `art` and /// the definitions it leads to, and never reads an image's bytes. pub fn art_resources<'a>(doc: &'a Document, art: impl IntoIterator) -> ArtResources { @@ -451,6 +462,7 @@ pub fn art_resources<'a>(doc: &'a Document, art: impl IntoIterator doc.char_styles.iter().filter(|s| s.name == *name).for_each(|s| saved(&mut h, s)), Res::ParaStyle => doc.para_styles.iter().filter(|s| s.name == *name).for_each(|s| saved(&mut h, s)), Res::Brush => defs.brushes.get().iter().filter(|b| b.name == *name).for_each(|b| saved(&mut h, b)), + Res::GraphDesign => doc.graph_designs.iter().filter(|g| g.name == *name).for_each(|g| node(&mut h, &mut kept.0, &g.art)), // Swatches below (tints count too); graphic styles go by id. Res::Swatch | Res::GraphicStyle => {} } @@ -824,6 +836,22 @@ fn same_art(r: &Relink, ours: &[Arc], theirs: &[Arc]) -> bool { ours.len() == theirs.len() && ours.iter().zip(theirs).all(|(a, b)| relinked(&unlinked, a) == relinked(r, b)) } +/// `n` with the ids of its objects, those of opacity-mask art included, all 0: art drawn again +/// compares equal to art drawn the same way, whatever ids each drawing gave it. +fn without_ids(n: &Node) -> Node { + let mut n = n.clone(); + n.id = vectorcraft_doc::NodeId(0); + if let Some(mask) = n.extras_if_any().and_then(|e| e.mask.as_deref_mut()) { + mask.art = Arc::new(without_ids(&mask.art)); + } + if let Some(children) = n.children_mut() { + for c in children.iter_mut() { + *c = Arc::new(without_ids(c)); + } + } + n +} + /// Is `ours` (a document brush) brush `theirs` (a pasted one) once the art of that is relinked by /// `r`? Graphic style links don't count, as in [`same_art`]. fn same_brush(r: &Relink, ours: &Brush, theirs: &Brush) -> bool { @@ -1106,6 +1134,17 @@ pub(crate) struct Imported { /// `{kind, from, to}` for every resource the pasted objects now know under another name: added /// renamed, or a copy added renamed by an earlier paste. pub renamed: Vec, + /// The graph designs the pasted graphs draw with that the document has under the same name + /// and that would draw them otherwise than the art they were pasted with: the document keeps + /// its own, and the pasted graphs are drawn again with it. + pub kept_designs: BTreeSet, + /// The names of the symbols added to the document, whose art may hold graphs that draw with + /// [`Self::kept_designs`]. + pub added_symbols: BTreeSet, + /// The names of the graph designs added to the document. + pub added_designs: BTreeSet, + /// The global and spot colors that took the document's color (merged). + merged_swatches: BTreeSet, } impl Imported { @@ -1161,14 +1200,24 @@ impl Clipboard { char_styles: pick(Res::CharStyle, &src.char_styles), para_styles: pick(Res::ParaStyle, &src.para_styles), brushes, + graph_designs: src.graph_designs.iter().filter(|g| used.has(Res::GraphDesign, &g.name)).cloned().collect(), + set_densities: src.set_densities_of(&nodes), nodes, ..Default::default() } } - /// The resources the objects use now (Paste without Formatting leaves text styles behind). - pub(super) fn used(&self) -> Used { - let defs = Defs { + /// The resources the objects use now (Paste without Formatting leaves text styles behind), + /// pasted into `d`: the art of a graph design `d` has under the same name is not followed, as + /// `d` keeps its own design. + pub(super) fn used(&self, d: &Document) -> Used { + let designs: Vec = self.graph_designs.iter().filter(|g| !d.graph_designs.iter().any(|x| x.name == g.name)).cloned().collect(); + Used::of(&self.defs(&designs), &self.nodes) + } + + /// The clipboard's definitions, with graph designs `designs`. + fn defs<'a>(&'a self, designs: &'a [GraphDesign]) -> Defs<'a> { + Defs { swatches: self.swatches.iter().collect(), symbols: &self.symbols, patterns: &self.patterns, @@ -1176,9 +1225,9 @@ impl Clipboard { char_styles: &self.char_styles, para_styles: &self.para_styles, brushes: Brushes::Ready(&self.brushes), + graph_designs: designs, index: DefIndex::default(), - }; - Used::of(&defs, &self.nodes) + } } /// The used global and spot colours whose name `d` gives another one: (pasted, document). @@ -1199,7 +1248,8 @@ impl Clipboard { /// paste ([`Self::colors_converted`]), its color-bearing resources are compared as another /// document's are, while its image blobs are still the document's own under their keys. pub(crate) fn import_into(&self, d: &mut Document, choices: &SwatchChoices, same_doc: bool) -> Result { - self.import_used_with_images(d, &self.used(), choices, same_doc && !self.colors_converted, same_doc) + let used = self.used(d); + self.import_used_with_images(d, &used, choices, same_doc && !self.colors_converted, same_doc) } /// Give the objects' colors linked to a global or spot swatch whose conflict with `d` @@ -1210,7 +1260,7 @@ impl Clipboard { if same_doc { return; } - let used = self.used(); + let used = self.used(d); let colors: BTreeMap = self .conflicts(d, &used) .into_iter() @@ -1247,6 +1297,11 @@ impl Clipboard { ) -> Result { let mut out = Imported::default(); out.relink.filters = self.filter_links(d, same_doc)?; + let held = |name: &str| d.graph_designs.iter().any(|x| x.name == name); + let new_designs = self.graph_designs.iter().filter(|g| used.has(Res::GraphDesign, &g.name) && !held(&g.name)).count(); + if new_designs > 0 && d.graph_designs.len().saturating_add(new_designs) > GraphDesign::MAX { + return Err(EngineError::Other(format!("a document keeps at most {} graph designs", GraphDesign::MAX))); + } self.import_images(d, used, same_doc_images, &mut out); self.import_swatches(d, used, choices, same_doc, &mut out); self.import_kinsoku_sets(d, used, same_doc, &mut out); @@ -1330,11 +1385,18 @@ impl Clipboard { .collect(), None => HashMap::new(), }; + // A symbol whose graphs the paste draws again with the document's designs is + // also the document's one that holds its art drawn that way (an earlier paste + // added it). + let redrawn = (!fresh && d.symbols.iter().any(|s| copy_of(&def.name, &s.name))) + .then(|| self.redrawn_art(d, &def.art, &out.relink)) + .flatten(); let r = &out.relink; let p = place(&mut d.symbols, def, same_doc, |a, b| { !fresh && options.is_none_or(|o| theirs.get(&a.name) == Some(o)) - && same_art(r, std::slice::from_ref(&a.art), std::slice::from_ref(&b.art)) + && (same_art(r, std::slice::from_ref(&a.art), std::slice::from_ref(&b.art)) + || redrawn.as_ref().is_some_and(|art| without_ids(&a.art) == *art)) }); if let Some(name) = p.new_name(&def.name) { if let Some(o) = options { @@ -1370,6 +1432,7 @@ impl Clipboard { } } self.import_graphic_styles(d, used, same_doc, &mut out); + self.import_graph_designs(d, used, same_doc, &mut out)?; for (r, name, def) in added_styles { let theirs = if r == Res::CharStyle { &mut d.char_styles } else { &mut d.para_styles }; if let Some(s) = theirs.iter_mut().find(|s| s.name == name) { @@ -1380,6 +1443,7 @@ impl Clipboard { for s in d.symbols.iter_mut().filter(|s| added_symbols.contains(&s.name)) { out.relink.node(Arc::make_mut(&mut s.art)); } + out.added_symbols = added_symbols.into_iter().collect(); for p in d.patterns.iter_mut().filter(|p| added_patterns.contains(&p.name)) { for a in &mut p.art { out.relink.node(Arc::make_mut(a)); @@ -1496,6 +1560,10 @@ impl Clipboard { for a in self.brushes.iter().flat_map(Brush::art) { node_filters(a, &mut found); } + // A design the document has under the same name stays its own, so its art here is not pasted. + for g in self.graph_designs.iter().filter(|g| !d.graph_designs.iter().any(|x| x.name == g.name)) { + node_filters(&g.art, &mut found); + } for g in &self.graphic_styles { appearance_filters(&g.appearance, &mut found); } @@ -1574,6 +1642,7 @@ impl Clipboard { for w in &bases { let p = if conflicts.contains(&w.name) && choices.of(&w.name) == SwatchChoice::Merge { out.merged += 1; + out.merged_swatches.insert(w.name.clone()); Placed::Existing } else { add_swatch(d, w, same_doc) @@ -1623,6 +1692,71 @@ impl Clipboard { out.relink.styles.insert(g.id, d.graphic_style_id(i)); } } + + /// Symbol art `art` relinked by `relink` with its graphs drawn again with the designs `d` holds + /// under a name whose design the clipboard lacks or holds with other art, as a paste that adds + /// the symbol draws it, its ids left out ([`without_ids`]). `None` when no graph of it draws + /// with such a design. + fn redrawn_art(&self, d: &mut Document, art: &Arc, relink: &Relink) -> Option { + let theirs = |n: &str| self.graph_designs.iter().find(|g| g.name == n); + let differs: BTreeSet = d + .graph_designs + .iter() + .filter(|x| theirs(&x.name).is_none_or(|g| !Arc::ptr_eq(&g.art, &x.art) && g.art != x.art)) + .map(|x| x.name.clone()) + .collect(); + if differs.is_empty() || !crate::cmd::graph::holds_designs(art, &differs) { + return None; + } + let mut n = (**art).clone(); + relink.node(&mut n); + crate::cmd::graph::redraw_detached(d, &mut n, &differs); + Some(without_ids(&n)) + } + + /// Graph designs: the document's design of a name stays as it is and the pasted graphs draw + /// with it ([`Imported::kept_designs`]); a design the document lacks is added under its name, its art following the + /// resources placed above, with fresh ids. Called once every other resource is placed. + fn import_graph_designs(&self, d: &mut Document, used: &Used, same_doc: bool, out: &mut Imported) -> Result<()> { + // Every name the pasted graphs draw with whose design in the document would draw them + // otherwise: another design of that name, one the clipboard holds no design for (deleted + // and made again), or, from another document, the same art when a resource came in renamed + // or a swatch took the document's color, that the design's art uses. (An SVG filter effect + // carries its definition, so a filter that draws otherwise makes the art differ.) + let defs = self.defs(&self.graph_designs); + let moved = |n: &str| { + if same_doc || (out.relink.renames.is_empty() && out.merged_swatches.is_empty()) { + return false; + } + let uses = designs_used(&defs, &[n.to_string()]); + out.relink.renames.iter().any(|(r, names)| names.keys().any(|from| uses.has(*r, from))) + || out.merged_swatches.iter().any(|w| uses.has(Res::Swatch, w)) + }; + let differs = |n: &str| { + let ours = d.graph_designs.iter().find(|x| x.name == n); + let theirs = self.graph_designs.iter().find(|g| g.name == n); + ours.is_some_and(|x| theirs.is_none_or(|g| !Arc::ptr_eq(&g.art, &x.art) && g.art != x.art) || moved(n)) + }; + let named = used.names.get(&Res::GraphDesign).into_iter().flatten(); + let kept: Vec = named.filter(|n| differs(n)).cloned().collect(); + out.kept_designs.extend(kept); + for g in self.graph_designs.iter().filter(|g| used.has(Res::GraphDesign, &g.name)) { + if d.graph_designs.iter().any(|x| x.name == g.name) { + out.placed(Res::GraphDesign, &g.name, &Placed::Existing); + continue; + } + if d.graph_designs.len() >= GraphDesign::MAX { + return Err(EngineError::Other(format!("a document keeps at most {} graph designs", GraphDesign::MAX))); + } + let mut art = (*g.art).clone(); + out.relink.node(&mut art); + let art = d.reid(&art); + d.graph_designs.push(GraphDesign { name: g.name.clone(), art: Arc::new(art) }); + out.placed(Res::GraphDesign, &g.name, &Placed::Added); + out.added_designs.insert(g.name.clone()); + } + Ok(()) + } } /// Where a loaded text style is in the document ([`import_text_styles`]). @@ -1662,6 +1796,72 @@ pub(crate) fn import_text_styles(src: &Document, d: &mut Document, chars: bool, Ok(placed) } +/// The resources graph designs `names` of `src` use, through the definitions they lead to. +fn designs_used(defs: &Defs<'_>, names: &[String]) -> Used { + let mut used = Used::default(); + let mut todo = vec![]; + for n in names { + used.note(defs, Ref::Name(Res::GraphDesign, n), &mut todo); + } + used.follow(defs, todo); + used +} + +/// A document holding `src`'s graph designs and the swatches, patterns, symbols, styles, brushes +/// and images their art uses, and nothing else: what a document opened as a library keeps for the +/// Graph Column and Graph Marker dialogs. `None` when `src` has no graph designs. +pub(crate) fn graph_design_library(src: &Document) -> Option { + if src.graph_designs.is_empty() { + return None; + } + let names: Vec = src.graph_designs.iter().map(|g| g.name.clone()).collect(); + let library = OnceCell::new(); + let used = designs_used(&Defs::of(src, &library), &names); + let clip = Clipboard::with_used(src, &used, &library, vec![]); + let mut d = clip.to_document(); + // A new document's default swatches and graphic styles give way to the source's of the same + // name or id, so a design draws with the source's. + let defaults = d.swatches.len().saturating_sub(clip.swatches.len()); + let mut i = 0; + d.swatches.retain(|s| { + i += 1; + i > defaults || !clip.swatches.iter().any(|c| c.name == s.name) + }); + // The swatch groups are all a new document's. + for g in d.swatch_groups.iter_mut() { + g.swatches.retain(|s| !clip.swatches.iter().any(|c| c.name == s.name)); + } + let defaults = d.graphic_styles.len().saturating_sub(clip.graphic_styles.len()); + let mut i = 0; + d.graphic_styles.retain(|g| { + i += 1; + i > defaults || !clip.graphic_styles.iter().any(|c| (c.id != 0 && c.id == g.id) || c.name == g.name) + }); + // The symbols keep their Symbol Options, which the document keeps by name. + for (name, options) in &clip.symbol_options { + options.give(&mut d, name); + } + d.title = src.title.clone(); + Some(d) +} + +/// Add graph designs `names` of `src` to `d`, with the swatches, patterns, symbols, styles, +/// brushes and images their art uses, placed as Paste places them ([`Clipboard::import_into`]; a +/// global or spot color whose name `d` gives another color is `d`'s). A design `d` has under the +/// same name stays as it is, and the art of `src`'s design of that name is not followed. → the +/// names of the designs added ([`Imported::added_designs`]): those of `names` `d` lacked, and those +/// their art uses; with the symbols added and the designs `d` kept that their art draws with +/// ([`Imported::added_symbols`], [`Imported::kept_designs`]). An error, with `d` unchanged, when `d` +/// would hold more than [`GraphDesign::MAX`] designs. +pub(crate) fn import_graph_designs(src: &Document, d: &mut Document, names: &[String]) -> Result { + let library = OnceCell::new(); + let held = |n: &str| d.graph_designs.iter().any(|x| x.name == n); + let followed: Vec = src.graph_designs.iter().filter(|g| names.contains(&g.name) || !held(&g.name)).cloned().collect(); + let used = designs_used(&Defs { graph_designs: &followed, ..Defs::of(src, &library) }, names); + let clip = Clipboard::with_used(src, &used, &library, vec![]); + clip.import_used(d, &used, &SwatchChoices::default(), false) +} + /// Swatch `w` in `d` ([`existing`]), else added under a free name (swatches and colour groups /// share one namespace). fn add_swatch(d: &mut Document, w: &Swatch, same_doc: bool) -> Placed { diff --git a/crates/engine/src/cmd/colormgmt.rs b/crates/engine/src/cmd/colormgmt.rs index 2f169dc3b1..1b394fa95c 100644 --- a/crates/engine/src/cmd/colormgmt.rs +++ b/crates/engine/src/cmd/colormgmt.rs @@ -84,7 +84,7 @@ pub fn specs() -> Vec { "Convert Color", [], None, - "{color (#rrggbbaa and #rgba are refused), to: \"rgb\"|\"cmyk\"|\"gray\"|\"lab\", intent?} → {model, values, hex, lab: [L,a,b], outOfGamut, deltaE}", + "{color (#rrggbbaa and #rgba are refused), to: \"rgb\"|\"cmyk\"|\"gray\"|\"lab\"|\"oklch\", intent?} → {model, values, hex, lab: [L,a,b], outOfGamut, deltaE}; oklch values are [L (0..100 %), C, H (0..360°)] of the color's display sRGB (CSS Color 4 OKLCH: https://www.w3.org/TR/css-color-4/#specifying-oklab-oklch), with H 0 for a gray; a color outside sRGB (a Lab color, a CMYK color or an RGB color in a wider working RGB space) is clipped to sRGB first", always, convert_color ), @@ -1362,10 +1362,15 @@ fn convert_color(_: &mut Session, p: &Value) -> Result { let intent = intent_param(p, C)?.unwrap_or(c.settings().intent); let lab = c.lab(&col); let (model, vals) = match text_param(p, "to", C)?.unwrap_or("rgb") { - "rgb" => ("rgb", values(&c.convert(&col, Model::Rgb, intent))), - "cmyk" => ("cmyk", values(&c.convert(&col, Model::Cmyk, intent))), - "gray" | "grayscale" => ("gray", values(&c.convert(&col, Model::Gray, intent))), - "lab" => ("lab", vec![lab.l, lab.a, lab.b]), + "rgb" => ("rgb", json!(values(&c.convert(&col, Model::Rgb, intent)))), + "cmyk" => ("cmyk", json!(values(&c.convert(&col, Model::Cmyk, intent)))), + "gray" | "grayscale" => ("gray", json!(values(&c.convert(&col, Model::Gray, intent)))), + "lab" => ("lab", json!([lab.l, lab.a, lab.b])), + "oklch" => { + // RGB numbers past 0..1 ([2, 2, 2]) display clipped, as `hex` reports them. + let [l, ch, h] = vectorcraft_color::oklab::to_oklch(c.display_rgb(&col).map(|v| v.clamp(0.0, 1.0))); + ("oklch", json!([l * 100.0, ch, h])) + } other => return Err(bad(C, format!("unknown model `{other}`"))), }; let de = c.gamut_error(&col); diff --git a/crates/engine/src/cmd/create.rs b/crates/engine/src/cmd/create.rs index f012bcfc82..0ce38be40b 100644 --- a/crates/engine/src/cmd/create.rs +++ b/crates/engine/src/cmd/create.rs @@ -73,7 +73,7 @@ pub fn specs() -> Vec { "Circle Through Points", [], None, - "{points?: [[x, y], [x, y]] or [[x, y], [x, y], [x, y]] (two: the ends of a diameter; left out: the two or three selected anchor points, where a path selected whole counts all its anchors and selected segments' ends do not count)} → {id, cx, cy, radius}: a circle with the current paint whose edge passes through the points, not pixel-aligned even while Align New Objects to Pixel Grid is on; two points that are the same, three on one line, or a circle reaching past the canvas are an error, and nothing is drawn", + "{points?: [[x, y], [x, y]] or [[x, y], [x, y], [x, y]] (two: the ends of a diameter; left out: the two or three selected anchor points, where a path selected whole counts all its anchors and selected segments' ends do not count), anchors?: \"standard\"|\"points\" (default standard: four anchors at 0°, 90°, 180° and 270°; points: an anchor at each point and more between them so that no curve turns more than a quarter)} → {id, cx, cy, radius}: a circle with the current paint whose edge passes through the points, not pixel-aligned even while Align New Objects to Pixel Grid is on; two points that are the same, three on one line, or a circle reaching past the canvas are an error, and nothing is drawn", has_doc, circle_through_points ), @@ -443,20 +443,32 @@ fn ellipse(s: &mut Session, p: &Value) -> Result { } /// A live ellipse whose edge passes through two or three points: `points`, or the two or three -/// selected anchor points ([`selected_anchor_points`]). Two points are the ends of a diameter. One -/// undo step, named as an Ellipse tool drag is. +/// selected anchor points ([`selected_anchor_points`]). Two points are the ends of a diameter. With +/// `anchors: "points"` the circle is a plain path with an anchor at each point +/// ([`shapes::circle_with_anchors_at`]); otherwise it is a live ellipse. One undo step, named as an +/// Ellipse tool drag is. fn circle_through_points(s: &mut Session, p: &Value) -> Result { const C: &str = "shape.circleThroughPoints"; let points = match p.get("points").filter(|v| !v.is_null()) { Some(v) => two_or_three_points(v).ok_or_else(|| bad(C, "`points` must be two or three [x, y] pairs of numbers"))?, None => selected_anchor_points(s)?.ok_or_else(|| bad(C, "direct-select two or three anchor points, or give `points`"))?, }; + let key = "anchors"; + let at_points = match p.get(key).map(Value::as_str) { + None | Some(Some("standard")) => false, + Some(Some("points")) => true, + Some(_) => return Err(bad(C, format!("`{key}` must be one of {}", "standard, points"))), + }; let (center, radius) = shapes::circle_through_points(&points) .ok_or_else(|| bad(C, "no circle passes through these points: two are the same or all three lie on one line"))?; - let r = Rect::new(center.x - radius, center.y - radius, center.x + radius, center.y + radius); - let live = LiveShape::Ellipse { w: r.width(), h: r.height(), pie: (0.0, 360.0), xf: Affine::translate(r.origin().to_vec2()) }; // Not pixel-aligned: the circle stays through the points. - let mut out = add_art_unaligned(s, "Ellipse", path_kind(live.to_path(), Some(live)))?; + let mut out = if at_points { + add_art_unaligned(s, "Ellipse", path_kind(shapes::circle_with_anchors_at(center, radius, &points), None))? + } else { + let r = Rect::new(center.x - radius, center.y - radius, center.x + radius, center.y + radius); + let live = LiveShape::Ellipse { w: r.width(), h: r.height(), pie: (0.0, 360.0), xf: Affine::translate(r.origin().to_vec2()) }; + add_art_unaligned(s, "Ellipse", path_kind(live.to_path(), Some(live)))? + }; out["cx"] = json!(center.x); out["cy"] = json!(center.y); out["radius"] = json!(radius); diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 5e0231228b..ccebbfac88 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -1568,6 +1568,8 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho for xf in placements { for (k, n) in clip.nodes.iter().enumerate() { let mut c = d.reid(n); + // A pasted symbol set packs from the density recorded for it at Copy. + d.carry_set_densities(n, &c, &clip.set_densities); imported.apply(&mut c); let sc = vectorcraft_doc::Scaling { patterns: mode == PasteMode::Drag, ..Default::default() }; if xf != Affine::IDENTITY { @@ -1651,6 +1653,17 @@ fn paste_clip(s: &mut Session, p: &Value, mode: PasteMode, clip: &Clipboard, cho for id in &new_ids { super::object::keep_compound_aligned(d, *id, vectorcraft_doc::Scaling::default()); } + // A pasted graph whose design the document has under the same name draws with the document's, + // in the pasted objects and in the art of the symbols the paste added. + if !imported.kept_designs.is_empty() { + super::graph::redraw_with_designs(d, &new_ids, &imported.kept_designs)?; + super::graph::redraw_symbols_with_designs(d, &imported.added_symbols, &imported.kept_designs); + } + // The graphs already in the document that draw with a design the paste added are drawn + // again with it; the pasted ones already draw with it. + if !imported.added_designs.is_empty() { + super::graph::refresh_graphs(d, &imported.added_designs, &new_ids, &imported.added_symbols)?; + } sel.set(new_ids.iter().copied()); // Copied ruler guides (#3226): on the layer new art goes to, moved as the objects are (a // paste of guides alone keeps them where they were, but onto another artboard or every diff --git a/crates/engine/src/cmd/effectcmd.rs b/crates/engine/src/cmd/effectcmd.rs index 5ea3efd950..edb5561796 100644 --- a/crates/engine/src/cmd/effectcmd.rs +++ b/crates/engine/src/cmd/effectcmd.rs @@ -52,7 +52,7 @@ fn effect_specs() -> Vec { "Apply Effect", [], None, - "{effect: id (see effect.list, e.g. \"stylize.dropShadow\", \"distort.roughen\", \"warp.arc\", or \"plugin.\" for an installed effect plug-in), params?: {…} (missing keys take the dialog defaults), item?: appearance item index|null (apply to that fill/stroke only; omitted: the Appearance panel's active item, else the whole object), ids?|id?: [..] (layers too), target?: \"object\"|\"contents\" (contents: the objects inside groups and layers), aligned?: bool (item is a row of the first target's stack: each other target gets the effect on its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, a row of the art's stack: docs/mcp.md)} append a live effect to each selected object's appearance (a group's or layer's apply to its members as one piece: one combined shadow; a Pathfinder effect, which combines a group's contents, groups several loose selected objects first, in the same undo step); the art of a graph design in a graph series is left out, and objects that are all such art are an error (docs/mcp.md) → {ids, index, item, grouped?}", + "{effect: id (see effect.list, e.g. \"stylize.dropShadow\", \"distort.roughen\", \"warp.arc\", or \"plugin.\" for an installed effect plug-in), params?: {…} (missing keys take the dialog defaults), item?: appearance item index|null (apply to that fill/stroke only; omitted: the Appearance panel's active item, else the whole object), ids?|id?: [..] (layers too), target?: \"object\"|\"contents\" (contents: the objects inside groups and layers), aligned?: bool (item is a row of the first target's stack: each other target gets the effect on its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, a row of the art's stack: docs/mcp.md), savedBevel?: [[x, y]…] (with params bevel {custom: name}: the custom bevel's points, used in place of the bevels file's; the journal records them so a replay draws the same bevel after the file changes)} append a live effect to each selected object's appearance (a group's or layer's apply to its members as one piece: one combined shadow; a Pathfinder effect, which combines a group's contents, groups several loose selected objects first, in the same undo step); the art of a graph design in a graph series is left out, and objects that are all such art are an error (docs/mcp.md) → {ids, index, item, grouped?}", has_doc, apply ), @@ -79,7 +79,7 @@ fn effect_specs() -> Vec { "Effect Options", [], None, - "{index: int, params?: {…} (merged into the current parameters), warpStyle?: string (an existing Warp style suffix, e.g. arc or flag; changes only an applied Warp in place; params are checked against the new style), threeDType?: plane|extrude|revolve|inflate (the 3D and Materials panel's object type: changes only an applied 3D effect in place into Rotate, Extrude & Bevel, Revolve or Inflate; the settings the new effect also takes keep their values, rotation angles wrapped into -180..180 outside Revolve, and the others start at its defaults; params then merge into the new effect's; the type the effect already has, with nothing else given, changes nothing and records no undo step), visible?: bool (any other value but null is refused, when a step plays too), item?: appearance item index|null (as effect.remove), ids?|id?: [..], target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md)} → {ids}", + "{index: int, params?: {…} (merged into the current parameters), warpStyle?: string (an existing Warp style suffix, e.g. arc or flag; changes only an applied Warp in place; params are checked against the new style), threeDType?: plane|extrude|revolve|inflate (the 3D and Materials panel's object type: changes only an applied 3D effect in place into Rotate, Extrude & Bevel, Revolve or Inflate; the settings the new effect also takes keep their values, rotation angles wrapped into -180..180 outside Revolve, and the others start at its defaults; params then merge into the new effect's; the type the effect already has, with nothing else given, changes nothing and records no undo step), visible?: bool (any other value but null is refused, when a step plays too), item?: appearance item index|null (as effect.remove), ids?|id?: [..], target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md), savedBevel?: [[x, y]…] (as effect.apply)} → {ids}", has_doc, set_params ), @@ -442,6 +442,17 @@ fn check_revolve_count(n: &Node, cmd: &str) -> Result<()> { pub(crate) const ONE_3D: &str = "An object takes one 3D effect. Edit the existing effect's options, or remove it first."; +/// The Pathfinder Options that `effect.apply` gives a Pathfinder effect for the keys its `params` +/// leave out: the preferences' Pathfinder Options in force. +pub fn pathfinder_effect_options(s: &Session) -> effects::PathfinderEffectOptions { + let current = super::pathops::current_pf_options(s); + effects::PathfinderEffectOptions { + precision: current.precision, + remove_redundant_points: current.remove_redundant_points, + remove_unpainted: current.remove_unpainted, + } +} + /// `effect.apply`: adds effect `effect` (or `id`) with `params`, its defaults filled in, to the /// targets' active item as one undo step. A 3D effect must fit each target, which takes only one; /// a Pathfinder effect on loose objects groups them first. → `{ids, index, item}`. @@ -465,13 +476,30 @@ pub(crate) fn apply(s: &mut Session, p: &Value) -> Result { super::params::check_effect_color(C, id, ¶ms)?; super::params::check_effect_channel(C, id, ¶ms)?; super::params::check_effect_center(C, id, ¶ms)?; + super::params::check_effect_pathfinder(C, id, ¶ms)?; // Crop Marks take their style from the preferences when applied. if id == effects::CROP_MARKS && params.get("style").is_none() { params["style"] = json!(s.crop_mark_style().id()); } + // A Pathfinder effect keeps the Pathfinder Options in force when it is applied, those `params` + // give aside. They join the journal entry, so replaying it gives the same effect. + if effects::takes_pathfinder_options(id) { + if let Value::Object(filled) = pathfinder_effect_options(s).to_params() { + for (key, v) in filled { + if params.get(&key).is_none() { + params[key.as_str()] = v; + } + } + } + s.note_journal("params", params.clone()); + } if texture_load_effect(id) { load_texture(&mut params, C)?; } + // A custom bevel by name takes a copy of its points from the bevels file. + if bevel_effect(id) { + super::bevels::resolve_custom(s, p, &mut params, C)?; + } // An SVG filter needs its element, and is named by its id. if id == effects::SVG_FILTER { let xml = params.get("xml").and_then(Value::as_str).ok_or_else(|| bad(C, "give `xml`, one SVG element"))?; @@ -789,10 +817,14 @@ pub(crate) fn set_params(s: &mut Session, p: &Value) -> Result { super::params::check_effect_color(C, effect, ¶ms)?; super::params::check_effect_channel(C, effect, ¶ms)?; super::params::check_effect_center(C, effect, ¶ms)?; + super::params::check_effect_pathfinder(C, effect, ¶ms)?; } if edited.iter().any(|e| texture_load_effect(e)) { load_texture(&mut params, C)?; } + if edited.iter().any(|e| bevel_effect(e)) || kind == Some(effects::EXTRUDE) { + super::bevels::resolve_custom(s, p, &mut params, C)?; + } let targets = effect_targets(s, p, item, index, C)?; // The type each 3D effect already has, with nothing else to change, is no edit (and is not // checked again). @@ -808,6 +840,15 @@ pub(crate) fn set_params(s: &mut Session, p: &Value) -> Result { return Ok(json!({ "ids": [] })); } } + // Pathfinder effects given the values they already evaluate with, and nothing else to change, + // are no edit and record no undo step. + if kind.is_none() && warp_id.is_none() && visible.is_none() { + let d = &s.doc()?.doc; + let fx: Vec<&Effect> = targets.iter().filter_map(|&(id, at, index)| d.node(id)?.appearance.effects_at(at)?.get(index)).collect(); + if !fx.is_empty() && fx.iter().all(|e| pathfinder_edit_changes_nothing(e, ¶ms)) { + return Ok(json!({ "ids": [] })); + } + } // An SVG filter is named by its id: another filter renames the effect. if edited.iter().any(|e| e == effects::SVG_FILTER) && let Some(xml) = params.get("xml").and_then(Value::as_str) @@ -876,6 +917,36 @@ pub(crate) fn set_params(s: &mut Session, p: &Value) -> Result { Ok(json!({ "ids": ids_json(&ids) })) } +/// Does effect `id` take a `bevel` (Extrude & Bevel, Extrude & Bevel (Classic)), which may be a +/// custom bevel given by name? +fn bevel_effect(id: &str) -> bool { + id == effects::EXTRUDE || id == effects::CLASSIC_EXTRUDE +} + +/// Does merging `params` into Pathfinder effect `e` leave it drawing as it does: the same Pathfinder +/// Options ([`effects::PathfinderEffectOptions`], so an effect saved without them and given their +/// defaults is unchanged), each option given equal to the one it stores (a precision that Scale +/// Strokes & Effects took past its range evaluates at the bound but is still edited), and every +/// other value given equal to the one it has? +fn pathfinder_edit_changes_nothing(e: &Effect, params: &Value) -> bool { + if !effects::takes_pathfinder_options(&e.id) { + return false; + } + let Some(given) = params.as_object().filter(|m| !m.is_empty()) else { return true }; + let current = effects::merged_params(&e.id, &e.params); + let mut after = current.clone(); + if let Value::Object(m) = &mut after { + m.extend(given.clone()); + } + let others_same = given.iter().filter(|(k, _)| !effects::PATHFINDER_OPTION_KEYS.contains(&k.as_str())).all(|(k, v)| current.get(k) == Some(v)); + let same_value = |a: &Value, b: &Value| a == b || a.as_f64().is_some_and(|x| b.as_f64() == Some(x)); + let stored_same = given + .iter() + .filter(|(k, _)| effects::PATHFINDER_OPTION_KEYS.contains(&k.as_str())) + .all(|(k, v)| e.params.get(k).is_none_or(|stored| same_value(stored, v))); + others_same && stored_same && effects::PathfinderEffectOptions::from_params(¤t) == effects::PathfinderEffectOptions::from_params(&after) +} + // ---------- Load Texture ---------- /// Effect › Distort › Glass. diff --git a/crates/engine/src/cmd/fileio/save.rs b/crates/engine/src/cmd/fileio/save.rs index 7150d68dbb..f03dc6fe0d 100644 --- a/crates/engine/src/cmd/fileio/save.rs +++ b/crates/engine/src/cmd/fileio/save.rs @@ -1193,7 +1193,8 @@ impl SaveJob { } // The other open documents that place this one show the new version. let written = self.plan.path.clone().filter(|_| matches!(self.plan.format.id, "vectorcraft" | "template")); - // A save of the arrowheads file lists its heads in the arrowhead menus. + // A save of the arrowheads file lists its heads in the arrowhead menus, and one of the + // bevels file its bevels in the Bevel Shape menus. let native = self.plan.format.id == "vectorcraft"; if let Some(st) = s.document_mut(uid) { self.finish(st); @@ -1204,6 +1205,7 @@ impl SaveJob { if let Some(path) = written { if native { s.arrowheads_saved(&path); + s.bevels_saved(&path); } crate::cmd::links::refresh_placed(s, uid, &path); } diff --git a/crates/engine/src/cmd/flatten/compose.rs b/crates/engine/src/cmd/flatten/compose.rs index fef23f86ae..ee245f16d2 100644 --- a/crates/engine/src/cmd/flatten/compose.rs +++ b/crates/engine/src/cmd/flatten/compose.rs @@ -141,7 +141,11 @@ impl Builder { if fills.is_empty() { Body::Complex } else { Body::Fills { shape: self.shape(path, rule, Kind::Vector)?, fills } } } NodeKind::Image(im) => { - let frame = shapes::rectangle(Rect::new(0.0, 0.0, im.width as f64, im.height as f64)).transformed(im.xf); + // A distorted image's frame joins its corners. + let frame = match n.image_frame().filter(|_| n.is_distorted_image()) { + Some(bp) => PathData::from_bezpath(&bp), + None => shapes::rectangle(Rect::new(0.0, 0.0, im.width as f64, im.height as f64)).transformed(im.xf), + }; self.shape(frame, FillRule::NonZero, Kind::Other)?; Body::Complex } diff --git a/crates/engine/src/cmd/gradient.rs b/crates/engine/src/cmd/gradient.rs index f5270c9780..8cf1091492 100644 --- a/crates/engine/src/cmd/gradient.rs +++ b/crates/engine/src/cmd/gradient.rs @@ -63,7 +63,7 @@ fn select_stop(s: &mut Session, p: &Value) -> Result { // No document is needed for the default paint's gradient, so this does not use `refuse_symbol_part`. // While the Live Paint Bucket is active the proxies show the default paint, whose stops can be // selected with a part picked. - if s.tool_id() != super::paint::LIVE_PAINT_BUCKET && s.active().is_some_and(|st| st.selection.symbol_part.is_some()) { + if !s.bucket_paints() && s.active().is_some_and(|st| st.selection.symbol_part.is_some()) { return Err(super::brushsym::part_only()); } let index = match p.get("index") { @@ -111,7 +111,7 @@ impl StopOwner { part: st.is_some_and(|d| d.selection.symbol_part.is_some()), fill: s.fill_active, item: s.appearance_item(), - bucket: s.tool_id() == super::paint::LIVE_PAINT_BUCKET, + bucket: s.bucket_paints(), } } } @@ -804,7 +804,7 @@ fn set_gradient_geom(s: &mut Session, p: &Value) -> Result { let skipped = super::paint::live_paint_parts_skipped(&s.doc()?.doc, &roots, !stroke); leaf_targets(s, &roots)?.into_iter().filter(|id| !skipped.contains(id)).collect() } - _ => item.targets(s, p)?, + _ => item.targets_for(s, p, !stroke)?, }; if targets.is_empty() { return Err(EngineError::Other("nothing selected".into())); diff --git a/crates/engine/src/cmd/graph.rs b/crates/engine/src/cmd/graph.rs index f1db9dd58a..06fb062e50 100644 --- a/crates/engine/src/cmd/graph.rs +++ b/crates/engine/src/cmd/graph.rs @@ -41,6 +41,7 @@ pub use data::{MAX_GRAPH_DATA_FILE, graph_cell_text, graph_data_from_grid, graph pub(crate) use data::{apply_csv, graph_csv_from_file, parse_csv}; #[cfg(test)] use data::{fmt_value, to_csv}; +pub(crate) use designs::{holds_designs, redraw_detached, redraw_symbols_with_designs, redraw_with_designs, refresh_graphs}; pub use edit::{GraphTypeSubject, graph_type_subject}; pub(crate) use edit::{edit_graph_art, graphs_holding, keep_placed}; pub use generate::calculated_axes; diff --git a/crates/engine/src/cmd/graph/columns.rs b/crates/engine/src/cmd/graph/columns.rs index 34addd90bd..6c87143618 100644 --- a/crates/engine/src/cmd/graph/columns.rs +++ b/crates/engine/src/cmd/graph/columns.rs @@ -1,5 +1,5 @@ use super::data::fmt_value; -use super::designs::design_names; +use super::designs::{bring_in_for, design_names, from_library, libraries_json}; use super::edit::{regenerate, spec_of, target}; use super::generate::generate_with; use super::markers::{design_frame, fit_affine}; @@ -437,7 +437,7 @@ pub(super) fn set_column(s: &mut Session, p: &Value) -> Result { let mut spec = spec_of(s, id)?; let count = spec.rows.iter().map(Vec::len).max().unwrap_or(0).min(vectorcraft_doc::MAX_GRAPH_SERIES); let picked = picked_series(s, p, id, count, C)?; - let names = design_names(&s.doc()?.doc); + let mut names = design_names(&s.doc()?.doc); let all: Vec = if picked.is_empty() { (0..count).collect() } else { picked.clone() }; // The column design the picked series (all of them with none picked) share; a design deleted since doesn't count, // as those series draw plain columns. @@ -446,14 +446,21 @@ pub(super) fn set_column(s: &mut Session, p: &Value) -> Result { let shared = used.first().copied().flatten().filter(|c| used.iter().all(|x| *x == Some(*c))).cloned(); let Some(v) = p.get("design") else { let options = shared.clone().unwrap_or_default(); - return Ok(json!({ + let mut out = json!({ "designs": names, "design": shared.map(|c| c.design), "columnType": options.column_type.id(), "each": options.each, "fractions": options.fractions.id(), - })); + }); + if let Some(libs) = libraries_json(s) { + out["libraries"] = libs; + } + return Ok(out); }; + // A design of a loaded library comes into the document in the same undo step. + let library = from_library(s, p, C)?; + names.extend(library.as_ref().map(|(_, n)| n.clone())); let design = match v { Value::Null => None, Value::String(n) if names.contains(n) => Some(n.clone()), @@ -485,11 +492,17 @@ pub(super) fn set_column(s: &mut Session, p: &Value) -> Result { } // Drawn once on a copy of the document, to refuse designs past the budget before the edit. let mut probe = (*s.doc()?.doc).clone(); + if let Some((lib, name)) = &library { + bring_in_for(&mut probe, lib, name, id, &mut spec)?; + } let looks = column_designs(&probe, &spec); if generate_with(&mut probe, &spec, &looks).is_none() { return Err(bad(C, "the design is too big to draw in every column of this graph")); } s.edit("Graph Column", |d, sel| { + if let Some((lib, name)) = &library { + bring_in_for(d, lib, name, id, &mut spec)?; + } regenerate(d, id, spec)?; if !reselect.is_empty() { reselect_series(d, sel, id, &reselect); diff --git a/crates/engine/src/cmd/graph/commands.rs b/crates/engine/src/cmd/graph/commands.rs index 27da7936a8..1bea2161e2 100644 --- a/crates/engine/src/cmd/graph/commands.rs +++ b/crates/engine/src/cmd/graph/commands.rs @@ -39,7 +39,7 @@ pub fn specs() -> Vec { "Design…", ["Object", "Graph"], None, - "{new?: name|true (New Design: the selected art becomes a graph design, named \"New Design\" when true; put a rectangle at the back to set the size it draws at), rename?: name, to?: new name (the graphs drawing it follow), paste?: name (Paste Design: a copy of the design's art into the document, selected, to edit and save again), delete?: name|[names] (graphs drawing them go back to their default marks), ids?|id?: object ids (default: the selection), selectUnused?: bool (Select Unused: just the list)}; no params or selectUnused → {designs: [names], unused: [the names no graph draws with]}", + "{new?: name|true (New Design: the selected art becomes a graph design, named \"New Design\" when true; put a rectangle at the back to set the size it draws at), rename?: name, to?: new name (the graphs drawing it follow), paste?: name (Paste Design: a copy of the design's art into the document, selected, to edit and save again), delete?: name|[names] (graphs drawing them go back to their default marks), ids?|id?: object ids (default: the selection), selectUnused?: bool (Select Unused: just the list), library?: the id or name of a document loaded with swatch.library.load (Other Library…) that holds graph designs, add?: name|[names] of that library's designs (copy them into the document as one undo step, with the swatches, patterns, symbols, styles, brushes and images their art uses, as pasting brings them; a design the document already has under the same name stays as it is) → {added: [names], existing: [names the document already had]}}; library alone → {designs: [the library's names]}; no params or selectUnused → {designs: [names], unused: [the names no graph draws with], libraries?: [{library, name, designs}] (the loaded libraries that hold graph designs)}", has_doc, design ), @@ -48,7 +48,7 @@ pub fn specs() -> Vec { "Column…", ["Object", "Graph"], None, - "{id?, seriesIndexes?: [index], design?: name|null, columnType?: vertical|uniform|repeating|sliding, each?: value (more than 0), fractions?: chop|scale} draw the columns or bars and the legend swatch of the series selected with Group Selection (or listed, or every series) with a graph design, its backmost object as its frame and its guides left out: vertical stretches it along the value axis to each column's length at the column's width, uniform scales it both ways to that length, centered on the column, repeating stacks copies out from the zero line that each stand for `each` and cuts off the last one where the value ends (chop) or scales it down to fit (scale) (vertical when one copy would be longer than the canvas), and sliding scales the part above its horizontal guide line (in bar graphs, right of a vertical one) in proportion to the column's width and stretches the part below to fill the rest (vertical without a guide, or in a column too short for the part above); type in the design that holds a `%` followed by two digits shows each column's value in place of the `%` and the digits, the first digit giving the least number of places before the decimal point (zeros added in front; 0 = as many as the value needs) and the second digit giving the places after it (rounded half away from zero), at the type's own size where the design's copy puts it (a repeating design shows it once, where a whole copy ending at the value end puts it; type inside a group that clips, is hidden or has its own opacity, blend mode, isolation, knockout, appearance or opacity mask, or inside a blend, compound shape, envelope, repeat or intertwine, stays there and is filled in each copy, drawn with the design; type inside a symbol stays as typed), and is left out of the legend swatch (a design of such type alone gets the default swatch); the design keeps its own orientation for negative values, and columns drawn with a design cast no drop shadow; null = plain columns; options left out keep the series' shared ones, else vertical, 10 and chop. Column, stacked column, bar and stacked bar series. No design → {designs: [names], design: the selected series' design or null, columnType, each, fractions}", + "{id?, seriesIndexes?: [index], design?: name|null, library?: id or name (a document loaded with swatch.library.load: a design of it that the document lacks is copied in first, in the same undo step, as graph.design's add copies it; the document's own design of a name is the one used), columnType?: vertical|uniform|repeating|sliding, each?: value (more than 0), fractions?: chop|scale} draw the columns or bars and the legend swatch of the series selected with Group Selection (or listed, or every series) with a graph design, its backmost object as its frame and its guides left out: vertical stretches it along the value axis to each column's length at the column's width, uniform scales it both ways to that length, centered on the column, repeating stacks copies out from the zero line that each stand for `each` and cuts off the last one where the value ends (chop) or scales it down to fit (scale) (vertical when one copy would be longer than the canvas), and sliding scales the part above its horizontal guide line (in bar graphs, right of a vertical one) in proportion to the column's width and stretches the part below to fill the rest (vertical without a guide, or in a column too short for the part above); type in the design that holds a `%` followed by two digits shows each column's value in place of the `%` and the digits, the first digit giving the least number of places before the decimal point (zeros added in front; 0 = as many as the value needs) and the second digit giving the places after it (rounded half away from zero), at the type's own size where the design's copy puts it (a repeating design shows it once, where a whole copy ending at the value end puts it; type inside a group that clips, is hidden or has its own opacity, blend mode, isolation, knockout, appearance or opacity mask, or inside a blend, compound shape, envelope, repeat or intertwine, stays there and is filled in each copy, drawn with the design; type inside a symbol stays as typed), and is left out of the legend swatch (a design of such type alone gets the default swatch); the design keeps its own orientation for negative values, and columns drawn with a design cast no drop shadow; null = plain columns; options left out keep the series' shared ones, else vertical, 10 and chop. Column, stacked column, bar and stacked bar series. No design → {designs: [names], design: the selected series' design or null, columnType, each, fractions, libraries?: [{library, name, designs}]}", has_selection, set_column ), @@ -57,7 +57,7 @@ pub fn specs() -> Vec { "Marker…", ["Object", "Graph"], None, - "{id?, seriesIndexes?: [index], design?: name|null} draw the data points and legend swatch of the series selected with Group Selection (or listed, or every series) with a graph design, scaled so its backmost object fills the default marker's square; null = the default marker. Line, scatter and radar series. No design → {designs: [names], design: the selected series' design or null}", + "{id?, seriesIndexes?: [index], design?: name|null, library?: id or name (a document loaded with swatch.library.load: a design of it that the document lacks is copied in first, in the same undo step, as graph.design's add copies it; the document's own design of a name is the one used)} draw the data points and legend swatch of the series selected with Group Selection (or listed, or every series) with a graph design, scaled so its backmost object fills the default marker's square; null = the default marker. Line, scatter and radar series. No design → {designs: [names], design: the selected series' design or null, libraries?: [{library, name, designs}]}", has_selection, set_marker ), diff --git a/crates/engine/src/cmd/graph/designs.rs b/crates/engine/src/cmd/graph/designs.rs index 6ab79bac77..f0d42808ab 100644 --- a/crates/engine/src/cmd/graph/designs.rs +++ b/crates/engine/src/cmd/graph/designs.rs @@ -1,44 +1,291 @@ -use super::edit::regenerate; -use super::{Arc, Document, GraphDesign, GraphSpec, Result, Session, Value, bad, json, ok, str_param}; +use super::edit::{regenerate, regenerate_detached}; +use std::collections::BTreeSet; + +use super::{Arc, Document, GraphDesign, GraphKind, GraphSpec, Node, Result, Session, Value, bad, json, ok, str_param}; +use crate::cmd::clipboard::resources::import_graph_designs; +use crate::cmd::swatchlib::{concealed_library_id, shown_library_id}; /// The document's graph design names, in order. pub(super) fn design_names(d: &Document) -> Vec { d.graph_designs.iter().map(|x| x.name.clone()).collect() } -/// Whether graph `g` draws a series with design `name`, as its marker or its columns. +/// The library param `library` names: a document Other Library… loaded (`swatch.library.load`) +/// that holds graph designs, by its id, the id a reply showed for it, or its name (in any case, as +/// swatch library names are matched). `None` without +/// `library`. +fn library_param(s: &Session, p: &Value, cmd: &str) -> Result>> { + let key = match p.get("library") { + None | Some(Value::Null) => return Ok(None), + Some(Value::String(k)) => k.as_str(), + Some(_) => { + let list = "graph.design"; + return Err(bad(cmd, format!("`library` is a library id or name (see {list})"))); + } + }; + let libs = &s.graph_design_libraries; + let own = concealed_library_id(s, key); + libs.get(key) + .or_else(|| own.as_deref().and_then(|id| libs.get(id))) + .or_else(|| libs.iter().find(|l| l.name.eq_ignore_ascii_case(key))) + .map(|l| Some(l.doc.clone())) + .ok_or_else(|| bad(cmd, format!("no library `{key}`"))) +} + +/// The loaded libraries' designs, as lists show them: `[{library, name, designs}]`; `None` when no +/// loaded library holds graph designs. +pub(super) fn libraries_json(s: &Session) -> Option { + let libs: Vec = s + .graph_design_libraries + .iter() + .map(|l| json!({ "library": shown_library_id(s, &l.id), "name": l.name, "designs": design_names(&l.doc) })) + .collect(); + (!libs.is_empty()).then(|| json!(libs)) +} + +/// The library design `p`'s `design` names, with the library to bring it in from, when `p` gives a +/// `library` and the document has no design of that name: the document's own design of a name is +/// the one a graph draws with. +pub(super) fn from_library(s: &Session, p: &Value, cmd: &str) -> Result, String)>> { + let Some(lib) = library_param(s, p, cmd)? else { return Ok(None) }; + let Some(Value::String(n)) = p.get("design") else { return Ok(None) }; + if s.doc()?.doc.graph_designs.iter().any(|x| x.name == *n) { + return Ok(None); + } + if !lib.graph_designs.iter().any(|x| x.name == *n) { + return Err(bad(cmd, format!("no design named `{n}`"))); + } + Ok(Some((lib, n.clone()))) +} + +/// Add designs `names` of library `lib` to `d` with the resources their art uses, and redraw the +/// graphs that already name a design the document lacked: one of `names`, or one their art uses. +/// The graphs in the art of the symbols that came in are drawn with the designs the document kept. +pub(super) fn bring_in(d: &mut Document, lib: &Document, names: &[String]) -> Result<()> { + let imported = import_graph_designs(lib, d, names)?; + if !imported.kept_designs.is_empty() { + redraw_symbols_with_designs(d, &imported.added_symbols, &imported.kept_designs); + } + if !imported.added_designs.is_empty() { + refresh_graphs(d, &imported.added_designs, &[], &BTreeSet::new())?; + } + Ok(()) +} + +/// [`bring_in`] library design `name` for graph `id`, whose new spec is `spec`: when that redraws +/// the graph, `spec` takes the rectangle the redraw gave it, so a graph moved or resized since it +/// was last drawn stays where it is. +pub(super) fn bring_in_for(d: &mut Document, lib: &Document, name: &str, id: super::NodeId, spec: &mut GraphSpec) -> Result<()> { + bring_in(d, lib, &[name.to_string()])?; + if let Some(g) = d.node(id).and_then(|n| n.extras().graph.as_deref()) { + spec.rect = g.rect; + } + Ok(()) +} + +/// Whether graph `g` draws a series with design `name`: as the marker of a series drawn with +/// markers (every series of a scatter or radar graph, and line series) while Mark Data Points is +/// on or the legend has an entry for the series, or as the columns of a series drawn as columns or +/// bars. fn draws_with(g: &GraphSpec, name: &str) -> bool { + let scatter = g.kind == GraphKind::Scatter; + let nser = g.rows.iter().map(Vec::len).max().unwrap_or(0).clamp(1, vectorcraft_doc::MAX_GRAPH_SERIES); + // The legend draws entry `s` with marker design `s`, and leaves out an entry whose label is blank + // (a scatter graph's entries are its pairs of series, labeled by the first of each pair). + let in_legend = |s: usize| { + let entries = if scatter { nser.div_ceil(2) } else { nser }; + let label = g.series.get(if scatter { s * 2 } else { s }).map_or("", String::as_str); + g.legend && !g.series.is_empty() && s < entries && !super::labels::blank_label(label) + }; + // Point markers use the same range of designs: a scatter graph plots a pair of series for each. + let plotted = if scatter { nser.div_ceil(2) } else { nser }; + let shown = |s: usize| s < plotted && (g.mark_points || in_legend(s)); + let marked = |s: usize| shown(s) && (matches!(g.kind, GraphKind::Scatter | GraphKind::Radar) || g.series_kind(s) == GraphKind::Line); + let columnar = |s: usize| matches!(g.series_kind(s), GraphKind::Column | GraphKind::StackedColumn | GraphKind::Bar | GraphKind::StackedBar); + g.series_markers.iter().enumerate().any(|(s, m)| m.as_deref() == Some(name) && marked(s)) + || g.series_columns.iter().enumerate().any(|(s, c)| c.as_ref().is_some_and(|c| c.design == name) && columnar(s)) +} + +/// Whether graph `g` names design `name` for a series, as its marker or its columns, whether or +/// not the series draws with it. +fn names_design(g: &GraphSpec, name: &str) -> bool { g.series_markers.iter().flatten().any(|m| m == name) || g.series_columns.iter().flatten().any(|c| c.design == name) } -/// Regenerate the graphs whose series use design `name` (it was added or removed). +/// Regenerate the graphs whose series use design `name` (it was added or removed), in the layers, +/// in opacity-mask art and in symbols' art. fn refresh_graphs_using(d: &mut Document, name: &str) -> Result<()> { - let mut ids = vec![]; + refresh_graphs(d, &BTreeSet::from([name.to_string()]), &[], &BTreeSet::new()) +} + +/// Regenerate the graphs that draw a series with one of the designs `names`, in the layers, in +/// opacity-mask art and in symbols' art, except those in the subtrees of `skip` and in the art of +/// symbols `skip_symbols`. +pub(crate) fn refresh_graphs(d: &mut Document, names: &BTreeSet, skip: &[super::NodeId], skip_symbols: &BTreeSet) -> Result<()> { + let mut skipped = std::collections::HashSet::new(); + for n in skip.iter().filter_map(|id| d.node(*id)) { + n.walk(&mut |m| { + skipped.insert(m.id); + }); + } + let (mut ids, mut masked) = (vec![], vec![]); d.walk(|n| { - if n.extras().graph.as_deref().is_some_and(|g| draws_with(g, name)) { + if skipped.contains(&n.id) { + return; + } + if n.extras().graph.as_deref().is_some_and(|g| names.iter().any(|name| draws_with(g, name))) { ids.push(n.id); } + if n.extras().mask.as_deref().is_some_and(|m| holds(&m.art, names)) { + masked.push(n.id); + } }); for id in ids { if let Some(spec) = d.node(id).and_then(|n| n.extras().graph.as_deref().cloned()) { regenerate(d, id, spec)?; } } + // The graphs in objects' opacity-mask art. + for id in masked { + let Some(mut art) = d.node(id).and_then(|n| n.extras().mask.as_deref()).map(|m| (*m.art).clone()) else { continue }; + redraw_in(d, &mut art, names); + if let Some(mask) = d.node_mut(id).and_then(|n| n.extras_if_any()).and_then(|e| e.mask.as_deref_mut()) { + mask.art = Arc::new(art); + } + } + // And the graphs in symbols' art, which instances draw. + let symbols: BTreeSet = d.symbols.iter().map(|s| s.name.clone()).filter(|s| !skip_symbols.contains(s)).collect(); + redraw_symbols_with_designs(d, &symbols, names); Ok(()) } -/// The designs no graph's series draw with (Select Unused). +/// [`redraw_in`] for the clipboard: graph art `n`, outside the document, drawn again with `d`'s +/// designs `names`. +pub(crate) fn redraw_detached(d: &mut Document, n: &mut Node, names: &BTreeSet) { + if holds(n, names) { + redraw_in(d, n, names); + } +} + +/// Whether `n`'s subtree, the art of opacity masks included, holds a graph that draws a series +/// with one of the designs `names`. +pub(crate) fn holds_designs(n: &Node, names: &BTreeSet) -> bool { + holds(n, names) +} + +/// Draw the graphs in the subtrees of `ids` again that draw a series with one of the designs +/// `names`: pasted graphs, after the paste kept the document's own designs of those names. +pub(crate) fn redraw_with_designs(d: &mut Document, ids: &[super::NodeId], names: &std::collections::BTreeSet) -> Result<()> { + for id in ids { + let Some(mut n) = d.node(*id).filter(|n| holds(n, names)).cloned() else { continue }; + redraw_in(d, &mut n, names); + *d.node_mut(*id).ok_or(super::EngineError::NoNode(*id))? = n; + } + Ok(()) +} + +/// Draw the graphs in the art of symbols `symbols` again that draw a series with one of the +/// designs `names`: graphs of the symbols a paste added, after the paste kept the document's own +/// designs of those names. +pub(crate) fn redraw_symbols_with_designs( + d: &mut Document, + symbols: &std::collections::BTreeSet, + names: &std::collections::BTreeSet, +) { + for i in 0..d.symbols.len() { + let Some(s) = d.symbols.get(i).filter(|s| symbols.contains(&s.name) && holds(&s.art, names)) else { continue }; + let old = s.art.clone(); + let mut art = (*old).clone(); + redraw_in(d, &mut art, names); + let Some(s) = d.symbols.get_mut(i) else { continue }; + s.art = Arc::new(art); + // Instances' changes to parts the redraw replaced are dropped. + let name = s.name.clone(); + crate::cmd::symboledit::follow_art_change(d, &name, &old); + } +} + +/// Whether `n`'s subtree, the art of opacity masks included, holds a graph that draws a series +/// with one of the designs `names`. +fn holds(n: &Node, names: &std::collections::BTreeSet) -> bool { + let mut found = false; + vectorcraft_doc::swatches::walk_with_masks(n, &mut |m| { + found |= m.extras().graph.as_deref().is_some_and(|g| names.iter().any(|name| draws_with(g, name))); + }); + found +} + +/// Redraw the graphs of `n`'s subtree, the art of opacity masks included, that draw a series with +/// one of the designs `names`. +fn redraw_in(d: &mut Document, n: &mut Node, names: &std::collections::BTreeSet) { + if let Some(mut art) = n.extras().mask.as_deref().filter(|m| holds(&m.art, names)).map(|m| (*m.art).clone()) { + redraw_in(d, &mut art, names); + if let Some(mask) = n.extras_if_any().and_then(|e| e.mask.as_deref_mut()) { + mask.art = Arc::new(art); + } + } + if n.extras().graph.as_deref().is_some_and(|g| names.iter().any(|name| draws_with(g, name))) { + regenerate_detached(d, n); + return; + } + if let Some(children) = n.children_mut() { + for c in children.iter_mut().filter(|c| holds(c, names)) { + redraw_in(d, Arc::make_mut(c), names); + } + } +} + +/// The designs no graph's series draw with (Select Unused): graphs in the layers, in opacity-mask +/// art and in symbols' art count. fn unused_designs(d: &Document) -> Vec { let mut used = std::collections::HashSet::new(); - d.walk(|n| { + let mut note = |n: &Node| { if let Some(g) = n.extras().graph.as_deref() { used.extend(g.series_markers.iter().flatten().cloned()); used.extend(g.series_columns.iter().flatten().map(|c| c.design.clone())); } - }); + }; + for art in d.layers.iter().chain(d.symbols.iter().map(|s| &s.art)) { + vectorcraft_doc::swatches::walk_with_masks(art, &mut note); + } d.graph_designs.iter().map(|x| x.name.clone()).filter(|n| !used.contains(n)).collect() } +/// Whether `n`'s subtree, the art of opacity masks included, holds a graph that names design +/// `name` for a series ([`names_design`]). +fn names_in(n: &Node, name: &str) -> bool { + let mut found = false; + vectorcraft_doc::swatches::walk_with_masks(n, &mut |m| { + found |= m.extras().graph.as_deref().is_some_and(|g| names_design(g, name)); + }); + found +} + +/// Graph `g`'s series that name design `old` name `new` instead. +fn rename_series(g: &mut GraphSpec, old: &str, new: &str) { + for m in g.series_markers.iter_mut().flatten().filter(|m| **m == old) { + *m = new.to_string(); + } + for c in g.series_columns.iter_mut().flatten().filter(|c| c.design == old) { + c.design = new.to_string(); + } +} + +/// [`rename_series`] for the graphs of `n`'s subtree, the art of opacity masks included. +fn rename_in(n: &mut Node, old: &str, new: &str) { + if let Some(mask) = n.extras_if_any().and_then(|e| e.mask.as_deref_mut()).filter(|m| names_in(&m.art, old)) { + rename_in(Arc::make_mut(&mut mask.art), old, new); + } + if let Some(g) = n.extras_if_any().and_then(|e| e.graph.as_deref_mut()) { + rename_series(g, old, new); + } + if let Some(children) = n.children_mut() { + for c in children.iter_mut().filter(|c| names_in(c, old)) { + rename_in(Arc::make_mut(c), old, new); + } + } +} + /// Design names from param `key`: one name or a list of names. fn names_param(p: &Value, key: &str, cmd: &str) -> Result>> { match p.get(key) { @@ -105,22 +352,29 @@ pub(super) fn design(s: &mut Session, p: &Value) -> Result { if let Some(x) = d.graph_designs.iter_mut().find(|x| x.name == old) { x.name = new.clone(); } - let mut graphs = vec![]; + let (mut graphs, mut masked) = (vec![], vec![]); d.walk(|n| { - if n.extras().graph.as_deref().is_some_and(|g| draws_with(g, &old)) { + if n.extras().graph.as_deref().is_some_and(|g| names_design(g, &old)) { graphs.push(n.id); } + if n.extras().mask.as_deref().is_some_and(|m| names_in(&m.art, &old)) { + masked.push(n.id); + } }); for id in graphs { if let Some(g) = d.node_mut(id).and_then(|n| n.extras_if_any().and_then(|e| e.graph.as_deref_mut())) { - for m in g.series_markers.iter_mut().flatten().filter(|m| **m == old) { - *m = new.clone(); - } - for c in g.series_columns.iter_mut().flatten().filter(|c| c.design == old) { - c.design = new.clone(); - } + rename_series(g, &old, &new); } } + // The graphs in opacity-mask art and in symbols' art follow too, their art as it is. + for id in masked { + if let Some(mask) = d.node_mut(id).and_then(|n| n.extras_if_any()).and_then(|e| e.mask.as_deref_mut()) { + rename_in(Arc::make_mut(&mut mask.art), &old, &new); + } + } + for s in d.symbols.iter_mut().filter(|s| names_in(&s.art, &old)) { + rename_in(Arc::make_mut(&mut s.art), &old, &new); + } Ok(()) })?; return Ok(json!({ "name": to })); @@ -159,7 +413,29 @@ pub(super) fn design(s: &mut Session, p: &Value) -> Result { })?; return ok(); } + // Designs from a document loaded as a library: those the document has under the same name stay + // as they are. + if let Some(mut wanted) = names_param(p, "add", C)? { + let lib = library_param(s, p, C)?.ok_or_else(|| bad(C, "missing `library`"))?; + if let Some(n) = wanted.iter().find(|n| !lib.graph_designs.iter().any(|x| x.name == **n)) { + return Err(bad(C, format!("no design named `{n}`"))); + } + let mut seen = std::collections::HashSet::new(); + wanted.retain(|n| seen.insert(n.clone())); + let (existing, added): (Vec, Vec) = wanted.into_iter().partition(|n| taken(s, n)); + if !added.is_empty() { + s.edit("New Design", |d, _| bring_in(d, &lib, &added))?; + } + return Ok(json!({ "added": added, "existing": existing })); + } + if let Some(lib) = library_param(s, p, C)? { + return Ok(json!({ "designs": design_names(&lib) })); + } // The list, with the designs no graph draws with (Select Unused picks those). let d = &s.doc()?.doc; - Ok(json!({ "designs": design_names(d), "unused": unused_designs(d) })) + let mut out = json!({ "designs": design_names(d), "unused": unused_designs(d) }); + if let Some(libs) = libraries_json(s) { + out["libraries"] = libs; + } + Ok(out) } diff --git a/crates/engine/src/cmd/graph/edit.rs b/crates/engine/src/cmd/graph/edit.rs index 728eff6427..e5ce1e7ed0 100644 --- a/crates/engine/src/cmd/graph/edit.rs +++ b/crates/engine/src/cmd/graph/edit.rs @@ -109,6 +109,33 @@ pub(crate) fn edit_graph_art(n: &mut Node, edit: impl FnOnce(&mut Node)) { /// generation, which is recorded in the spec's `placed_art` bounds, or `placed` in graphs saved without them). pub(super) fn regenerate(d: &mut Document, id: NodeId, mut spec: GraphSpec) -> Result<()> { let n = d.node(id).ok_or(EngineError::NoNode(id))?; + carry_moves(n, &mut spec); + let children = generate(d, &spec); + spec.placed = children_bounds(&children); + spec.placed_art = art_bounds(&children); + let n = d.node_mut(id).ok_or(EngineError::NoNode(id))?; + if let Some(ch) = n.children_mut() { + *ch = children; + } + n.extras_mut().graph = Some(Box::new(spec)); + Ok(()) +} + +/// [`regenerate`] graph `n` from its own spec, where `n` is outside `d`'s layers (in a symbol's art). +pub(super) fn regenerate_detached(d: &mut Document, n: &mut Node) { + let Some(mut spec) = n.extras().graph.as_deref().cloned() else { return }; + carry_moves(n, &mut spec); + let children = generate(d, &spec); + spec.placed = children_bounds(&children); + spec.placed_art = art_bounds(&children); + if let Some(ch) = n.children_mut() { + *ch = children; + } + n.extras_mut().graph = Some(Box::new(spec)); +} + +/// Adjust `spec`'s plot rect for any move or scale of graph `n` since its last generation. +fn carry_moves(n: &Node, spec: &mut GraphSpec) { if let Some((placed, now)) = measured(n) && placed.width() > 1e-9 && placed.height() > 1e-9 @@ -119,15 +146,6 @@ pub(super) fn regenerate(d: &mut Document, id: NodeId, mut spec: GraphSpec) -> R * Affine::translate(-placed.origin().to_vec2()); spec.rect = a.transform_rect_bbox(spec.rect); } - let children = generate(d, &spec); - spec.placed = children_bounds(&children); - spec.placed_art = art_bounds(&children); - let n = d.node_mut(id).ok_or(EngineError::NoNode(id))?; - if let Some(ch) = n.children_mut() { - *ch = children; - } - n.extras_mut().graph = Some(Box::new(spec)); - Ok(()) } pub(super) fn create(s: &mut Session, p: &Value) -> Result { diff --git a/crates/engine/src/cmd/graph/markers.rs b/crates/engine/src/cmd/graph/markers.rs index 95a738ff7e..7b8a14d496 100644 --- a/crates/engine/src/cmd/graph/markers.rs +++ b/crates/engine/src/cmd/graph/markers.rs @@ -1,4 +1,4 @@ -use super::designs::design_names; +use super::designs::{bring_in_for, design_names, from_library, libraries_json}; use super::edit::{regenerate, spec_of, target}; use super::series::{picked_series, reselect_series}; use super::{Affine, Arc, Document, GraphSpec, Node, NodeKind, Rect, Result, Session, Value, bad, json}; @@ -55,7 +55,7 @@ pub(super) fn set_marker(s: &mut Session, p: &Value) -> Result { let mut spec = spec_of(s, id)?; let count = spec.rows.iter().map(Vec::len).max().unwrap_or(0).min(vectorcraft_doc::MAX_GRAPH_SERIES); let picked = picked_series(s, p, id, count, C)?; - let names = design_names(&s.doc()?.doc); + let mut names = design_names(&s.doc()?.doc); let Some(v) = p.get("design") else { // The design the picked series (all of them with none picked) share, or null. let all: Vec = if picked.is_empty() { (0..count).collect() } else { picked }; @@ -63,8 +63,15 @@ pub(super) fn set_marker(s: &mut Session, p: &Value) -> Result { let used: Vec> = all.iter().map(|i| spec.series_markers.get(*i).and_then(Option::as_ref).filter(|n| names.contains(n))).collect(); let shared = used.first().copied().flatten().filter(|d| used.iter().all(|x| *x == Some(*d))); - return Ok(json!({ "designs": names, "design": shared })); + let mut out = json!({ "designs": names, "design": shared }); + if let Some(libs) = libraries_json(s) { + out["libraries"] = libs; + } + return Ok(out); }; + // A design of a loaded library comes into the document in the same undo step. + let library = from_library(s, p, C)?; + names.extend(library.as_ref().map(|(_, n)| n.clone())); let design = match v { Value::Null => None, Value::String(n) if names.contains(n) => Some(n.clone()), @@ -83,10 +90,21 @@ pub(super) fn set_marker(s: &mut Session, p: &Value) -> Result { while spec.series_markers.last().is_some_and(Option::is_none) { spec.series_markers.pop(); } - if marker_cost(&spec, &marker_designs(&s.doc()?.doc, &spec)) > MARKER_BUDGET { + let cost = match &library { + Some((lib, name)) => { + let mut probe = (*s.doc()?.doc).clone(); + bring_in_for(&mut probe, lib, name, id, &mut spec)?; + marker_cost(&spec, &marker_designs(&probe, &spec)) + } + None => marker_cost(&spec, &marker_designs(&s.doc()?.doc, &spec)), + }; + if cost > MARKER_BUDGET { return Err(bad(C, "the design is too big to draw at every data point of this graph")); } s.edit("Graph Marker", |d, sel| { + if let Some((lib, name)) = &library { + bring_in_for(d, lib, name, id, &mut spec)?; + } regenerate(d, id, spec)?; if !reselect.is_empty() { reselect_series(d, sel, id, &reselect); diff --git a/crates/engine/src/cmd/graph/tests.rs b/crates/engine/src/cmd/graph/tests.rs index 5d50fb9c39..13394fc8d0 100644 --- a/crates/engine/src/cmd/graph/tests.rs +++ b/crates/engine/src/cmd/graph/tests.rs @@ -5469,6 +5469,964 @@ fn graph_designs_are_saved_pasted_and_deleted() { assert!(series_parts(&s, id, 0).iter().all(|n| matches!(n.kind, NodeKind::Path { .. }))); } +/// Graph design "Coin" in the active document: a 10 × 10 rectangle filled with global swatch "Gold". +fn save_coin_design(s: &mut Session) { + s.execute("swatch.new", &json!({"name": "Gold", "color": "#d4a017", "global": true})).unwrap(); + let r = s.execute("shape.rectangle", &json!({"x": 600, "y": 600, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap(); + s.execute("paint.setFill", &json!({"swatch": "Gold", "ids": [r]})).unwrap(); + s.execute("select.set", &json!({"ids": [r]})).unwrap(); + s.execute("graph.design", &json!({"new": "Coin"})).unwrap(); +} + +/// Load a saved document holding [`save_coin_design`]'s design as a swatch library (Other +/// Library…) → its id. +fn load_coin_library(s: &mut Session) -> String { + let mut src = Session::new(); + src.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_coin_design(&mut src); + let bytes = vectorcraft_format::save_file(&src.doc().unwrap().doc); + let p = json!({"dataBase64": vectorcraft_format::base64_encode(&bytes), "name": "Coins.vectorcraft"}); + let r = s.execute("swatch.library.load", &p).unwrap(); + assert_eq!(r["graphDesigns"], 1); + r["library"].as_str().unwrap().to_string() +} + +fn undo_len(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +/// Whether some object of `n` is filled with a colour linked to swatch `name`. +fn paints_with_swatch(n: &vectorcraft_doc::Node, name: &str) -> bool { + let mut found = false; + n.walk(&mut |m| found |= m.appearance.items.iter().any(|it| matches!(it.paint(), Paint::Solid { swatch: Some(w), .. } if w == name))); + found +} + +#[test] +fn designs_of_a_document_loaded_as_a_swatch_library_come_in_when_applied() { + let mut s = Session::new(); + let lib = load_coin_library(&mut s); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let id = graph(&mut s, "column"); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + // The Column dialog's list: none of the document's, Coin from the library. + let q = s.execute("graph.column", &json!({})).unwrap(); + assert_eq!((q["designs"].clone(), q["libraries"][0]["library"].clone()), (json!([]), json!(lib))); + assert_eq!(q["libraries"][0]["designs"], json!(["Coin"])); + assert!(s.execute("graph.column", &json!({"design": "Coin"})).is_err(), "not the document's"); + let steps = undo_len(&s); + s.execute("graph.column", &json!({"design": "Coin", "library": lib})).unwrap(); + assert_eq!(undo_len(&s), steps + 1, "one undo step"); + let d = &s.doc().unwrap().doc; + assert_eq!(d.graph_designs.iter().map(|g| g.name.as_str()).collect::>(), ["Coin"]); + assert!(d.swatch("Gold").is_some_and(|w| w.global), "the swatch the design's art uses comes along"); + assert!(paints_with_swatch(&d.graph_designs[0].art, "Gold")); + assert!(paints_with_swatch(series(d.node(id).unwrap(), 0), "Gold"), "the columns draw the design"); + // Undo takes the design, its swatch and the columns' design out together. + s.execute("edit.undo", &json!({})).unwrap(); + let d = &s.doc().unwrap().doc; + assert!(d.graph_designs.is_empty() && d.swatch("Gold").is_none() && spec(&s, id).series_columns.is_empty()); + // Marker takes them too. + let line = graph(&mut s, "line"); + s.execute("select.set", &json!({"ids": [line.0]})).unwrap(); + s.execute("graph.marker", &json!({"design": "Coin", "library": lib})).unwrap(); + assert_eq!(spec(&s, line).series_markers, [Some("Coin".to_string()), Some("Coin".to_string())]); + assert!(s.doc().unwrap().doc.swatch("Gold").is_some()); + // An unknown library or design, and a library that is not a string, are refused. + for p in [json!({"design": "Coin", "library": "Nope"}), json!({"design": "Nope", "library": lib}), json!({"design": "Coin", "library": 3})] { + assert!(s.execute("graph.column", &p).is_err(), "{p}"); + } +} + +#[test] +fn a_library_design_applied_to_a_moved_graph_that_names_it_keeps_the_graph_in_place() { + let mut s = Session::new(); + let lib = load_coin_library(&mut s); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + // A library's name works in any case, as swatch library names do. + assert_eq!(s.execute("graph.design", &json!({"library": "COINS"})).unwrap(), json!({"designs": ["Coin"]})); + for (kind, cmd) in [("line", "graph.marker"), ("column", "graph.column")] { + // The graph names design "Coin", which the document no longer has, and is moved after. + save_design(&mut s, "Coin"); + let id = graph(&mut s, kind); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute(cmd, &json!({"design": "Coin"})).unwrap(); + s.execute("graph.design", &json!({"delete": "Coin"})).unwrap(); + let rect = spec(&s, id).rect; + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("object.move", &json!({"dx": 40, "dy": -10})).unwrap(); + s.execute(cmd, &json!({"id": id.0, "design": "Coin", "library": lib})).unwrap(); + let now = spec(&s, id).rect; + assert!((now.x0 - (rect.x0 + 40.0)).abs() < 1e-6 && (now.y0 - (rect.y0 - 10.0)).abs() < 1e-6, "{cmd}: {now:?}"); + assert!((now.width() - rect.width()).abs() < 1e-6 && (now.height() - rect.height()).abs() < 1e-6, "{cmd}: {now:?}"); + s.execute("graph.design", &json!({"delete": "Coin"})).unwrap(); + } +} + +#[test] +fn a_design_the_document_has_under_the_same_name_stays_as_it_is() { + let mut s = Session::new(); + let lib = load_coin_library(&mut s); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_design(&mut s, "Coin"); + let own = s.doc().unwrap().doc.graph_designs[0].art.clone(); + assert_eq!(s.execute("graph.design", &json!({"library": lib})).unwrap(), json!({"designs": ["Coin"]})); + let steps = undo_len(&s); + let r = s.execute("graph.design", &json!({"library": lib, "add": ["Coin", "Coin"]})).unwrap(); + assert_eq!(r, json!({"added": [], "existing": ["Coin"]})); + assert_eq!(undo_len(&s), steps, "nothing changed: no undo step"); + // Applying it with the library draws with the document's own design. + let id = graph(&mut s, "column"); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("graph.column", &json!({"design": "Coin", "library": lib})).unwrap(); + let d = &s.doc().unwrap().doc; + assert!(d.graph_designs.len() == 1 && std::sync::Arc::ptr_eq(&d.graph_designs[0].art, &own)); + assert!(d.swatch("Gold").is_none()); + assert!(s.execute("graph.design", &json!({"add": "Coin"})).is_err(), "no library"); + assert!(s.execute("graph.design", &json!({"library": lib, "add": "Nope"})).is_err()); + assert!(s.execute("graph.design", &json!({"library": lib, "add": 4})).is_err()); + // The document without it takes it as one undo step. + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let r = s.execute("graph.design", &json!({"library": "Coins", "add": "Coin"})).unwrap(); + assert_eq!(r, json!({"added": ["Coin"], "existing": []})); + assert!(s.doc().unwrap().doc.swatch("Gold").is_some()); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.doc().unwrap().doc.graph_designs.is_empty()); +} + +#[test] +fn a_pasted_graph_brings_the_designs_its_series_draw_with() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_coin_design(&mut s); + let id = graph(&mut s, "column"); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("graph.column", &json!({"design": "Coin"})).unwrap(); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("edit.copy", &json!({})).unwrap(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + s.execute("edit.paste", &json!({})).unwrap(); + let d = &s.doc().unwrap().doc; + assert_eq!(d.graph_designs.iter().map(|g| g.name.as_str()).collect::>(), ["Coin"]); + assert!(paints_with_swatch(&d.graph_designs[0].art, "Gold") && d.swatch("Gold").is_some()); + // A data edit redraws the pasted graph with the design. + let pasted = s.doc().unwrap().selection.objects.to_vec()[0]; + s.execute("graph.setData", &json!({"id": pasted.0, "csv": ",A\nQ1,4\nQ2,6"})).unwrap(); + assert!(paints_with_swatch(series(s.doc().unwrap().doc.node(pasted).unwrap(), 0), "Gold")); + // A document with its own design of that name keeps it. + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_design(&mut s, "Coin"); + let own = s.doc().unwrap().doc.graph_designs[0].art.clone(); + s.execute("edit.paste", &json!({})).unwrap(); + let d = &s.doc().unwrap().doc; + assert!(d.graph_designs.len() == 1 && std::sync::Arc::ptr_eq(&d.graph_designs[0].art, &own)); + // The pasted graph is drawn with that design straight away. + let pasted = s.doc().unwrap().selection.objects.to_vec()[0]; + // The document's design is a rectangle and an ellipse, the pasted one a rectangle alone: each + // column and the legend swatch hold two paths. + let paths = |n: &vectorcraft_doc::Node| { + let mut count = 0; + n.walk(&mut |m| count += usize::from(matches!(m.kind, NodeKind::Path { .. }))); + count + }; + let columns: Vec = series(d.node(pasted).unwrap(), 0).children().unwrap().iter().map(|n| paths(n)).collect(); + assert_eq!(columns, [2, 2, 2, 2], "drawn with the document's design"); +} + +#[test] +fn a_design_the_document_keeps_brings_none_of_the_pasted_designs_resources() { + // A column graph whose spec names marker design "Coin", which only line series draw: the + // graph's own art does not use the design's swatch. + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_coin_design(&mut s); + let id = graph(&mut s, "column"); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("graph.marker", &json!({"design": "Coin"})).unwrap(); + assert!(spec(&s, id).series_markers.iter().any(|m| m.as_deref() == Some("Coin"))); + assert!(!paints_with_swatch(s.doc().unwrap().doc.node(id).unwrap(), "Gold")); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("edit.copy", &json!({})).unwrap(); + // A document with its own "Coin" keeps it and takes nothing the pasted design's art uses. + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_design(&mut s, "Coin"); + s.execute("edit.paste", &json!({})).unwrap(); + assert!(s.doc().unwrap().doc.swatch("Gold").is_none()); + // A document without one takes the design and its swatch. + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + s.execute("edit.paste", &json!({})).unwrap(); + assert!(s.doc().unwrap().doc.swatch("Gold").is_some()); +} + +#[test] +fn a_pasted_graph_naming_a_deleted_design_draws_with_the_documents_design_of_that_name() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_coin_design(&mut s); + let id = graph(&mut s, "column"); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("graph.column", &json!({"design": "Coin"})).unwrap(); + s.execute("graph.design", &json!({"delete": "Coin"})).unwrap(); + assert!(spec(&s, id).series_columns.iter().flatten().any(|c| c.design == "Coin"), "the graph still names it"); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("edit.copy", &json!({})).unwrap(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_design(&mut s, "Coin"); + s.execute("edit.paste", &json!({})).unwrap(); + let pasted = s.doc().unwrap().selection.objects.to_vec()[0]; + let paths = |n: &vectorcraft_doc::Node| { + let mut count = 0; + n.walk(&mut |m| count += usize::from(matches!(m.kind, NodeKind::Path { .. }))); + count + }; + let d = &s.doc().unwrap().doc; + let columns: Vec = series(d.node(pasted).unwrap(), 0).children().unwrap().iter().map(|n| paths(n)).collect(); + assert_eq!(columns, [2, 2, 2, 2], "drawn with the document's design"); +} + +#[test] +fn a_pasted_graph_keeps_its_art_when_only_a_resource_its_design_does_not_use_comes_in_renamed() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_design(&mut s, "Coin"); + s.execute("swatch.new", &json!({"name": "Ink", "color": "#ff0000", "global": true})).unwrap(); + let r = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + s.execute("paint.setFill", &json!({"swatch": "Ink", "ids": [r]})).unwrap(); + let id = graph(&mut s, "column"); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("graph.column", &json!({"design": "Coin"})).unwrap(); + // An edit of the graph's art that drawing the graph again would not keep. + let mark = series(s.doc().unwrap().doc.node(id).unwrap(), 0).children().unwrap()[0].id; + s.edit("Name", |d, _| { + if let Some(n) = d.node_mut(mark) { + n.name = Some("Mine".into()); + } + Ok(()) + }) + .unwrap(); + // A copy of the document holds the same design; its "Ink" is another color, so the pasted + // rectangle's swatch takes the document's color, or with "add" comes in renamed. + let saved = vectorcraft_format::base64_encode(&vectorcraft_format::save_file(&s.doc().unwrap().doc)); + s.execute("select.set", &json!({"ids": [id.0, r]})).unwrap(); + s.execute("edit.copy", &json!({})).unwrap(); + s.execute("document.open", &json!({"name": "b.vectorcraft", "dataBase64": saved})).unwrap(); + s.execute("swatch.edit", &json!({"name": "Ink", "color": "#0000ff"})).unwrap(); + for conflict in ["merge", "add"] { + let r = s.execute("edit.paste", &json!({"swatchConflict": conflict})).unwrap(); + let ink_renamed = r["renamed"].as_array().is_some_and(|a| a.iter().any(|x| x["from"] == "Ink")); + let expected = if conflict == "merge" { (json!(1), false) } else { (json!(0), true) }; + assert_eq!((r["merged"].clone(), ink_renamed), expected, "{conflict}: {r}"); + let st = s.doc().unwrap(); + let d = &st.doc; + let pasted = st.selection.objects.iter().copied().find(|i| d.node(*i).is_some_and(|n| n.extras().graph.is_some())).unwrap(); + let names: Vec> = series(d.node(pasted).unwrap(), 0).children().unwrap().iter().map(|n| n.name.clone()).collect(); + assert_eq!(names[0].as_deref(), Some("Mine"), "{conflict}: not drawn again: {names:?}"); + } +} + +#[test] +fn a_pasted_graph_is_drawn_again_when_its_designs_svg_filter_comes_in_under_another_name() { + const SHIFT: &str = r#""#; + const SHIFT_MORE: &str = r#""#; + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + s.execute("svgFilter.define", &json!({"xml": SHIFT})).unwrap(); + let r = s.execute("shape.rectangle", &json!({"x": 600, "y": 600, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap(); + s.execute("svgFilter.apply", &json!({"name": "Shift", "ids": [r]})).unwrap(); + s.execute("select.set", &json!({"ids": [r]})).unwrap(); + s.execute("graph.design", &json!({"new": "Coin"})).unwrap(); + let id = graph(&mut s, "column"); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("graph.column", &json!({"design": "Coin"})).unwrap(); + let mark = series(s.doc().unwrap().doc.node(id).unwrap(), 0).children().unwrap()[0].id; + s.edit("Name", |d, _| { + if let Some(n) = d.node_mut(mark) { + n.name = Some("Mine".into()); + } + Ok(()) + }) + .unwrap(); + // A copy of the document holds the same design, but its "Shift" filter draws otherwise, so the + // pasted graph's filter keeps its own definition under another name. + let saved = vectorcraft_format::base64_encode(&vectorcraft_format::save_file(&s.doc().unwrap().doc)); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("edit.copy", &json!({})).unwrap(); + s.execute("document.open", &json!({"name": "b.vectorcraft", "dataBase64": saved})).unwrap(); + s.execute("svgFilter.define", &json!({"xml": SHIFT_MORE, "replace": "Shift"})).unwrap(); + s.execute("edit.paste", &json!({})).unwrap(); + let st = s.doc().unwrap(); + let pasted = st.selection.objects.to_vec()[0]; + let names: Vec> = series(st.doc.node(pasted).unwrap(), 0).children().unwrap().iter().map(|n| n.name.clone()).collect(); + assert_ne!(names[0].as_deref(), Some("Mine"), "drawn again with the document's design: {names:?}"); +} + +#[test] +fn a_symbol_pasted_with_a_graph_inside_draws_it_with_the_documents_design_of_that_name() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_coin_design(&mut s); + let id = graph(&mut s, "column"); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("graph.column", &json!({"design": "Coin"})).unwrap(); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + let instance = s.execute("symbol.new", &json!({"name": "Chart"})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [instance]})).unwrap(); + s.execute("edit.copy", &json!({})).unwrap(); + // A document whose "Coin" is a rectangle and an ellipse: the symbol's graph draws with it. + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_design(&mut s, "Coin"); + s.execute("edit.paste", &json!({})).unwrap(); + let d = &s.doc().unwrap().doc; + let art = &d.symbols.iter().find(|x| x.name == "Chart").expect("the symbol came in").art; + let mut graphs = vec![]; + art.walk(&mut |m| { + if m.extras().graph.is_some() { + graphs.push(m.clone()); + } + }); + let paths = |n: &vectorcraft_doc::Node| { + let mut count = 0; + n.walk(&mut |m| count += usize::from(matches!(m.kind, NodeKind::Path { .. }))); + count + }; + let columns: Vec = series(&graphs[0], 0).children().unwrap().iter().map(|n| paths(n)).collect(); + assert_eq!(columns, [2, 2, 2, 2], "drawn with the document's design"); +} + +#[test] +fn a_design_brought_in_from_a_library_redraws_the_graphs_in_symbols_that_name_it() { + let mut s = Session::new(); + let lib = load_coin_library(&mut s); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + // A graph that names "Coin", which the document no longer has, kept as a symbol's art. + save_design(&mut s, "Coin"); + let id = graph(&mut s, "column"); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("graph.column", &json!({"design": "Coin"})).unwrap(); + s.execute("graph.design", &json!({"delete": "Coin"})).unwrap(); + s.execute("symbol.new", &json!({"name": "Chart", "ids": [id.0]})).unwrap(); + s.execute("graph.design", &json!({"library": lib, "add": "Coin"})).unwrap(); + let d = &s.doc().unwrap().doc; + let art = &d.symbols.iter().find(|x| x.name == "Chart").unwrap().art; + let mut graphs = vec![]; + art.walk(&mut |m| { + if m.extras().graph.is_some() { + graphs.push(m.clone()); + } + }); + assert!(paints_with_swatch(series(&graphs[0], 0), "Gold"), "drawn with the library's design"); +} + +#[test] +fn a_design_brought_in_from_a_library_leaves_a_scatter_graph_that_names_it_for_a_slot_it_does_not_plot() { + let mut s = Session::new(); + let lib = load_coin_library(&mut s); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + // Four data columns plot two series, so marker slot 2 is never drawn. + let id = make(&mut s, "scatter", ",y1,x1,y2,x2\nP,1,10,2,20\nQ,3,11,4,22"); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + assert!(spec(&s, id).mark_points, "Mark Data Points is on"); + s.execute("graph.marker", &json!({"design": "Coin", "library": lib, "seriesIndexes": [2]})).unwrap(); + s.execute("graph.design", &json!({"delete": "Coin"})).unwrap(); + assert_eq!(spec(&s, id).series_markers.get(2).cloned().flatten().as_deref(), Some("Coin")); + // An edit of the graph's art that drawing the graph again would not keep. + let mark = series(s.doc().unwrap().doc.node(id).unwrap(), 0).children().unwrap()[0].id; + s.edit("Name", |d, _| { + if let Some(n) = d.node_mut(mark) { + n.name = Some("Mine".into()); + } + Ok(()) + }) + .unwrap(); + s.execute("graph.design", &json!({"library": lib, "add": "Coin"})).unwrap(); + let names: Vec> = series(s.doc().unwrap().doc.node(id).unwrap(), 0).children().unwrap().iter().map(|n| n.name.clone()).collect(); + assert_eq!(names[0].as_deref(), Some("Mine"), "not drawn again: {names:?}"); +} + +#[test] +fn a_symbol_a_library_design_brings_draws_its_graph_with_the_documents_design_it_keeps() { + // The library's design "A" holds an instance of symbol "Chart", whose graph draws columns with + // the library's "B": a rectangle and an ellipse. + let mut src = Session::new(); + src.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_design(&mut src, "B"); + let id = graph(&mut src, "column"); + src.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + src.execute("graph.column", &json!({"design": "B"})).unwrap(); + let instance = src.execute("symbol.new", &json!({"name": "Chart", "ids": [id.0]})).unwrap()["id"].as_u64().unwrap(); + src.execute("select.set", &json!({"ids": [instance]})).unwrap(); + src.execute("graph.design", &json!({"new": "A"})).unwrap(); + let bytes = vectorcraft_format::save_file(&src.doc().unwrap().doc); + let mut s = Session::new(); + let p = json!({"dataBase64": vectorcraft_format::base64_encode(&bytes), "name": "Lib.vectorcraft"}); + let lib = s.execute("swatch.library.load", &p).unwrap()["library"].as_str().unwrap().to_string(); + // The document's own "B" is a single rectangle, and stays. + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let r = s.execute("shape.rectangle", &json!({"x": 600, "y": 600, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [r]})).unwrap(); + s.execute("graph.design", &json!({"new": "B"})).unwrap(); + s.execute("graph.design", &json!({"library": lib, "add": "A"})).unwrap(); + let d = &s.doc().unwrap().doc; + assert_eq!(d.graph_designs.len(), 2, "A came in and B stayed"); + let art = &d.symbols.iter().find(|x| x.name == "Chart").expect("the symbol came in").art; + let mut graphs = vec![]; + art.walk(&mut |m| { + if m.extras().graph.is_some() { + graphs.push(m.clone()); + } + }); + let paths = |n: &vectorcraft_doc::Node| { + let mut count = 0; + n.walk(&mut |m| count += usize::from(matches!(m.kind, NodeKind::Path { .. }))); + count + }; + let columns: Vec = series(&graphs[0], 0).children().unwrap().iter().map(|n| paths(n)).collect(); + assert_eq!(columns, [1, 1, 1, 1], "drawn with the document's B"); +} + +#[test] +fn a_design_brought_in_from_a_library_redraws_a_graph_in_an_opacity_mask() { + let mut s = Session::new(); + let lib = load_coin_library(&mut s); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_design(&mut s, "Coin"); + let r = s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 300, "height": 200})).unwrap()["id"].as_u64().unwrap(); + let id = graph(&mut s, "column"); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("graph.column", &json!({"design": "Coin"})).unwrap(); + s.execute("graph.design", &json!({"delete": "Coin"})).unwrap(); + s.execute("select.set", &json!({"ids": [r, id.0]})).unwrap(); + s.execute("transparency.makeOpacityMask", &json!({})).unwrap(); + s.execute("graph.design", &json!({"library": lib, "add": "Coin"})).unwrap(); + let mut graphs = vec![]; + vectorcraft_doc::swatches::walk_with_masks(s.doc().unwrap().doc.node(NodeId(r)).unwrap(), &mut |m| { + if m.extras().graph.is_some() { + graphs.push(m.clone()); + } + }); + assert!(paints_with_swatch(series(&graphs[0], 0), "Gold"), "drawn with the library's design"); +} + +#[test] +fn an_instance_drops_its_changes_to_graph_parts_a_design_change_redraws() { + use vectorcraft_doc::symbol_overrides::SymbolOverride; + let mut s = Session::new(); + let lib = load_coin_library(&mut s); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_design(&mut s, "Coin"); + let id = graph(&mut s, "column"); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("graph.column", &json!({"design": "Coin"})).unwrap(); + s.execute("graph.design", &json!({"delete": "Coin"})).unwrap(); + let instance = s.execute("symbol.new", &json!({"name": "Chart", "ids": [id.0], "type": "dynamic"})).unwrap()["id"].as_u64().unwrap(); + let instance = NodeId(instance); + // A change to the graph itself, and one to a part of it that drawing it again replaces. + let changes = vec![ + SymbolOverride { path: vec![], opacity: Some(0.5), ..Default::default() }, + SymbolOverride { path: vec![0], opacity: Some(0.25), ..Default::default() }, + ]; + s.edit("Change", |d, _| { + if let Some(n) = d.node_mut(instance) { + n.extras_mut().symbol_overrides = changes; + } + Ok(()) + }) + .unwrap(); + s.execute("graph.design", &json!({"library": lib, "add": "Coin"})).unwrap(); + let kept = s.doc().unwrap().doc.node(instance).unwrap().extras().symbol_overrides.clone(); + assert_eq!(kept.iter().map(|o| o.path.clone()).collect::>(), [Vec::::new()], "{kept:?}"); +} + +#[test] +fn a_graph_in_an_opacity_mask_draws_with_the_documents_design_when_pasted() { + let paths = |n: &vectorcraft_doc::Node| { + let mut count = 0; + n.walk(&mut |m| count += usize::from(matches!(m.kind, NodeKind::Path { .. }))); + count + }; + let mask_graph = |n: &vectorcraft_doc::Node| { + let mut graphs = vec![]; + vectorcraft_doc::swatches::walk_with_masks(n, &mut |m| { + if m.extras().graph.is_some() { + graphs.push(m.clone()); + } + }); + graphs.into_iter().next().expect("the masked graph") + }; + // In a symbol's art and among the pasted objects. + for in_symbol in [true, false] { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_coin_design(&mut s); + let r = s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 300, "height": 200})).unwrap()["id"].as_u64().unwrap(); + let id = graph(&mut s, "column"); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("graph.column", &json!({"design": "Coin"})).unwrap(); + s.execute("select.set", &json!({"ids": [r, id.0]})).unwrap(); + s.execute("transparency.makeOpacityMask", &json!({})).unwrap(); + let copied = if in_symbol { s.execute("symbol.new", &json!({"name": "Masked", "ids": [r]})).unwrap()["id"].as_u64().unwrap() } else { r }; + s.execute("select.set", &json!({"ids": [copied]})).unwrap(); + s.execute("edit.copy", &json!({})).unwrap(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_design(&mut s, "Coin"); + s.execute("edit.paste", &json!({})).unwrap(); + let st = s.doc().unwrap(); + let g = if in_symbol { + mask_graph(&st.doc.symbols.iter().find(|x| x.name == "Masked").expect("the symbol came in").art) + } else { + mask_graph(st.doc.node(st.selection.objects.to_vec()[0]).unwrap()) + }; + let columns: Vec = series(&g, 0).children().unwrap().iter().map(|n| paths(n)).collect(); + assert_eq!(columns, [2, 2, 2, 2], "in a symbol: {in_symbol}"); + } +} + +#[test] +fn a_graph_pasted_back_after_its_design_was_made_again_draws_with_the_new_design() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_coin_design(&mut s); + let id = graph(&mut s, "column"); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("graph.column", &json!({"design": "Coin"})).unwrap(); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("edit.copy", &json!({})).unwrap(); + // Made again under the same name as a rectangle and an ellipse. + s.execute("graph.design", &json!({"delete": "Coin"})).unwrap(); + save_design(&mut s, "Coin"); + s.execute("edit.paste", &json!({})).unwrap(); + let pasted = s.doc().unwrap().selection.objects.to_vec()[0]; + let paths = |n: &vectorcraft_doc::Node| { + let mut count = 0; + n.walk(&mut |m| count += usize::from(matches!(m.kind, NodeKind::Path { .. }))); + count + }; + let d = &s.doc().unwrap().doc; + let columns: Vec = series(d.node(pasted).unwrap(), 0).children().unwrap().iter().map(|n| paths(n)).collect(); + assert_eq!(columns, [2, 2, 2, 2], "drawn with the design the document has now"); +} + +/// The graphs in `n`'s subtree, those in opacity-mask art included. +fn graphs_in(n: &vectorcraft_doc::Node) -> Vec { + let mut graphs = vec![]; + vectorcraft_doc::swatches::walk_with_masks(n, &mut |m| { + if m.extras().graph.is_some() { + graphs.push(m.clone()); + } + }); + graphs +} + +/// Load a saved document holding [`save_coin_design`]'s "Coin" and design "Chart", an instance of +/// symbol "Plot" whose column graph names "Coin" as its columns (`columns`) or only as a marker +/// its columns do not draw, as a swatch library → its id. +fn load_chart_library(s: &mut Session, columns: bool) -> String { + let mut src = Session::new(); + src.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_coin_design(&mut src); + let id = graph(&mut src, "column"); + src.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + src.execute(if columns { "graph.column" } else { "graph.marker" }, &json!({"design": "Coin"})).unwrap(); + let instance = src.execute("symbol.new", &json!({"name": "Plot", "ids": [id.0]})).unwrap()["id"].as_u64().unwrap(); + src.execute("select.set", &json!({"ids": [instance]})).unwrap(); + src.execute("graph.design", &json!({"new": "Chart"})).unwrap(); + let bytes = vectorcraft_format::save_file(&src.doc().unwrap().doc); + let p = json!({"dataBase64": vectorcraft_format::base64_encode(&bytes), "name": "Charts.vectorcraft"}); + s.execute("swatch.library.load", &p).unwrap()["library"].as_str().unwrap().to_string() +} + +#[test] +fn a_library_design_brings_none_of_the_resources_of_a_design_the_document_keeps() { + let mut s = Session::new(); + let lib = load_chart_library(&mut s, false); + // The document keeps its own "Coin": nothing the library's "Coin" uses comes in. + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_design(&mut s, "Coin"); + s.execute("graph.design", &json!({"library": lib, "add": "Chart"})).unwrap(); + let d = &s.doc().unwrap().doc; + assert!(d.symbols.iter().any(|x| x.name == "Plot"), "the design's symbol came in"); + assert!(d.swatch("Gold").is_none()); + // A document without one takes the design and its swatch. + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + s.execute("graph.design", &json!({"library": lib, "add": "Chart"})).unwrap(); + let d = &s.doc().unwrap().doc; + assert!(d.graph_designs.iter().any(|x| x.name == "Coin") && d.swatch("Gold").is_some()); +} + +#[test] +fn a_design_a_library_design_brings_along_redraws_the_graphs_that_name_it() { + let mut s = Session::new(); + let lib = load_chart_library(&mut s, true); + // A graph that names "Coin", which the document no longer has. + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_design(&mut s, "Coin"); + let id = graph(&mut s, "column"); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("graph.column", &json!({"design": "Coin"})).unwrap(); + s.execute("graph.design", &json!({"delete": "Coin"})).unwrap(); + let r = s.execute("graph.design", &json!({"library": lib, "add": "Chart"})).unwrap(); + assert_eq!(r, json!({"added": ["Chart"], "existing": []})); + let d = &s.doc().unwrap().doc; + assert!(paints_with_swatch(series(d.node(id).unwrap(), 0), "Gold"), "drawn with the library's Coin"); +} + +#[test] +fn a_paste_that_adds_a_design_redraws_the_documents_graphs_that_name_it_and_not_the_pasted_ones() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_coin_design(&mut s); + let id = graph(&mut s, "column"); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("graph.column", &json!({"design": "Coin"})).unwrap(); + // An edit of the copied graph's art that drawing it again would not keep. + let mark = series(s.doc().unwrap().doc.node(id).unwrap(), 0).children().unwrap()[0].id; + s.edit("Name", |d, _| { + if let Some(n) = d.node_mut(mark) { + n.name = Some("Mine".into()); + } + Ok(()) + }) + .unwrap(); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("edit.copy", &json!({})).unwrap(); + // A document whose graph names "Coin", which it no longer has. + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_design(&mut s, "Coin"); + let own = graph(&mut s, "column"); + s.execute("select.set", &json!({"ids": [own.0]})).unwrap(); + s.execute("graph.column", &json!({"design": "Coin"})).unwrap(); + s.execute("graph.design", &json!({"delete": "Coin"})).unwrap(); + s.execute("edit.paste", &json!({})).unwrap(); + let st = s.doc().unwrap(); + assert!(paints_with_swatch(series(st.doc.node(own).unwrap(), 0), "Gold"), "drawn with the pasted Coin"); + let pasted = st.selection.objects.to_vec()[0]; + let first = series(st.doc.node(pasted).unwrap(), 0).children().unwrap()[0].name.clone(); + assert_eq!(first.as_deref(), Some("Mine"), "the pasted graph is not drawn again"); +} + +#[test] +fn a_paste_that_adds_a_marker_design_a_graph_does_not_show_leaves_that_graph_as_it_is() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_coin_design(&mut s); + let id = graph(&mut s, "column"); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("graph.column", &json!({"design": "Coin"})).unwrap(); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("edit.copy", &json!({})).unwrap(); + // A line graph whose series name "Coin", which the document no longer has, as a marker that + // Mark Data Points does not show, with no legend or with a legend that has no entry for them. + for (legend, csv) in [(false, ",2024,2025\nQ1,3,2\nQ2,5,4"), (true, ",,\nQ1,3,2\nQ2,5,4")] { + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_design(&mut s, "Coin"); + let p = json!({"type": "line", "x": 100, "y": 100, "width": 300, "height": 200, "csv": csv}); + let own = NodeId(s.execute("graph.create", &p).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [own.0]})).unwrap(); + s.execute("graph.marker", &json!({"design": "Coin"})).unwrap(); + s.execute("graph.setType", &json!({"id": own.0, "markPoints": false, "legend": legend})).unwrap(); + s.execute("graph.design", &json!({"delete": "Coin"})).unwrap(); + let mark = series(s.doc().unwrap().doc.node(own).unwrap(), 0).children().unwrap()[0].id; + s.edit("Name", |d, _| { + if let Some(n) = d.node_mut(mark) { + n.name = Some("Mine".into()); + } + Ok(()) + }) + .unwrap(); + s.execute("edit.paste", &json!({})).unwrap(); + let d = &s.doc().unwrap().doc; + assert!(d.graph_designs.iter().any(|x| x.name == "Coin"), "legend {legend}: the paste added Coin"); + let first = series(d.node(own).unwrap(), 0).children().unwrap()[0].name.clone(); + assert_eq!(first.as_deref(), Some("Mine"), "legend {legend}: not drawn again"); + } +} + +#[test] +fn a_symbol_pasted_twice_with_a_graph_the_document_draws_again_is_added_once() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_coin_design(&mut s); + let id = graph(&mut s, "column"); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("graph.column", &json!({"design": "Coin"})).unwrap(); + let instance = s.execute("symbol.new", &json!({"name": "Chart", "ids": [id.0]})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [instance]})).unwrap(); + s.execute("edit.copy", &json!({})).unwrap(); + // A document whose "Coin" is other art: the first paste draws the symbol's graph with it. + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_design(&mut s, "Coin"); + // The paths of each column of the symbol's graph: 2 for the document's Coin, 1 for the copied one. + let columns = |s: &Session| { + let art = s.doc().unwrap().doc.symbols.iter().find(|x| x.name == "Chart").unwrap().art.clone(); + let graph = graphs_in(&art).remove(0); + let paths = |n: &vectorcraft_doc::Node| { + let mut count = 0; + n.walk(&mut |m| count += usize::from(matches!(m.kind, NodeKind::Path { .. }))); + count + }; + series(&graph, 0).children().unwrap().iter().map(|n| paths(n)).collect::>() + }; + s.execute("edit.paste", &json!({})).unwrap(); + assert_eq!(columns(&s), [2, 2, 2, 2], "the first paste draws with the document's Coin"); + s.execute("edit.paste", &json!({})).unwrap(); + let d = &s.doc().unwrap().doc; + let names: Vec<&str> = d.symbols.iter().map(|x| x.name.as_str()).filter(|n| n.starts_with("Chart")).collect(); + assert_eq!(names, ["Chart"]); + assert_eq!(columns(&s), [2, 2, 2, 2], "drawn with the document's Coin"); +} + +#[test] +fn a_symbol_pasted_twice_whose_designs_swatch_takes_the_documents_color_is_added_once() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_coin_design(&mut s); + // A copy of the document holds the same "Coin"; its "Gold" is another color. + let saved = vectorcraft_format::base64_encode(&vectorcraft_format::save_file(&s.doc().unwrap().doc)); + let id = graph(&mut s, "column"); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("graph.column", &json!({"design": "Coin"})).unwrap(); + let instance = s.execute("symbol.new", &json!({"name": "Chart", "ids": [id.0]})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [instance]})).unwrap(); + s.execute("edit.copy", &json!({})).unwrap(); + for conflict in ["merge", "add"] { + s.execute("document.open", &json!({"name": format!("{conflict}.vectorcraft"), "dataBase64": saved})).unwrap(); + s.execute("swatch.edit", &json!({"name": "Gold", "color": "#0000ff"})).unwrap(); + let r = s.execute("edit.paste", &json!({"swatchConflict": conflict})).unwrap(); + let gold_renamed = r["renamed"].as_array().is_some_and(|a| a.iter().any(|x| x["from"] == "Gold")); + let expected = if conflict == "merge" { (json!(1), false) } else { (json!(0), true) }; + assert_eq!((r["merged"].clone(), gold_renamed), expected, "{conflict}: {r}"); + s.execute("edit.paste", &json!({"swatchConflict": conflict})).unwrap(); + let d = &s.doc().unwrap().doc; + let names: Vec<&str> = d.symbols.iter().map(|x| x.name.as_str()).filter(|n| n.starts_with("Chart")).collect(); + assert_eq!(names, ["Chart"], "{conflict}"); + } +} + +#[test] +fn a_pasted_graph_that_only_names_a_kept_design_as_an_undrawn_marker_keeps_its_art() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_coin_design(&mut s); + // A column graph whose series name "Coin" as a marker, which columns do not draw. + let id = graph(&mut s, "column"); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("graph.marker", &json!({"design": "Coin"})).unwrap(); + let mark = series(s.doc().unwrap().doc.node(id).unwrap(), 0).children().unwrap()[0].id; + s.edit("Name", |d, _| { + if let Some(n) = d.node_mut(mark) { + n.name = Some("Mine".into()); + } + Ok(()) + }) + .unwrap(); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("edit.copy", &json!({})).unwrap(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_design(&mut s, "Coin"); + s.execute("edit.paste", &json!({})).unwrap(); + let st = s.doc().unwrap(); + let pasted = st.selection.objects.to_vec()[0]; + let first = series(st.doc.node(pasted).unwrap(), 0).children().unwrap()[0].name.clone(); + assert_eq!(first.as_deref(), Some("Mine"), "not drawn again"); +} + +#[test] +fn renaming_a_design_renames_it_in_the_graphs_of_symbols_and_opacity_masks() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_coin_design(&mut s); + let in_symbol = graph(&mut s, "column"); + s.execute("select.set", &json!({"ids": [in_symbol.0]})).unwrap(); + s.execute("graph.column", &json!({"design": "Coin"})).unwrap(); + s.execute("symbol.new", &json!({"name": "Chart", "ids": [in_symbol.0]})).unwrap(); + let r = s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 300, "height": 200})).unwrap()["id"].as_u64().unwrap(); + let masked = graph(&mut s, "column"); + s.execute("select.set", &json!({"ids": [masked.0]})).unwrap(); + s.execute("graph.column", &json!({"design": "Coin"})).unwrap(); + s.execute("select.set", &json!({"ids": [r, masked.0]})).unwrap(); + s.execute("transparency.makeOpacityMask", &json!({})).unwrap(); + let before = graphs_in(&s.doc().unwrap().doc.symbols.iter().find(|x| x.name == "Chart").unwrap().art); + s.execute("graph.design", &json!({"rename": "Coin", "to": "Medal"})).unwrap(); + let d = &s.doc().unwrap().doc; + let symbol = graphs_in(&d.symbols.iter().find(|x| x.name == "Chart").unwrap().art); + let mask = graphs_in(d.node(NodeId(r)).unwrap()); + for (where_, g) in [("symbol", &symbol[0]), ("mask", &mask[0])] { + let designs: Vec = g.extras().graph.as_deref().unwrap().series_columns.iter().flatten().map(|c| c.design.clone()).collect(); + assert!(!designs.is_empty() && designs.iter().all(|n| n == "Medal"), "{where_}: {designs:?}"); + } + assert_eq!(symbol[0].children(), before[0].children(), "the symbol's graph keeps its art"); +} + +#[test] +fn a_design_only_a_graph_in_a_symbol_or_a_mask_draws_with_is_not_unused() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_design(&mut s, "Coin"); + save_design(&mut s, "Pill"); + let id = graph(&mut s, "column"); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("graph.column", &json!({"design": "Coin"})).unwrap(); + s.execute("symbol.new", &json!({"name": "Chart", "ids": [id.0]})).unwrap(); + let r = s.execute("shape.rectangle", &json!({"x": 100, "y": 100, "width": 300, "height": 200})).unwrap()["id"].as_u64().unwrap(); + let masked = graph(&mut s, "column"); + s.execute("select.set", &json!({"ids": [masked.0]})).unwrap(); + s.execute("graph.column", &json!({"design": "Pill"})).unwrap(); + s.execute("select.set", &json!({"ids": [r, masked.0]})).unwrap(); + s.execute("transparency.makeOpacityMask", &json!({})).unwrap(); + assert_eq!(s.execute("graph.design", &json!({})).unwrap()["unused"], json!([])); +} + +#[test] +fn a_library_copied_to_user_defined_keeps_its_graph_designs_under_the_loaded_id() { + let dir = vectorcraft_testkit::TempDir::new("graph-design-library-user"); + let mut s = Session::new(); + s.swatch_libraries.set_user_dir(Some(dir.to_string_lossy().to_string())); + let loaded = load_coin_library(&mut s); + // The User Defined copy is a swatch file: it holds the swatches alone. + let copy = s.execute("swatch.library.copyToUser", &json!({"library": loaded})).unwrap()["library"].as_str().unwrap().to_string(); + assert_ne!(copy, loaded); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + let libraries = s.execute("graph.design", &json!({})).unwrap()["libraries"].clone(); + assert_eq!(libraries, json!([{"library": loaded, "name": libraries[0]["name"], "designs": ["Coin"]}])); + assert_eq!(s.execute("graph.design", &json!({"library": loaded})).unwrap(), json!({"designs": ["Coin"]})); + assert!(s.execute("graph.design", &json!({"library": copy})).is_err()); +} + +#[test] +fn a_swatch_library_file_over_the_size_limit_is_refused_before_it_is_read() { + let dir = vectorcraft_testkit::TempDir::new("graph-design-library-size"); + let path = dir.join("big.vectorcraft"); + let f = std::fs::File::create(&path).unwrap(); + f.set_len(((256 << 20) + 1) as u64).unwrap(); + let mut s = Session::new(); + let e = s.execute("swatch.library.load", &json!({"path": path})).unwrap_err().to_string(); + assert!(e.contains("larger than 256 MB"), "{e}"); +} + +#[test] +fn a_document_with_graph_designs_and_no_swatches_loads_for_its_designs() { + let mut src = Session::new(); + src.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + save_design(&mut src, "Pill"); + let mut d = (*src.doc().unwrap().doc).clone(); + d.swatches.clear(); + d.swatch_groups.clear(); + let p = json!({"dataBase64": vectorcraft_format::base64_encode(&vectorcraft_format::save_file(&d)), "name": "Pills.vectorcraft"}); + let mut s = Session::new(); + let r = s.execute("swatch.library.load", &p).unwrap(); + assert_eq!((r["count"].clone(), r["graphDesigns"].clone()), (json!(0), json!(1))); + // Without graph designs it has nothing to offer. + d.graph_designs.clear(); + let p = json!({"dataBase64": vectorcraft_format::base64_encode(&vectorcraft_format::save_file(&d)), "name": "Bare.vectorcraft"}); + let e = s.execute("swatch.library.load", &p).unwrap_err().to_string(); + assert!(e.contains("has no swatches of its own"), "{e}"); +} + +#[test] +fn a_design_library_keeps_the_sources_color_for_a_default_swatch_name() { + let mut src = Session::new(); + src.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + // A default swatch the source made global and gave another color, used by a design. + let name = src.doc().unwrap().doc.swatches.iter().find(|w| !w.name.starts_with('[')).unwrap().name.clone(); + let mine = Paint::solid(vectorcraft_color::Color::rgb(0.1, 0.7, 0.3)); + let (n, p) = (name.clone(), mine.clone()); + src.edit("Change", move |d, _| { + if let Some(w) = d.swatches.iter_mut().find(|w| w.name == n) { + w.paint = p; + w.global = true; + } + Ok(()) + }) + .unwrap(); + let r = src.execute("shape.rectangle", &json!({"x": 600, "y": 600, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap(); + src.execute("paint.setFill", &json!({"swatch": name, "ids": [r]})).unwrap(); + src.execute("select.set", &json!({"ids": [r]})).unwrap(); + src.execute("graph.design", &json!({"new": "Green"})).unwrap(); + let lib = crate::cmd::clipboard::resources::graph_design_library(&src.doc().unwrap().doc).unwrap(); + let named: Vec<_> = lib.swatches.iter().filter(|w| w.name == name).collect(); + assert_eq!(named.len(), 1, "one swatch named {name}"); + assert_eq!(named[0].paint, mine); + // And one named like a swatch in a default group. + let grouped = src.doc().unwrap().doc.swatch_groups.iter().flat_map(|g| g.swatches.iter()).next().unwrap().name.clone(); + let (n, p) = (grouped.clone(), mine.clone()); + src.edit("Change", move |d, _| { + if let Some(w) = d.swatch_groups.iter_mut().flat_map(|g| g.swatches.iter_mut()).find(|w| w.name == n) { + w.paint = p; + w.global = true; + } + Ok(()) + }) + .unwrap(); + let r = src.execute("shape.rectangle", &json!({"x": 650, "y": 600, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap(); + src.execute("paint.setFill", &json!({"swatch": grouped, "ids": [r]})).unwrap(); + src.execute("select.set", &json!({"ids": [r]})).unwrap(); + src.execute("graph.design", &json!({"new": "Grouped"})).unwrap(); + let lib = crate::cmd::clipboard::resources::graph_design_library(&src.doc().unwrap().doc).unwrap(); + let all: Vec<_> = lib.swatches.iter().chain(lib.swatch_groups.iter().flat_map(|g| g.swatches.iter())).filter(|w| w.name == grouped).collect(); + assert_eq!(all.len(), 1, "one swatch named {grouped}"); +} + +#[test] +fn inline_swatch_library_data_over_the_size_limit_is_refused_before_it_is_read() { + // With a limit of 3 bytes: text and base64 of 3 bytes pass, and of 4 bytes are refused. + let too_big = |p: serde_json::Value| crate::cmd::swatchlib::library_too_big(&p, "swatch.library.load", 3).unwrap(); + assert!(!too_big(json!({"data": "abc"}))); + assert!(too_big(json!({"data": "abcd"}))); + let b64 = |n: usize| vectorcraft_format::base64_encode(&vec![7u8; n]); + assert!(!too_big(json!({"dataBase64": b64(3)}))); + assert!(too_big(json!({"dataBase64": b64(4)}))); +} + +#[test] +fn a_swatch_library_file_is_read_no_further_than_the_size_limit() { + let dir = vectorcraft_testkit::TempDir::new("graph-design-library-bound"); + let path = dir.join("grown.gpl"); + std::fs::write(&path, [b'a'; 9]).unwrap(); + let mut s = Session::new(); + let p = json!({"path": path}); + let parsed = |_: &[u8], _: &str| Err(crate::EngineError::Other("parsed".into())); + // A file that grew past the limit after the size check is refused when it is read. + let e = s.swatch_libraries.load_within(&p, "swatch.library.load", Some(8), parsed).unwrap_err().to_string(); + assert!(e.contains("larger than"), "{e}"); + let e = s.swatch_libraries.load_within(&p, "swatch.library.load", Some(9), parsed).unwrap_err().to_string(); + assert!(e.contains("parsed"), "{e}"); +} + +#[test] +fn reading_the_head_of_a_swatch_library_file_stops_at_the_limit() { + let dir = vectorcraft_testkit::TempDir::new("graph-design-library-head"); + let path = dir.join("long.gpl"); + std::fs::write(&path, vec![b'a'; 1 << 20]).unwrap(); + // The read the limit check relies on returns the bytes up to one past the limit, not the file. + let head = crate::cmd::fileio::read_file_head(&path.to_string_lossy(), 9).unwrap(); + assert_eq!(head.len(), 9); +} + +#[test] +fn a_library_design_brings_its_symbols_with_their_symbol_options() { + // The source design is an instance of symbol "Corner" with 9-slice scaling, a top-left + // registration point and the Graphic export type. + let mut src = Session::new(); + src.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + src.execute("shape.rectangle", &json!({"x": 600, "y": 600, "width": 10, "height": 10})).unwrap(); + src.execute("select.all", &json!({})).unwrap(); + let opts = json!({"name": "Corner", "nineSlice": true, "registration": 0, "exportType": "graphic"}); + let inst = src.execute("symbol.new", &opts).unwrap()["id"].as_u64().unwrap(); + src.execute("select.set", &json!({"ids": [inst]})).unwrap(); + src.execute("graph.design", &json!({"new": "Corner Mark"})).unwrap(); + let bytes = vectorcraft_format::save_file(&src.doc().unwrap().doc); + let mut s = Session::new(); + let p = json!({"dataBase64": vectorcraft_format::base64_encode(&bytes), "name": "Corners.vectorcraft"}); + let lib = s.execute("swatch.library.load", &p).unwrap()["library"].as_str().unwrap().to_string(); + s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap(); + s.execute("graph.design", &json!({"library": lib, "add": "Corner Mark"})).unwrap(); + let (from, to) = (&src.doc().unwrap().doc, &s.doc().unwrap().doc); + assert!(from.symbol_nine_slice("Corner").is_some()); + assert_eq!(to.symbol_nine_slice("Corner"), from.symbol_nine_slice("Corner")); + assert_eq!(to.symbol_registration("Corner"), from.symbol_registration("Corner")); + assert_eq!(to.symbol_export_type("Corner"), from.symbol_export_type("Corner")); +} + #[test] fn designs_and_markers_survive_save_and_open() { let mut s = Session::new(); diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index 392d6340c6..abb1a2d2aa 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -1211,6 +1211,16 @@ pub(crate) fn set_image_from_path(d: &mut Document, id: NodeId, path: &str, doc_ install(d, &[id], read, Some(Preserve::Bounds), None) } +/// Distorted image `im` shows the file read for `link` (`img`) and keeps its corners and its +/// clipping: the new pixels fill them. Its transform is scaled to the new pixel size, so a reader +/// that places it by the transform still gives it its old size. +fn refill_distorted(im: &mut ImageObject, link: &LinkInfo, img: &RasterImage) { + if (img.width, img.height) != (im.width, im.height) && img.width > 0 && img.height > 0 { + im.xf *= Affine::scale_non_uniform(f64::from(im.width) / f64::from(img.width), f64::from(im.height) / f64::from(img.height)); + } + (im.key, im.width, im.height, im.link) = (img.key.clone(), img.width, img.height, Some(link.clone())); +} + /// Image objects `ids` (in the layers or outside them) show the file read for `link` (`img`), each /// placed as its Placement Options say (`force`: as that Preserve choice says, whatever they say); /// with `also` (a file's path and the content shown), so do the images outside the layer tree that @@ -1235,7 +1245,12 @@ fn install(d: &mut Document, ids: &[NodeId], (link, img): FileRead, force: Optio let mut make = |n: &Node, held: Option<(&PathData, FillRule)>| { let mut n = n.clone(); let mut clip = ClipTo::Keep; + let distorted = n.is_distorted_image(); if let NodeKind::Image(im) = &mut n.kind { + if distorted { + refill_distorted(im, &link, &img); + return (n, clip); + } let o = PlacementOptions { preserve: force.unwrap_or(im.placement.preserve), ..im.placement }; let size = |w: u32, h: u32| (w as f64, h as f64); let (old_pt, old_clip) = match old.get(&im.key) { @@ -1251,6 +1266,14 @@ fn install(d: &mut Document, ids: &[NodeId], (link, img): FileRead, force: Optio Nested { pick: &pick, make: &mut make, next: 0 }.run(d); } for id in ids { + if d.node(*id).is_some_and(Node::is_distorted_image) { + if let Some(n) = d.node_mut(*id) + && let NodeKind::Image(im) = &mut n.kind + { + refill_distorted(im, &link, &img); + } + continue; + } let Some(NodeKind::Image(im)) = d.node(*id).map(|n| &n.kind) else { continue }; let o = PlacementOptions { preserve: force.unwrap_or(im.placement.preserve), ..im.placement }; let size = |w: u32, h: u32| (w as f64, h as f64); @@ -2068,6 +2091,9 @@ fn relink(s: &mut Session, p: &Value) -> Result { _ => None, }) }; + // Whether the images were found as the missing links (nothing selected, a folder given) rather + // than named or selected. + let mut found_missing = false; let mut ids: Vec = match (&each, ids_param(p, "ids", C)?) { (Some(each), _) => each.iter().flat_map(|(ids, _)| ids.iter().copied()).collect(), (None, Some(ids)) => ids, @@ -2075,6 +2101,7 @@ fn relink(s: &mut Session, p: &Value) -> Result { let selected: Vec = st.selection.objects.iter().copied().filter(|id| image(id).is_some()).collect(); match folder_param { Some(_) if selected.is_empty() => { + found_missing = true; groups(&st.doc, None).into_iter().filter(|g| probe(g, LinkBase::of(st)).0 == Status::Missing).flat_map(|g| g.ids).collect() } _ => selected, @@ -2087,6 +2114,11 @@ fn relink(s: &mut Session, p: &Value) -> Result { if ids.is_empty() { return Err(bad(C, "select the images to relink, or pass ids")); } + // A named or selected distorted image is refused before a folder is searched, whether or not + // its file is found there. + if !found_missing && let Some(id) = ids.iter().find(|id| stored(&doc, **id).is_some_and(Node::is_distorted_image)) { + return Err(super::xform::distorted_image_error(C, *id)); + } // All Instances: the other stored objects linked to the same files, each once. if scope == Scope::All { let paths: BTreeSet<&str> = ids.iter().filter_map(|id| image(id).flatten()).map(|l| l.path.as_str()).collect(); @@ -2131,6 +2163,11 @@ fn relink(s: &mut Session, p: &Value) -> Result { } (None, None, None) => return Err(bad(C, "give path (a file) or folder")), } + // A new file's placement options place a plain image: a distorted one is left as it is. + let distorted = files.iter().flat_map(|(ids, _)| ids).find(|id| stored(&doc, **id).is_some_and(Node::is_distorted_image)); + if let Some(id) = distorted { + return Err(super::xform::distorted_image_error(C, *id)); + } // Every file is read and checked before any is copied. let mut checked = vec![]; for (ids, path) in files { @@ -2593,6 +2630,9 @@ fn embed(s: &mut Session, p: &Value) -> Result { if ids.is_empty() { return Err(bad(C, "select the linked images or placed documents, or pass ids")); } + if let Some(id) = ids.iter().find(|id| stored(&doc, **id).is_some_and(Node::is_distorted_image)) { + return Err(super::xform::distorted_image_error(C, *id)); + } // A DCS file's plates print from its file. let separated = |id: &NodeId| match kind(id) { Some(NodeKind::Image(im)) => st.doc.images.get(&im.key).is_some_and(ImageBlob::is_separated), @@ -2721,6 +2761,9 @@ fn unembed(s: &mut Session, p: &Value) -> Result { if im.link.is_some() { return Err(bad(C, format!("image {} is linked already", id.0))); } + if n.is_distorted_image() { + return Err(super::xform::distorted_image_error(C, id)); + } let blob = st.doc.images.get(&im.key).filter(|b| !b.is_proxy()).ok_or_else(|| bad(C, "the image's pixels aren't in the document"))?; // As stored (PNG, JPEG, GIF, WebP), unless the path names another format. let stored = stored_extension(blob); @@ -2772,6 +2815,9 @@ fn unembed_to_folder(s: &mut Session, p: &Value, ids: Option>) -> Re skipped.push(id); continue; } + if n.is_distorted_image() { + return Err(super::xform::distorted_image_error(C, id)); + } let blob = st.doc.images.get(&im.key).filter(|b| !b.is_proxy()).ok_or_else(|| bad(C, "the image's pixels aren't in the document"))?; embedded.push((id, n.display_name(), blob)); } @@ -2984,7 +3030,9 @@ fn info(s: &mut Session, p: &Value) -> Result { let (px, py) = file_pt(&st.doc, &im.key); out["effectivePpi"] = out["ppi"].take(); out["ppi"] = json!([72.0 / px, 72.0 / py]); - (out["scale"], out["rotation"]) = scale_rotation(im.xf, (px, py)); + // A distorted image is measured at its middle, as its effective resolution is. + let xf = stored(&doc, id).and_then(vectorcraft_doc::image_quad::nearest_affine).unwrap_or(im.xf); + (out["scale"], out["rotation"]) = scale_rotation(xf, (px, py)); out["format"] = json!(format_label(&st.doc, im)); out["placement"] = placement_json(im.placement); out["status"] = json!("embedded"); diff --git a/crates/engine/src/cmd/live/blend.rs b/crates/engine/src/cmd/live/blend.rs index cfb87afdb3..d2e3f7b95a 100644 --- a/crates/engine/src/cmd/live/blend.rs +++ b/crates/engine/src/cmd/live/blend.rs @@ -244,12 +244,22 @@ pub(super) fn spine_move_anchor(s: &mut Session, p: &Value) -> Result { Some(_) => return Err(bad(C, "handle must be in or out")), }; let independent = switch_or(p, "independent", false, C)?; + let symmetric = switch_or(p, "symmetric", false, C)?; let link = switch_or(p, "link", false, C)?; let with = spine_points_param(p, C)?; // Any `with`, even an empty list, asks to move points, which a handle drag doesn't. if handle.is_some() && p.get("with").is_some_and(|v| !v.is_null()) { return Err(bad(C, "`with` moves points, not a handle")); } + if symmetric && independent { + return Err(bad(C, "`independent` and `symmetric` cannot both be true")); + } + if symmetric && handle.is_none() { + return Err(bad(C, "`symmetric` places a handle: give `handle`")); + } + if link && symmetric { + return Err(bad(C, "`link` and `symmetric` cannot both be true")); + } if link && independent { return Err(bad(C, "`link` and `independent` cannot both be true")); } @@ -264,6 +274,8 @@ pub(super) fn spine_move_anchor(s: &mut Session, p: &Value) -> Result { } edit_spine(s, p, C, "Reshape Spine", |sp, anchors, keys| { let pull_out = handle.is_some_and(|out| sp.has_segment(index, !out)); + // At an open end of the spine the handle moves as it would without `symmetric`. + let symmetric = symmetric && pull_out; let a = sp.anchors.get_mut(index).ok_or_else(|| bad(C, "no such spine point"))?; if let Some(out) = handle { if link { @@ -271,6 +283,10 @@ pub(super) fn spine_move_anchor(s: &mut Session, p: &Value) -> Result { } else { a.set_handle(out, q, independent); } + if symmetric { + let opposite = a.p - (q - a.p); + if out { a.h_in = opposite } else { a.h_out = opposite } + } return Ok(()); } let delta = q - a.p; diff --git a/crates/engine/src/cmd/live/commands.rs b/crates/engine/src/cmd/live/commands.rs index 991ebf103c..7d23f34a77 100644 --- a/crates/engine/src/cmd/live/commands.rs +++ b/crates/engine/src/cmd/live/commands.rs @@ -99,7 +99,7 @@ pub fn specs() -> Vec { "Move Spine Point", [], None, - "{id? (default: the selected blend), anchor: index, x, y, with?: [index…], handle?: in|out, independent?: bool, link?: bool} move a point of the blend's spine (its handles along), and the points `with` names by as much, or with `handle` place that handle's end at (x, y) (a smooth point keeps the other handle in line unless `independent`; `link` makes the point smooth with the other handle in line at its own length, a retracted one pulled out to the moved handle's length where a segment leaves the point on its side; `link` needs `handle` and cannot go with `independent`). A key object sitting on a moved point moves with it. The first edit turns the straight spine into a path", + "{id? (default: the selected blend), anchor: index, x, y, with?: [index…], handle?: in|out, independent?: bool, symmetric?: bool, link?: bool} move a point of the blend's spine (its handles along), and the points `with` names by as much, or with `handle` place that handle's end at (x, y) (a smooth point keeps the other handle in line unless `independent`; `symmetric` mirrors the opposite handle about the anchor without changing its kind, except at an open end of the spine; `link` makes the point smooth with the other handle in line at its own length, a retracted one pulled out to the moved handle's length where a segment leaves the point on its side; `symmetric` and `link` need `handle`, `symmetric` cannot go with `independent`, and `link` cannot go with `independent` or `symmetric`; all default false). A key object sitting on a moved point moves with it. The first edit turns the straight spine into a path", has_doc, spine_move_anchor ), diff --git a/crates/engine/src/cmd/live/mesh.rs b/crates/engine/src/cmd/live/mesh.rs index 97b6160718..70d31c2a34 100644 --- a/crates/engine/src/cmd/live/mesh.rs +++ b/crates/engine/src/cmd/live/mesh.rs @@ -25,14 +25,23 @@ pub(super) fn mesh_create(s: &mut Session, p: &Value) -> Result { }; let (rows, cols) = if at.is_some() { (1, 1) } else { (rows, cols) }; let roots = roots_param(s, p)?; + // The distorted images left as they are, each with why. + let mut distorted = vec![]; let (ids, index) = s.edit("Create Gradient Mesh", |d, sel| { let mut out = vec![]; let mut index = None; let mut refused = None; let model = d.color_mode.model(); + distorted.clear(); for id in &roots { let Some(n) = d.node(*id).cloned() else { continue }; let m = if let NodeKind::Image(im) = &n.kind { + if n.is_distorted_image() { + let e = super::super::xform::distorted_image_error(C, *id); + distorted.push(json!({"id": id.0, "reason": e.to_string()})); + refused.get_or_insert(e); + continue; + } // An embedded image: the points take the picture's colours there. match image_mesh(d, im, rows, cols) { Ok(mut m) => { @@ -40,7 +49,7 @@ pub(super) fn mesh_create(s: &mut Session, p: &Value) -> Result { Some(m) } Err(why) => { - refused.get_or_insert(why); + refused.get_or_insert_with(|| bad(C, why)); continue; } } @@ -60,7 +69,7 @@ pub(super) fn mesh_create(s: &mut Session, p: &Value) -> Result { match m.add_lines_at(q, tol) { Some(i) => index = Some(i), None => { - refused.get_or_insert("point is outside the object"); + refused.get_or_insert_with(|| bad(C, "point is outside the object")); continue; } } @@ -75,7 +84,7 @@ pub(super) fn mesh_create(s: &mut Session, p: &Value) -> Result { out.push(*id); } if out.is_empty() { - return Err(bad(C, refused.unwrap_or("select a path, a compound path or an embedded image"))); + return Err(refused.unwrap_or_else(|| bad(C, "select a path, a compound path or an embedded image"))); } sel.set(out.iter().copied()); Ok((out, index)) @@ -84,6 +93,9 @@ pub(super) fn mesh_create(s: &mut Session, p: &Value) -> Result { if let Some(i) = index { r["index"] = json!(i); } + if !distorted.is_empty() { + r["skipped"] = json!(distorted); + } Ok(r) } diff --git a/crates/engine/src/cmd/menucmds.rs b/crates/engine/src/cmd/menucmds.rs index a1464ebcef..aa330e11ea 100644 --- a/crates/engine/src/cmd/menucmds.rs +++ b/crates/engine/src/cmd/menucmds.rs @@ -998,6 +998,9 @@ fn mosaic_plan(s: &Session, p: &Value) -> Result { .ok_or_else(|| bad(C, "select an image"))?; let node = st.doc.node(id).ok_or(EngineError::NoNode(id))?; let NodeKind::Image(im) = &node.kind else { return Err(bad(C, "select an image")) }; + if node.is_distorted_image() { + return Err(super::xform::distorted_image_error(C, id)); + } if !st.doc.images.get(&im.key).is_some_and(|b| !b.bytes.is_empty()) { return Err(bad(C, "the image has no embedded pixels")); } @@ -1285,6 +1288,9 @@ fn crop_image(s: &mut Session, p: &Value) -> Result { .ok_or_else(|| bad(C, "select an image"))?; let node = st.doc.node(id).cloned().ok_or(EngineError::NoNode(id))?; let NodeKind::Image(im) = &node.kind else { return Err(bad(C, "select an image")) }; + if node.is_distorted_image() { + return Err(super::xform::distorted_image_error(C, id)); + } if switch_or(p, "trim", false, C)? { if p.get("ppi").is_some_and(|v| !v.is_null()) { return Err(bad(C, "trim keeps the image's pixels as they are: leave out ppi")); @@ -1495,11 +1501,16 @@ fn mask_image(s: &mut Session, _: &Value) -> Result { .selection .objects .iter() - .find_map(|id| match st.doc.node(*id).map(|n| &n.kind) { - Some(NodeKind::Image(im)) => { - Some((*id, vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, im.width as f64, im.height as f64)).transformed(im.xf))) + .find_map(|id| { + let n = st.doc.node(*id)?; + match &n.kind { + // A distorted image's outline joins its corners. + NodeKind::Image(_) if n.is_distorted_image() => Some((*id, PathData::from_bezpath(&n.image_frame()?))), + NodeKind::Image(im) => { + Some((*id, vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, im.width as f64, im.height as f64)).transformed(im.xf))) + } + _ => None, } - _ => None, }) .ok_or_else(|| bad("object.maskImage", "select an image"))?; let (gid, pid) = s.edit("Mask", |d, sel| { diff --git a/crates/engine/src/cmd/newart.rs b/crates/engine/src/cmd/newart.rs index d9d0905140..a42088e7e3 100644 --- a/crates/engine/src/cmd/newart.rs +++ b/crates/engine/src/cmd/newart.rs @@ -209,7 +209,7 @@ impl Session { /// the first selected object (so the last selection's once nothing is selected). Not while the /// Live Paint Bucket is the active tool: the fill and stroke are the colors it paints with. pub(crate) fn inherit_new_art(&mut self) { - if self.prefs.new_art_basic || self.tool_id() == super::paint::LIVE_PAINT_BUCKET { + if self.prefs.new_art_basic || self.bucket_paints() { return; } let Some(st) = self.active() else { return }; diff --git a/crates/engine/src/cmd/object/commands.rs b/crates/engine/src/cmd/object/commands.rs index e5ff38efa6..0bc08c748e 100644 --- a/crates/engine/src/cmd/object/commands.rs +++ b/crates/engine/src/cmd/object/commands.rs @@ -305,7 +305,7 @@ pub fn specs() -> Vec { "Live Shape Properties", [], None, - "{id?, ids?, radius?: pt (or % of each corner's maximum when `relativeRadii` is true), kind?: \"round\"|\"invertedRound\"|\"chamfer\", relativeRadii?: bool (Relative rounding, as in the reference app: store radii as fractions of each corner's maximum so they scale with the shape), corners?: [i…], items?: [{id, corners?: [i…]}] (several objects, each with its own corners, in place of ids and corners: the canvas's corner widgets across a selection), sides?: n, polygonAngle?: degrees (counter-clockwise from its first vertex straight up), polygonRadius?: pt (centre to vertex), sideLength?: pt (sets the radius), makeSidesEqual?: true (a polygon scaled unevenly: drops the uneven scale and shear, keeping its centre, angle and mean radius), pieStart?, pieEnd?: degrees (an ellipse's pie, counter-clockwise from 3 o'clock; 0 to 360 is the whole ellipse), invertPie?: true (swaps them: the other part of the ellipse), constrainPie?: bool (Constrain Pie Angle: with one of pieStart and pieEnd, not both and not with invertPie, the other angle moves by as much, so each ellipse keeps its span), lineLength?: pt (a live line's length, above 0; its first end stays), lineAngle?: degrees (a live line's angle, counter-clockwise from 3 o'clock, from its first end to its second; it turns about its midpoint), rectangleAngle?: degrees (a live rectangle's, counterclockwise from level), ellipseAngle?: degrees (a live ellipse's, counterclockwise from level; its pie turns with it)} (rectangleAngle, ellipseAngle and polygonAngle turn each shape of that kind about its own center and leave other objects as they are; a pixel-aligned shape then goes back on the pixel grid, as after other edits, which can move its center or change its size; an angle that is not a number is an error, and `null` counts as an omitted key; a shape that a turn would take past the coordinate limit (±4,000,000 pt) is an error that changes nothing; Live Corners on any path: radius and kind set its corners (anchors that aren't smooth, where two sides, straight or curved (#1144), meet at an angle): `corners` (anchor indices of the path with its corners uncut, counting every subpath's anchors in order: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; a polygon's from the first vertex clockwise), else the corners with a Direct-Selected anchor, else every corner; each radius is drawn no larger than half the corner's shorter side allows; a path that isn't a live shape keeps its uncut outline so its corners stay editable, and is plain again once none is cut; sides: a polygon's, which keep the radius they shared; the polygon params apply in that order: sides, makeSidesEqual, polygonAngle, then sideLength or else polygonRadius; a line's lineLength applies before its lineAngle)", + "{id?, ids?, radius?: pt (or % of each corner's maximum when `relativeRadii` is true), kind?: \"round\"|\"invertedRound\"|\"chamfer\", relativeRadii?: bool (Relative rounding, as in the reference app: store radii as fractions of each corner's maximum so they scale with the shape), corners?: [i…], rectanglesOnly?: bool (only the live rectangles among the targets; the other objects stay as they are), items?: [{id, corners?: [i…]}] (several objects, each with its own corners, in place of ids and corners: the canvas's corner widgets across a selection), sides?: n, polygonAngle?: degrees (counter-clockwise from its first vertex straight up), polygonRadius?: pt (centre to vertex), sideLength?: pt (sets the radius), makeSidesEqual?: true (a polygon scaled unevenly: drops the uneven scale and shear, keeping its centre, angle and mean radius), pieStart?, pieEnd?: degrees (an ellipse's pie, counter-clockwise from 3 o'clock; 0 to 360 is the whole ellipse), invertPie?: true (swaps them: the other part of the ellipse), constrainPie?: bool (Constrain Pie Angle: with one of pieStart and pieEnd, not both and not with invertPie, the other angle moves by as much, so each ellipse keeps its span), lineLength?: pt (a live line's length, above 0; its first end stays), lineAngle?: degrees (a live line's angle, counter-clockwise from 3 o'clock, from its first end to its second; it turns about its midpoint), rectangleAngle?: degrees (a live rectangle's, counterclockwise from level), ellipseAngle?: degrees (a live ellipse's, counterclockwise from level; its pie turns with it)} (rectangleAngle, ellipseAngle and polygonAngle turn each shape of that kind about its own center and leave other objects as they are; a pixel-aligned shape then goes back on the pixel grid, as after other edits, which can move its center or change its size; an angle that is not a number is an error, and `null` counts as an omitted key; a shape that a turn would take past the coordinate limit (±4,000,000 pt) is an error that changes nothing; Live Corners on any path: radius and kind set its corners (anchors that aren't smooth, where two sides, straight or curved (#1144), meet at an angle): `corners` (anchor indices of the path with its corners uncut, counting every subpath's anchors in order: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; a polygon's from the first vertex clockwise), else the corners with a Direct-Selected anchor, else every corner; each radius is drawn no larger than half the corner's shorter side allows; a path that isn't a live shape keeps its uncut outline so its corners stay editable, and is plain again once none is cut; sides: a polygon's, which keep the radius they shared; the polygon params apply in that order: sides, makeSidesEqual, polygonAngle, then sideLength or else polygonRadius; a line's lineLength applies before its lineAngle)", has_selection, set_live_shape ), diff --git a/crates/engine/src/cmd/object/shape.rs b/crates/engine/src/cmd/object/shape.rs index b2e69cc279..a4cec6253c 100644 --- a/crates/engine/src/cmd/object/shape.rs +++ b/crates/engine/src/cmd/object/shape.rs @@ -124,7 +124,7 @@ fn line_edit(l: &LiveShape, len: Option, angle: Option) -> Option Result { - check_switches(p, &["constrainPie", "invertPie", "makeSidesEqual", "relativeRadii"], "object.setLiveShape")?; + check_switches(p, &["constrainPie", "invertPie", "makeSidesEqual", "rectanglesOnly", "relativeRadii"], "object.setLiveShape")?; check_numbers(p, &["radius", "sides"], "object.setLiveShape")?; // `items`: objects each with its own `corners`; else `ids` (or the selection) sharing them. let items = match p.get("items").filter(|v| !v.is_null()) { @@ -235,6 +235,13 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result { // When every value given is the current one, the document and its undo history stay as they // are. let st = s.doc()?; + // `rectanglesOnly`: the live rectangles among the targets; the other objects stay as they are. + let ids: Vec = if p.get("rectanglesOnly").and_then(Value::as_bool) == Some(true) { + let rectangle = |id: &NodeId| matches!(st.doc.node(*id).map(|n| &n.kind), Some(NodeKind::Path { live: Some(l), .. }) if matches!(**l, LiveShape::Rectangle { .. })); + ids.into_iter().filter(rectangle).collect() + } else { + ids + }; // The lines that Line Length or Line Angle changes, as they become. A line that would reach // past the document's coordinate limit is an error before anything changes. let mut lines = std::collections::BTreeMap::new(); @@ -278,16 +285,23 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result { } let Some(c) = LiveCorners::new(path, live.as_deref()) else { return true }; let picked = corners_of(*id).unwrap_or_else(|| c.picked(st.selection.anchors.get(id))); - // Setting corners folds a scale left in a rectangle's transform into its size, which - // changes it. - live.as_deref().is_none_or(|l| l.folded() == *l) + // Setting a radius folds a scale left in a rectangle's transform into its size, which + // changes it. A kind the corners already have leaves the rectangle as it is. + (radius.is_none() || live.as_deref().is_none_or(|l| l.folded() == *l)) && picked.iter().all(|k| { *k < c.base.anchor_count() - && radius.is_none_or(|r| (c.drawn_radius(*k) - r.max(0.0)).abs() < 1e-9) + // A radius stored in document units can be larger than it draws; a relative + // one is a fraction, so it is compared as drawn. + && radius.is_none_or(|r| { + let now = if c.radii_relative() { c.drawn_radius(*k) } else { c.radius(*k) }; + (now - r.max(0.0)).abs() < 1e-9 + }) && kind.is_none_or(|kd| c.kind(*k) == kd) }) }; - if ids.iter().all(has_values) { + // The objects every value given already matches stay as they are, beside others that change. + let ids: Vec = ids.into_iter().filter(|id| !has_values(id)).collect(); + if ids.is_empty() { return ok(); } s.edit("Live Shape", |d, sel| { diff --git a/crates/engine/src/cmd/overprint.rs b/crates/engine/src/cmd/overprint.rs index 7435f04a3a..4c0b3ea9f4 100644 --- a/crates/engine/src/cmd/overprint.rs +++ b/crates/engine/src/cmd/overprint.rs @@ -21,7 +21,7 @@ pub fn specs() -> Vec { "Overprint", [], None, - "{fill?: bool, stroke?: bool, item?: appearance item index|null, ids?|id?, target?: \"object\"|\"contents\"} make fills and/or strokes overprint (Overprint Preview, Separations Preview) or knock out: item's, else every fill or stroke of the painted objects (groups: their contents; type: its characters too). Without item and ids, the Appearance panel's active item stands in when it is of that kind → {changed: objects}", + "{fill?: bool, stroke?: bool, item?: appearance item index|null, ids?|id?, target?: \"object\"|\"contents\"} make fills and/or strokes overprint (Overprint Preview, Separations Preview) or knock out: item's, else every fill or stroke of the painted objects (groups: their contents; type: its characters too). Without item and ids, the Appearance panel's active item stands in when it is of that kind. A whole Live Paint group (also its contents with `item`) takes the fill flags on its faces and the stroke flags on its edges, and its hidden source paths keep theirs → {changed: objects}", has_doc, set_overprint ), @@ -135,7 +135,7 @@ fn aims(s: &Session, p: &Value, cmd: &str, kinds: impl IntoIterator .into_iter() .map(|fill| { let it = item.of_kind(s, fill); - let ids = it.targets(s, p)?; + let ids = it.targets_for(s, p, fill)?; let ids = if edit { super::appearance::drop_design_art_rows(s, ids, it, fill, cmd)? } else { ids }; Ok((fill, it, ids)) }) diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs index 071c5f9862..b94a45e4f5 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/paint.rs @@ -203,10 +203,11 @@ impl Session { /// The object whose fill (or stroke) the proxy shows, with the Appearance panel's active item /// when it stands for it (see [`Session::proxy_paints`]); None: the defaults for new art. With /// an object of a dynamic symbol instance selected ([`DocState::selected_symbol_part`]), that - /// object as the instance draws it. None while the Live Paint Bucket is the active tool: the - /// proxies show the colors it paints with. + /// object as the instance draws it. None while the Live Paint Bucket is the active tool (or + /// another tool works for it, [`Session::bucket_paints`]): the proxies show the colors it + /// paints with. pub(crate) fn proxy_source(&self, stroke: bool) -> Option<(Cow<'_, Node>, Option)> { - if self.tool_id() == LIVE_PAINT_BUCKET { + if self.bucket_paints() { return None; } let st = self.active()?; @@ -215,12 +216,15 @@ impl Session { } let first = st.doc.node(*st.selection.subjects().first()?)?; let item = self.appearance_item(); + // Only an active Appearance row is shown here: it is a row of the first selected object. if first.appearance.item_of_kind(item, !stroke).is_some() { return Some((Cow::Borrowed(first), item)); } // A Live Paint group without faces (or edges) shows the next selected object's paint; any other - // object without a painted object shows the defaults for new art. - for id in st.selection.subjects() { + // object without a painted object shows the defaults for new art. A face or edge selected with + // its Live Paint group counts with the group, wherever it is in the selection. + let covered = live_paint_covered(&st.doc, st.selection.subjects()); + for id in st.selection.subjects().iter().filter(|id| !covered.contains(*id)) { let Some(n) = st.doc.node(*id) else { continue }; let mut nodes = vec![]; painted(n, true, stroke, &mut nodes); @@ -272,14 +276,6 @@ fn same_in_proxy(a: &Paint, b: &Paint) -> bool { } } -/// The ids of the faces and edges of `n` when it is a Live Paint group, else none. -pub(crate) fn live_paint_parts(n: &Node) -> Vec { - if !is_live_paint(n) { - return vec![]; - } - faces(n).into_iter().chain(edges(n)).map(|part| part.id).collect() -} - /// The objects whose paints the proxies show for a selected `n`, the ones the paint commands /// change ([`leaf_targets`]): groups and layers stand for their contents (and so do blends and /// other containers inside them), a compound path for its parts. A Live Paint group stands for its @@ -330,8 +326,9 @@ impl DocState { // Looking the first object up builds the id cache when there is none. let first = self.selection.objects.first().and_then(|id| self.doc.node(*id)); let (mut selected, mut fills, mut strokes) = (vec![], vec![], vec![]); - // The faces and edges of the selected Live Paint groups: selected as well, they count with their group's. - let mut covered = std::collections::HashSet::new(); + // The faces and edges of the selected Live Paint groups (or of those inside selected groups): selected as well, + // they count with their group's. + let covered = live_paint_covered(&self.doc, &self.selection.objects); // Every node with a selected id, in tree order: a repeated id (a damaged file) counts at each // place it appears. for n in self.doc.nodes_in_order(self.selection.objects.iter().copied()) { @@ -341,7 +338,6 @@ impl DocState { if covered.contains(&n.id) { continue; } - covered.extend(live_paint_parts(n)); painted(n, true, false, &mut fills); painted(n, true, true, &mut strokes); } @@ -378,11 +374,28 @@ impl DocState { } impl Session { + /// Do the fill and stroke proxies, and the paint commands that name no objects, stand for the + /// colors the Live Paint Bucket paints with? They do while the bucket is the active tool, while + /// a Cmd+click with the bucket uses the Selection tool, and while the Eyedropper samples into a + /// stop of the bucket's gradient for the Gradient panel's eyedropper, up to and including the + /// sample its click takes before it switches back to the bucket. + pub fn bucket_paints(&self) -> bool { + let for_bucket = |t: &dyn vectorcraft_tools::Tool| t.id() == LIVE_PAINT_BUCKET || t.returns_to() == Some(LIVE_PAINT_BUCKET); + // A Cmd+click lends the Selection tool to the bucket, or to the Eyedropper armed for it. + self.back_to_bucket || for_bucket(self.tool.as_ref()) || self.lender.as_deref().is_some_and(for_bucket) + } + + /// The tool the active tool's armed one-shot pick switches back to after its click + /// ([`vectorcraft_tools::Tool::returns_to`]). + pub fn tool_returns_to(&self) -> Option { + self.tool.returns_to().map(str::to_string) + } + /// [`DocState::proxy_mixed`] of the active document for the Appearance panel's active item. /// A gradient mesh with points picked ([`Session::fill_mesh_points`]) counts with their colors. /// Neither is mixed while the Live Paint Bucket is the active tool ([`Session::proxy_source`]). pub fn proxy_mixed(&self) -> (bool, bool) { - if self.tool_id() == LIVE_PAINT_BUCKET { + if self.bucket_paints() { return (false, false); } self.active().map_or((false, false), |st| st.proxy_mixed_with(self.appearance_item(), &self.fill_mesh_points())) @@ -737,12 +750,13 @@ pub(crate) fn apply_paint(s: &mut Session, p: &Value, paint: Paint, fill: bool) Ok(json!({"objects": ids.iter().collect::>().len()})) } -/// Is the Live Paint Bucket the active tool while `p` names no `ids`, `id` or `item`? A fill, +/// Is the Live Paint Bucket the active tool ([`Session::bucket_paints`]) while `p` names no `ids`, +/// `id` or `item`? A fill, /// stroke or stroke weight chosen then is what the bucket paints with, so it goes to the defaults /// and the selection keeps its paint. pub(crate) fn for_bucket(s: &Session, p: &Value) -> bool { // A null `ids` or `id` is no target, as `given_nodes` reads it; `item: null` names the top row. - s.tool_id() == LIVE_PAINT_BUCKET && ["ids", "id"].iter().all(|k| p.get(k).is_none_or(Value::is_null)) && p.get("item").is_none() + s.bucket_paints() && ["ids", "id"].iter().all(|k| p.get(k).is_none_or(Value::is_null)) && p.get("item").is_none() } /// `p` with `ids: []` when [`for_bucket`]: the paint goes to the defaults only. None otherwise. @@ -820,6 +834,36 @@ pub(crate) fn live_paint_parts_skipped(d: &Document, roots: &[NodeId], fill: boo out } +/// Faces, edges and the other objects (the hidden source paths) of Live Paint groups. +pub(crate) type LivePaintParts = (std::collections::HashSet, std::collections::HashSet, std::collections::HashSet); + +/// The faces, the edges and the hidden source paths of the Live Paint groups in `roots` (or inside them), +/// found as [`live_paint_parts_skipped`] finds them. +pub(crate) fn live_paint_split(d: &Document, roots: &[NodeId]) -> LivePaintParts { + let groups = live_paint_groups(d, roots); + let mut hidden = inside_live_paint(d, &groups); + let (mut faces, mut edges) = (std::collections::HashSet::new(), std::collections::HashSet::new()); + for (_, f, e) in &groups { + faces.extend(f.iter().copied()); + edges.extend(e.iter().copied()); + } + hidden.retain(|id| !faces.contains(id) && !edges.contains(id)); + (faces, edges, hidden) +} + +/// The faces and edges in `selected` whose Live Paint group is selected too, itself or inside another selected +/// object: they count with their group, wherever they are in `selected`. The groups are looked for only when an +/// object in `selected` is inside a Live Paint group. +pub(crate) fn live_paint_covered(d: &Document, selected: &[NodeId]) -> std::collections::HashSet { + let inside = |id: &NodeId| d.ancestry(*id).is_some_and(|up| up.iter().rev().skip(1).filter_map(|a| d.node(*a)).any(is_live_paint)); + if !selected.iter().any(inside) { + return std::collections::HashSet::new(); + } + let (mut parts, edges, _) = live_paint_split(d, selected); + parts.extend(edges); + parts +} + /// The instance whose object is selected with Direct Selection, and that object's path /// ([`super::brushsym::selected_part`]), when `p` names no `ids`, `id` or `item`: the paint commands /// then change that object. A bad `target` or `aligned` is refused as it is for any other selection. @@ -1337,7 +1381,7 @@ fn proxy_recolor(s: &mut Session, p: &Value, cmd: &str, label: &str, f: &dyn Fn( let item = item_target(s, p, cmd)?.of_kind(s, !stroke); // Read before the check below, so that a bad param (such as `target` or `aligned`, or an explicit `item` the art has // no row for) is still an error. - let targets = super::appearance::drop_design_art_rows(s, item.targets(s, p)?, item, !stroke, cmd)?; + let targets = super::appearance::drop_design_art_rows(s, item.targets_for(s, p, !stroke)?, item, !stroke, cmd)?; let of = match item { ItemTarget::Item { .. } => super::appearance::reference_of(s, p, item, cmd)?, ItemTarget::Top => None, diff --git a/crates/engine/src/cmd/paint/tests.rs b/crates/engine/src/cmd/paint/tests.rs index 77e061e993..8055a2f326 100644 --- a/crates/engine/src/cmd/paint/tests.rs +++ b/crates/engine/src/cmd/paint/tests.rs @@ -11,7 +11,7 @@ use vectorcraft_color::{Color, Paint}; use vectorcraft_doc::{Appearance, Document, LayerColor, Node, NodeId, NodeKind}; use vectorcraft_geom::{Rect, shapes}; -use super::{live_paint_parts, painted, picked_colors, proxy_paint, same_in_proxy}; +use super::{live_paint_covered, painted, picked_colors, proxy_paint, same_in_proxy}; use crate::{DocState, Session}; thread_local! { @@ -39,12 +39,11 @@ fn walked(st: &DocState, item: Option, points: &[(NodeId, Vec)]) - } let ids: HashSet = st.selection.objects.iter().copied().collect(); let (mut selected, mut fills, mut strokes) = (vec![], vec![], vec![]); - let mut covered = HashSet::new(); + let covered = live_paint_covered(&st.doc, &st.selection.objects); st.doc.walk(|n| { if ids.contains(&n.id) { selected.push(n); if !covered.contains(&n.id) { - covered.extend(live_paint_parts(n)); painted(n, true, false, &mut fills); painted(n, true, true, &mut strokes); } diff --git a/crates/engine/src/cmd/params.rs b/crates/engine/src/cmd/params.rs index 8e7d7f7b0f..64ce29e337 100644 --- a/crates/engine/src/cmd/params.rs +++ b/crates/engine/src/cmd/params.rs @@ -516,7 +516,30 @@ pub fn check_effect_params(id: &str, effect: &str, params: &Value) -> Result<()> } check_effect_color(id, effect, params)?; check_effect_channel(id, effect, params)?; - check_effect_center(id, effect, params) + check_effect_center(id, effect, params)?; + check_effect_pathfinder(id, effect, params) +} + +/// The Pathfinder Options in `params` of a Pathfinder effect (`effect`), as command `id` was given +/// them: `precision` a number of points from 0.001 to 10, and `removeRedundantPoints` and +/// `removeUnpainted` true or false. `effect.apply` and `effect.setParams` run this themselves +/// before they edit, as they run [`check_effect_color`]. +pub(crate) fn check_effect_pathfinder(id: &str, effect: &str, params: &Value) -> Result<()> { + use vectorcraft_render::effects; + if !effects::takes_pathfinder_options(effect) { + return Ok(()); + } + if let Some(v) = params.get("precision") + && !v.as_f64().is_some_and(|p| effects::PATHFINDER_EFFECT_PRECISION.contains(&p)) + { + return Err(bad(id, "precision must be from 0.001 to 10 pt")); + } + for key in ["removeRedundantPoints", "removeUnpainted"] { + if params.get(key).is_some_and(|v| !v.is_boolean()) { + return Err(bad(id, format!("`{key}` must be true or false"))); + } + } + Ok(()) } /// The type of the values in `params` of effect `effect`, as command `id` was given them: a key @@ -557,9 +580,11 @@ fn check_effect_types(id: &str, effect: &str, params: &Value) -> Result<()> { /// A value of the type effect `effect` reads for `key`, a parameter its params description names /// without a dialog default: the earlier 3D Perspective and light (`perspective`, `lightAzimuth`, /// `lightElevation`) and Scribble `variation` are numbers, an Outline Stroke's `width` is a number -/// and a Gaussian Blur's `linear` is true or false. A Glass, Texturizer or Rough Pastels -/// `textureImage`, an SVG filter's `name` and `xml`, a Warp's `version` and the `style` of Crop -/// Marks have checks of their own; they aren't listed. +/// and a Gaussian Blur's `linear` is true or false. A Pathfinder effect's `precision` is a number and +/// its `removeRedundantPoints` and `removeUnpainted` are true or false. A Glass, Texturizer or Rough +/// Pastels `textureImage`, an SVG filter's `name` and `xml`, a Warp's `version`, the `style` of Crop +/// Marks and an Extrude & Bevel's custom `bevelName` and `bevelProfile` have checks of their own; +/// they aren't listed. pub(crate) fn undefaulted_type(effect: &str, key: &str) -> Option { use vectorcraft_render::effects; let number = || Some(Value::from(0.0)); @@ -568,6 +593,8 @@ pub(crate) fn undefaulted_type(effect: &str, key: &str) -> Option { "variation" if effect == "stylize.scribble" => number(), "width" if effect == "path.outlineStroke" => number(), "linear" if effect == "blur.gaussian" => Some(Value::Bool(false)), + "precision" if effects::takes_pathfinder_options(effect) => number(), + "removeRedundantPoints" | "removeUnpainted" if effects::takes_pathfinder_options(effect) => Some(Value::Bool(false)), _ => None, } } diff --git a/crates/engine/src/cmd/path.rs b/crates/engine/src/cmd/path.rs index 6d01cabd2a..d32594d92d 100644 --- a/crates/engine/src/cmd/path.rs +++ b/crates/engine/src/cmd/path.rs @@ -50,7 +50,7 @@ pub fn specs() -> Vec { "Move Direction Handle", [], None, - "{id, subpath?, anchor, which: \"in\"|\"out\", x, y, independent?: bool, link?: bool, at?: [x,y]} move a direction handle; independent moves only that side and makes the anchor a corner; link makes the anchor smooth with the other handle in line at its own length (a retracted one is pulled out to the moved handle's length where a segment leaves the anchor on its side); link and independent cannot both be true; both default false; with link false, at moves the anchor and both handles before placing the chosen handle", + "{id, subpath?, anchor, which: \"in\"|\"out\", x, y, independent?: bool, symmetric?: bool, link?: bool, at?: [x,y]} move a direction handle; independent moves only that side and makes the anchor a corner; symmetric mirrors the other handle about the anchor without changing its kind (not at an open end, where no segment leaves the anchor on that side); link makes the anchor smooth with the other handle in line at its own length (a retracted one is pulled out to the moved handle's length where a segment leaves the anchor on its side); independent and symmetric cannot both be true, and link cannot go with either; all default false; with link false, at moves the anchor and both handles before placing the chosen handle", has_doc, set_handle ), @@ -461,6 +461,13 @@ fn set_handle(s: &mut Session, p: &Value) -> Result { return link_handle(s, p, id, si, ai, out, pos); } let independent = switch_or(p, "independent", false, "path.setHandle")?; + let symmetric = switch_or(p, "symmetric", false, "path.setHandle")?; + if symmetric && independent { + return Err(bad("path.setHandle", "`independent` and `symmetric` cannot both be true")); + } + // The other handle is mirrored only where a segment leaves the anchor on its side: at an open + // end the handle moves as it would without `symmetric`. + let symmetric = symmetric && has_segment(s, id, si, ai, !out)?; let at = match p.get("at").filter(|v| !v.is_null()) { None => None, Some(v) => Some(finite_numbers(v).map(|[x, y]| Point::new(x, y)).ok_or_else(|| bad("path.setHandle", "`at` must be [x, y]"))?), @@ -472,6 +479,7 @@ fn set_handle(s: &mut Session, p: &Value) -> Result { && at.is_none_or(|to| to == a.p) && (if out { a.h_out } else { a.h_in }) == pos && !(independent && a.kind != AnchorKind::Corner) + && (!symmetric || (if out { a.h_in } else { a.h_out }) == a.p - (pos - a.p)) { return ok(); } @@ -504,6 +512,10 @@ fn set_handle(s: &mut Session, p: &Value) -> Result { } else { a.set_handle(out, pos, independent); } + if symmetric { + let opposite = a.p - (pos - a.p); + if out { a.h_in = opposite } else { a.h_out = opposite } + } Ok(()) })?; ok() @@ -519,6 +531,9 @@ fn link_handle(s: &mut Session, p: &Value, id: NodeId, si: usize, ai: usize, out if switch_or(p, "independent", false, C)? { return Err(bad(C, "`link` and `independent` cannot both be true")); } + if switch_or(p, "symmetric", false, C)? { + return Err(bad(C, "`link` and `symmetric` cannot both be true")); + } if !(pos.x.abs() < 1e9 && pos.y.abs() < 1e9) { return Err(bad(C, "x and y must be finite")); } @@ -655,6 +670,16 @@ fn anchor_of(s: &Session, id: NodeId, si: usize, ai: usize) -> Result Result { + if s.script_running() { + return Err(EngineError::Busy); + } + let d = &s.doc()?.doc; + Ok(d.node(id).and_then(|n| n.path_data()).and_then(|path| path.subpaths.get(si)).is_some_and(|sp| sp.has_segment(ai, out))) +} + fn set_anchors(s: &mut Session, p: &Value) -> Result { let id = object_param(p, "id", "path.setAnchors")?.ok_or_else(|| bad("path.setAnchors", "missing id"))?; let subs = p.get("subpaths").and_then(Value::as_array).ok_or_else(|| bad("path.setAnchors", "missing subpaths"))?; diff --git a/crates/engine/src/cmd/pathops.rs b/crates/engine/src/cmd/pathops.rs index cb60409f17..96b9e51f99 100644 --- a/crates/engine/src/cmd/pathops.rs +++ b/crates/engine/src/cmd/pathops.rs @@ -685,14 +685,21 @@ fn pf_label(op: PathfinderOp) -> &'static str { } } -/// The Pathfinder Options an operation uses: those `p` gives, else the preferences'. They join the -/// command's journal entry, so replaying it gives the same result whatever the preferences are then. -fn pf_options(s: &mut Session, p: &Value, id: &str) -> Result { +/// The Pathfinder Options in the preferences, as the panel's operations and a new Pathfinder effect +/// take them. +pub(crate) fn current_pf_options(s: &Session) -> PathfinderOptions { let mut stored = s.prefs.pathfinder; if !PATHFINDER_PRECISION_RANGE.contains(&stored.precision) { // A preferences file edited by hand: the default, rather than refitting everything away. stored.precision = po::DEFAULT_PRECISION; } + stored +} + +/// The Pathfinder Options an operation uses: those `p` gives, else the preferences'. They join the +/// command's journal entry, so replaying it gives the same result whatever the preferences are then. +fn pf_options(s: &mut Session, p: &Value, id: &str) -> Result { + let stored = current_pf_options(s); let keys = ["precision", "removeRedundantPoints", "removeUnpainted"]; let given: serde_json::Map = p.as_object().into_iter().flatten().filter(|(k, _)| keys.contains(&k.as_str())).map(|(k, v)| (k.clone(), v.clone())).collect(); diff --git a/crates/engine/src/cmd/place.rs b/crates/engine/src/cmd/place.rs index 9ff644ca6d..b97109026f 100644 --- a/crates/engine/src/cmd/place.rs +++ b/crates/engine/src/cmd/place.rs @@ -630,19 +630,7 @@ fn at_param(p: &Value) -> Result> { /// `image_xf`), also for an image alone in a clip group when the new art is an image, clipped by /// its file's clipping path or not (`new_image`); other objects keep their centre. fn replace_xf(d: &Document, old: &Node, natural: Rect, image_xf: bool, new_image: bool) -> Affine { - // An image alone in a clip group (as a PSD or PSB file's clipping path places it, - // [`fileio::file_clipped`]) is measured as the image when the new art is an image; a DCS - // file's plates are not. - let image = match &old.kind { - NodeKind::Group { children, clip: true } if new_image => match &children[..] { - [path, image] if matches!(path.kind, NodeKind::Path { clipping: true, .. }) => match &image.kind { - NodeKind::Image(im) if d.images.get(&im.key).is_none_or(|b| b.separated().is_none()) => image, - _ => old, - }, - _ => old, - }, - _ => old, - }; + let image = replace_measured(d, old, new_image); if image_xf && let NodeKind::Image(im) = &image.kind { let (sx, sy) = pt_per_px(d.images.get(&im.key).and_then(|b| fileio::ppi::resolution(&b.bytes))); let full = Affine::scale_non_uniform(sx, sy); @@ -655,6 +643,22 @@ fn replace_xf(d: &Document, old: &Node, natural: Rect, image_xf: bool, new_image Affine::translate(c - natural.center()) } +/// The object [`replace_xf`] measures when Replace swaps `old`: an image alone in a clip group (as +/// a PSD or PSB file's clipping path places it, [`fileio::file_clipped`]) when the new art is an +/// image (`new_image`), except a DCS file's plates; else `old` itself. +fn replace_measured<'a>(d: &Document, old: &'a Node, new_image: bool) -> &'a Node { + match &old.kind { + NodeKind::Group { children, clip: true } if new_image => match &children[..] { + [path, image] if matches!(path.kind, NodeKind::Path { clipping: true, .. }) => match &image.kind { + NodeKind::Image(im) if d.images.get(&im.key).is_none_or(|b| b.separated().is_none()) => image, + _ => old, + }, + _ => old, + }, + _ => old, + } +} + /// `rect` fitted with `natural`'s aspect, centred. fn fit(natural: Rect, r: Rect) -> Affine { let ratio = |a: f64, b: f64| (b > 1e-9).then(|| a / b); @@ -814,6 +818,17 @@ fn apply(s: &mut Session, read: PlaceRead) -> Result { loaded.natural = Rect::from_origin_size(Point::ORIGIN, size); } let natural = loaded.natural; + // Replace keeps the transform of the image it measures (`replace_measured`), which a + // distortion's corners do not follow. Type, and any other object it measures, is placed by the + // bounds of what it replaces, so a distorted image there is not refused. + if let Some(o) = old_node + && !is_text + { + let image = replace_measured(&st.doc, o, matches!(loaded.art, Art::Image(..))); + if image.is_distorted_image() { + return Err(super::xform::distorted_image_error(PLACE, image.id)); + } + } let m = match (old_node, rect) { (Some(o), _) => replace_xf(&st.doc, o, natural, !is_text, matches!(loaded.art, Art::Image(..))), (None, Some(r)) => fit(natural, r), @@ -1173,6 +1188,8 @@ pub(crate) fn image_info(s: &mut Session, p: &Value) -> Result { let doc = super::links::with_brush_art(&st.doc); let n = doc.stored_node(id).map(|(n, _)| &**n).ok_or(EngineError::NoNode(id))?; let NodeKind::Image(im) = &n.kind else { return Err(bad(C, format!("object {} is not an image", id.0))) }; + // Effective resolution, taken at the middle of a distorted image. + let ppi = effective_ppi(vectorcraft_doc::image_quad::nearest_affine(n).unwrap_or(im.xf)); let size = n.geometric_bounds().unwrap_or_default(); // A linked file outside the read roots of the caller asking now is left unnamed, as in Link Info. let doc_path = super::links::LinkBase::of(st).doc; @@ -1184,7 +1201,7 @@ pub(crate) fn image_info(s: &mut Session, p: &Value) -> Result { "colorMode": st.doc.images.get(&im.key).map_or("RGB", |b| color_mode(&b.bytes)), "pixelWidth": im.width, "pixelHeight": im.height, - "ppi": effective_ppi(im.xf), + "ppi": ppi, "width": size.width(), "height": size.height(), })) diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index fa41a609c8..1230e0764d 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -153,6 +153,7 @@ pub(super) const ALLOWED: &[&str] = &[ "color.gamutCheck", "color.harmony", "color.plates", + "color.used", "dataset.capture", "dataset.delete", "dataset.list", @@ -746,5 +747,7 @@ pub(super) const DENIED: &[&str] = &[ "stroke.arrowheads.edit", "stroke.arrowheads.list", "text.similarFonts", + "threeD.bevels.edit", + "threeD.bevels.list", "type.compositeFonts.set", ]; diff --git a/crates/engine/src/cmd/prefscmds.rs b/crates/engine/src/cmd/prefscmds.rs index f66322498e..46cdee28a5 100644 --- a/crates/engine/src/cmd/prefscmds.rs +++ b/crates/engine/src/cmd/prefscmds.rs @@ -404,6 +404,7 @@ pub const PREF_SPECS: &[PrefSpec] = &[ "Update Links", choice(&[("automatically", "Automatically"), ("manually", "Manually"), ("askWhenModified", "Ask When Modified")]) ), + p!("pdfTextAs", "File Handling", "Files", "PDF Text", choice(&[("text", "Editable"), ("outlines", "Outlines")])), // Clipboard Handling p!("copyAsSvg", "Clipboard Handling", "On Copy", "Include SVG Code", bool), p!("copyAsPdf", "Clipboard Handling", "On Copy", "PDF", bool), @@ -752,6 +753,13 @@ impl Session { t.set_option("cornerRadius", &r); } } + // A press of the tool that is dropped keeps the new radius, also when the tool lent a + // selection tool for the press. + if self.press_taken_by("roundedRectangle") + && let Some((_, saved)) = self.press_options.as_mut() + { + saved.insert("cornerRadius".into(), r); + } } if fonts_folder_changed { let folder = self.prefs.fonts_folder.trim(); diff --git a/crates/engine/src/cmd/rasterfx.rs b/crates/engine/src/cmd/rasterfx.rs index e5c951e087..d5f90d2411 100644 --- a/crates/engine/src/cmd/rasterfx.rs +++ b/crates/engine/src/cmd/rasterfx.rs @@ -455,6 +455,10 @@ fn places(map: Affine) -> bool { /// member). pub(crate) fn replace_with_image(mut v: Node, image: Node) -> Node { if !v.is_layer() { + // The new pixels already show a distorted image's distortion. + if let Some(e) = v.extras_if_any() { + e.image_quad = None; + } return Node { kind: image.kind, appearance: Default::default(), ..v }; } v.appearance = Default::default(); diff --git a/crates/engine/src/cmd/recolor.rs b/crates/engine/src/cmd/recolor.rs index 1c3acf4e73..b4ad26400b 100644 --- a/crates/engine/src/cmd/recolor.rs +++ b/crates/engine/src/cmd/recolor.rs @@ -29,6 +29,15 @@ pub fn specs() -> Vec { has_doc, colors ), + cmd!( + query "color.used", + "Document Colors", + [], + None, + "{selection?: true (false: the objects select.all takes, also while something is selected), limit?: n (only the n most used; default all)} → {colors: [{key, hex, color: the color in its own model ({model, …}), count, swatch?: the global swatch it is linked to (from its first linked use in paint order, a plain use before a gradient stop that mixes the swatch's ink with process inks; left out when only such stops link it), tint?: 0..100 to three decimals (the percent of that swatch's color the same use stores)}] as recolor.colors lists them, selection: true when they are the selection's, uses: the uses of every color, those past limit included} the unique colors of the selection, or with nothing selected or selection false of the objects select.all takes without the hidden and locked objects inside them, most used first; the selection is left as it is", + has_doc, + used + ), cmd!( "recolor.apply", "Recolor Artwork", @@ -130,7 +139,8 @@ type Region = (vectorcraft_geom::BezPath, vectorcraft_geom::FillRule); #[derive(Clone)] struct ImageRead<'a> { blob: &'a vectorcraft_doc::ImageBlob, - xf: vectorcraft_geom::Affine, + /// Pixel space to the page: the image's transform, or a distorted image's projective map. + map: vectorcraft_geom::Homography, size: (f64, f64), area: Option, clip: Option>, @@ -261,9 +271,9 @@ impl<'a> Theme<'a> { let keeps: Vec bool + '_>> = group .iter() .map(|r| { - let (xf, (w, h), area, clip, cost, tested) = (r.xf, r.size, r.area, &r.clip, elements(r), &tested); + let (map, (w, h), area, clip, cost, tested) = (r.map, r.size, r.area, &r.clip, elements(r), &tested); Box::new(move |u: f64, v: f64| { - let p = xf * Point::new(u * w, v * h); + let Some(p) = map.apply(Point::new(u * w, v * h)) else { return false }; area.is_none_or(|a| a.contains(p)) && clip.as_ref().is_none_or(|rs| { tested.set(tested.get().saturating_add(cost)); @@ -278,7 +288,7 @@ impl<'a> Theme<'a> { .map(|(r, keep)| { use vectorcraft_geom::kurbo::Shape; let (w, h) = r.size; - let inv = r.xf.inverse(); + let inv = r.map.inverse(); // The box sampled: the marquee, cut to the clipping paths' bounds, so a small // region a clip shows of a large image is still sampled densely. let clip_box = r.clip.as_ref().map(|rs| rs.iter().map(|(bp, _)| bp.bounding_box()).reduce(|a, b| a.union(b)).unwrap_or_default()); @@ -286,12 +296,16 @@ impl<'a> Theme<'a> { (Some(a), Some(c)) => Some(a.intersect(c)), (a, c) => a.or(c), }; - let box_uv = region.map(|a| { - let uv: Vec = - [(a.x0, a.y0), (a.x1, a.y0), (a.x0, a.y1), (a.x1, a.y1)].into_iter().map(|(x, y)| inv * Point::new(x, y)).collect(); + // A region that crosses a distorted image's horizon has no box: the whole + // image is sampled, and `keep` tests each pixel. + let box_uv = region.zip(inv).and_then(|(a, inv)| { + let uv: Vec = [(a.x0, a.y0), (a.x1, a.y0), (a.x0, a.y1), (a.x1, a.y1)] + .into_iter() + .map(|(x, y)| inv.apply(Point::new(x, y))) + .collect::>()?; let low = |f: fn(&Point) -> f64| uv.iter().map(f).fold(f64::INFINITY, f64::min); let high = |f: fn(&Point) -> f64| uv.iter().map(f).fold(f64::NEG_INFINITY, f64::max); - [low(|p| p.x) / w, low(|p| p.y) / h, high(|p| p.x) / w, high(|p| p.y) / h] + Some([low(|p| p.x) / w, low(|p| p.y) / h, high(|p| p.x) / w, high(|p| p.y) / h]) }); (box_uv, if r.clip.is_some() { clipped } else { budget }, keep.as_ref()) }) @@ -401,7 +415,9 @@ impl<'a> Theme<'a> { None }; let size = (f64::from(im.width.max(1)), f64::from(im.height.max(1))); - self.queue_image(ImageRead { blob, xf: im.xf, size, area, clip: self.clip.clone(), colorize }); + // A distorted image's pixels are where its projective map puts them. + let map = n.image_map().unwrap_or_else(|| vectorcraft_geom::Homography::from_affine(im.xf)); + self.queue_image(ImageRead { blob, map, size, area, clip: self.clip.clone(), colorize }); return; } NodeKind::SymbolInstance { symbol, xf } => { @@ -945,16 +961,19 @@ fn pick_theme(s: &mut Session, p: &Value) -> Result { Ok(json!({"colors": colors.iter().map(key_str).collect::>(), "objects": theme.objects})) } -/// A colour the art uses: how often, and the global swatch it is linked to. +/// A color the art uses: how often, and the global swatch of its first linked use in paint order. struct Used { color: Color, count: usize, swatch: Option, + /// The global swatch of the first linked use that is not a gradient stop mixing the swatch's + /// ink with process inks, with the tint (0..1) its paint stores when the paint gives one. + plain: Option<(String, Option)>, } /// The unique colours of the objects `ids` and the objects inside them, most used first (ties by -/// key): fills, strokes, gradient stops, text, mesh points and the tiles of the patterns used as -/// fills or strokes. With `only`, an object not in it is left out with everything it holds. +/// key): fills, strokes, gradient stops, text, mesh points, the tiles of the patterns used as +/// fills or strokes, and the tiles of the patterns those tiles use. With `only`, an object not in it is left out with everything it holds. fn used_colors(d: &Document, ids: &[NodeId], only: Option<&BTreeSet>) -> Vec { fn read<'a>(n: &'a Node, only: Option<&BTreeSet>, out: &mut Vec<&'a Node>) { if only.is_some_and(|o| !o.contains(&n.id)) { @@ -967,44 +986,64 @@ fn used_colors(d: &Document, ids: &[NodeId], only: Option<&BTreeSet>) -> } let mut index: HashMap = HashMap::new(); let mut used: Vec<(ColorKey, Used)> = vec![]; - let mut count = |c: &Color, link: Option<&str>| { + let mut count_tint = |c: &Color, link: Option<&str>, tint: Option, mixed: bool| { let k = ColorKey::of(c); let i = *index.entry(k).or_insert_with(|| { - used.push((k, Used { color: *c, count: 0, swatch: None })); + used.push((k, Used { color: *c, count: 0, swatch: None, plain: None })); used.len() - 1 }); let u = &mut used[i].1; u.count += 1; - if u.swatch.is_none() { - u.swatch = link.filter(|l| d.swatch(l).is_some_and(|w| w.global && w.paint.color().is_some())).map(str::to_string); + if u.swatch.is_some() && (u.plain.is_some() || mixed) { + return; + } + if let Some(l) = link.filter(|l| d.swatch(l).is_some_and(|w| w.global && w.paint.color().is_some())) { + if u.swatch.is_none() { + u.swatch = Some(l.to_string()); + } + if u.plain.is_none() && !mixed { + u.plain = Some((l.to_string(), tint)); + } } }; - // The patterns used as fills or strokes: their tiles count once each. + // The patterns used as fills or strokes, and the patterns their tiles use: each tile counts + // once, and a pattern whose tile uses itself, directly or through other patterns, counts once. let mut patterns: Vec<&str> = vec![]; let mut nodes = vec![]; for n in ids.iter().filter_map(|id| d.node(*id)) { read(n, only, &mut nodes); } for m in nodes { - for p in node_paints(m).chain(override_paints(m)) { - match p { - Paint::Solid { color, swatch, .. } => count(color, swatch.as_deref()), - Paint::Gradient(g) => g.gradient.stops.iter().for_each(|s| count(&s.color, s.swatch.as_deref())), - Paint::Pattern { pattern, .. } if !patterns.contains(&pattern.as_str()) => patterns.push(pattern), - _ => {} - } - } - if let NodeKind::Mesh(mesh) = &m.kind { - mesh.points.iter().for_each(|p| count(&p.color, None)); - } + paints(m, &mut count_tint, &mut patterns); } - for def in patterns.iter().filter_map(|p| d.pattern(p)) { - def.art.iter().for_each(|n| node_colors(n, &mut count)); + let mut next = 0; + while let Some(&name) = patterns.get(next) { + next += 1; + for a in d.pattern(name).map(|def| def.art.as_slice()).unwrap_or_default() { + a.walk(&mut |m| paints(m, &mut count_tint, &mut patterns)); + } } used.sort_by(|a, b| b.1.count.cmp(&a.1.count).then(a.0.cmp(&b.0))); used.into_iter().map(|(_, u)| u).collect() } +/// Count the colors `m` holds itself with `count` (the color, its swatch, the tint the paint +/// stores, and whether it is a gradient stop that mixes the swatch's ink with process inks), and +/// add the patterns it is painted with to `patterns`. +fn paints<'a>(m: &'a Node, count: &mut impl FnMut(&Color, Option<&str>, Option, bool), patterns: &mut Vec<&'a str>) { + for p in node_paints(m).chain(override_paints(m)) { + match p { + Paint::Solid { color, swatch, tint } => count(color, swatch.as_deref(), Some(*tint), false), + Paint::Gradient(g) => g.gradient.stops.iter().for_each(|s| count(&s.color, s.swatch.as_deref(), Some(s.tint), s.plates.is_some())), + Paint::Pattern { pattern, .. } if !patterns.contains(&pattern.as_str()) => patterns.push(pattern), + _ => {} + } + } + if let NodeKind::Mesh(mesh) = &m.kind { + mesh.points.iter().for_each(|p| count(&p.color, None, None, false)); + } +} + /// The colors `n` shows, in paint order ([`node_colors`]), then the colors of the tiles of the /// patterns it uses as fills or strokes, and of the patterns those tiles use (each pattern once). fn shown_colors<'a>(d: &'a Document, n: &'a Node) -> Vec { @@ -1047,30 +1086,61 @@ fn scope_ids(s: &Session, p: &Value, cmd: &str) -> Result<(Vec, Option checked_ids_param(s, p, "ids", cmd)?, - None if st.selection.is_empty() => { - let only = super::select::selectable_ids(&st.doc, st.isolation); - return Ok((super::select::selectable(&st.doc, st.isolation), Some(only))); - } + None if st.selection.is_empty() => return Ok(all_art(st)), None => st.selection.objects.clone(), }; let mut seen = BTreeSet::new(); Ok((super::edit::outermost(&st.doc, ids).into_iter().filter(|id| seen.insert(*id)).collect(), None)) } -fn colors(s: &mut Session, p: &Value) -> Result { - let (ids, only) = scope_ids(s, p, "recolor.colors")?; - let st = s.doc()?; - let v: Vec = used_colors(&st.doc, &ids, only.as_ref()) - .iter() +/// The objects Select All takes, and the objects whose colors count ([`scope_ids`] with nothing +/// selected). +fn all_art(st: &crate::DocState) -> (Vec, Option>) { + let only = super::select::selectable_ids(&st.doc, st.isolation); + (super::select::selectable(&st.doc, st.isolation), Some(only)) +} + +/// The `colors` list of `recolor.colors` and `color.used` for the objects `ids` (see +/// [`used_colors`]). Each names the swatch of its first linked use. With `with_color`, each has its +/// color in its own model, and the swatch and tint come from its first linked use that is not a +/// gradient stop mixing the swatch's ink with process inks (none when every linked use is one). +fn colors_json(used: &[Used], with_color: bool) -> Vec { + used.iter() .map(|u| { let mut v = json!({"key": key_str(&u.color), "hex": u.color.to_hex(), "count": u.count}); - if let Some(w) = &u.swatch { + if with_color { + v["color"] = json!(u.color); + if let Some((w, tint)) = &u.plain { + v["swatch"] = json!(w); + if let Some(t) = tint { + v["tint"] = json!((f64::from(*t) * 100_000.0).round() / 1000.0); + } + } + } else if let Some(w) = &u.swatch { v["swatch"] = json!(w); } v }) - .collect(); - Ok(json!({ "colors": v })) + .collect() +} + +fn colors(s: &mut Session, p: &Value) -> Result { + let (ids, only) = scope_ids(s, p, "recolor.colors")?; + let st = s.doc()?; + Ok(json!({ "colors": colors_json(&used_colors(&st.doc, &ids, only.as_ref()), false) })) +} + +/// `color.used {selection?, limit?}`: the colors of the selection, or of the art Select All takes. +fn used(s: &mut Session, p: &Value) -> Result { + const C: &str = "color.used"; + let limit = super::index_opt(p, "limit", C)?.unwrap_or(usize::MAX); + let selection = switch_or(p, "selection", true, C)? && !s.doc()?.selection.is_empty(); + let (ids, only) = if selection { scope_ids(s, &json!({}), C)? } else { all_art(s.doc()?) }; + let st = s.doc()?; + let used = used_colors(&st.doc, &ids, only.as_ref()); + let uses: usize = used.iter().map(|u| u.count).sum(); + let shown = used.get(..limit.min(used.len())).unwrap_or_default(); + Ok(json!({ "colors": colors_json(shown, true), "selection": selection, "uses": uses })) } /// `recolor.weigh`'s rows as given, each with `from` as a list (a `{current: new}` map gives a @@ -2051,7 +2121,14 @@ mod tests { bp.line_to((size, size)); bp.line_to((0.0, size)); bp.close_path(); - ImageRead { blob, xf: Affine::IDENTITY, size: (size, size), area: None, clip: Some(vec![(bp, FillRule::NonZero)]), colorize: None } + ImageRead { + blob, + map: vectorcraft_geom::Homography::from_affine(Affine::IDENTITY), + size: (size, size), + area: None, + clip: Some(vec![(bp, FillRule::NonZero)]), + colorize: None, + } } /// The reads of one image inside clip groups share the work limit: three reads of a 64 px diff --git a/crates/engine/src/cmd/retype.rs b/crates/engine/src/cmd/retype.rs index cb548bd46e..0e31d5632a 100644 --- a/crates/engine/src/cmd/retype.rs +++ b/crates/engine/src/cmd/retype.rs @@ -10,9 +10,11 @@ //! path, inside groups too) is compared with the glyphs of the candidate fonts //! ([`vectorcraft_text::retype`]), the same up to uniform scale, rotation and translation. Matched //! glyphs map back to characters through the font's cmap and are rebuilt as point text, one object -//! per line of glyphs, with the first glyph's fill and stroke. Shapes that match no font stay as -//! they are and are reported. Near matches (another version of the font, simplified outlines, -//! merged glyphs) and images are phase 2. +//! per line of glyphs, with the first glyph's fill and stroke. A line whose glyphs are evenly spaced +//! apart takes that spacing as its tracking ([`Line::tracked`]), and lines stacked at one leading +//! and lined up at their starts, ends or centers become one area type object ([`blocks`]). Shapes +//! that match no font stay as they are and are reported. Near matches (another version of the +//! font, simplified outlines, merged glyphs) and images are phase 2. use std::f64::consts::{PI, TAU}; use std::sync::Arc; @@ -39,7 +41,7 @@ pub fn specs() -> Vec { "Retype", ["Type"], None, - "{fonts?: [family…]} turn the selected outlined text (glyph paths and compound paths, inside groups too) back into live point text: each shape is matched against the glyphs of the fonts the app has loaded, the document's fonts and the families in fonts, the same up to uniform scale, rotation and translation (exact matches only); matched glyphs become point text in that font and size at the same baseline, one object per line, with the first glyph's fill, stroke, opacity and blend mode, in one undo step; a line splits where its type would not draw the outlines' glyphs in their places (tracking, manual spacing, font substitutions); shapes that match no font, glyphs type cannot draw as they are, and shapes with their own opacity mask stay as they are → {ids (the new type), texts, fonts: [{family, style, size}], unmatched: [id…], truncated (shapes past the limits of 2048 shapes or 16 nested groups were left out)}; an error when no shape matches", + "{fonts?: [family…]} turn the selected outlined text (glyph paths and compound paths, inside groups too) back into live type: each shape is matched against the glyphs of the fonts the app has loaded, the document's fonts and the families in fonts, the same up to uniform scale, rotation and translation (exact matches only); matched glyphs become point text in that font and size at the same baseline, one object per line unless lines stack into one (below), with the first glyph's fill, stroke, opacity and blend mode, in one undo step; a line of three or more glyphs takes the spacing most of its gaps share as its tracking (pair kerning left out) when tracked type draws all of it in place, or more of it than untracked type (when untracked type also draws it, untracked type is kept if the tracking is under one unit or the tracked type would drop a gap one space wide (a b c keeps its spaces), and the tracked type otherwise), and negative tracking only when the line is opaque, Normal, with a solid fill or none and no stroke (its glyphs may overlap); lines that follow each other in paint order with the same group, paint, font, size, turn and tracking (an untracked line of one or two glyphs takes the others' tracking), each one the same leading (0.25 to 3 times the size) below the one before, and lined up at their starts, ends or centers become one area type object with that leading (Auto when Auto gives it) and left, right or center alignment, or one multi-line point type object when area type (after Text Wrap) would not draw the outlines' glyphs in their places or when checking the Text Wrap objects on the changed layers would copy more than 2,000,000 anchors, subpaths and shapes; where even that type would move a glyph, the lines before that glyph's line stay one object and the rest are joined again from that line; lines with an opacity below 100%, a blend mode other than Normal, a gradient or pattern fill or a stroke stay one object each; a line splits where its type would not draw the outlines' glyphs in their places (uneven spacing, manual kerning, font substitutions); shapes that match no font, glyphs type cannot draw as they are, and shapes with their own opacity mask stay as they are → {ids (the new type), texts (lines joined by \\n), fonts: [{family, style, size, tracking (1/1000 em), leading (pt, null for Auto or one line), area (bool)}], unmatched: [id…], truncated (shapes past the limits of 2048 shapes or 16 nested groups were left out)}; an error when no shape matches", has_selected_path, retype )] @@ -163,8 +165,11 @@ fn candidate_faces(db: &FontDb, d: &Document, fonts: &[String]) -> Vec, + /// Tracking in 1/1000 em, added after each character, spaces included. + tracking: f64, /// What each piece matched, as `pieces`. matches: Vec, /// Every glyph the first piece fits, while the line holds only it: the next glyph may tell @@ -204,16 +209,53 @@ impl Line { // Wrapped: type turned 180° has angles near +π and −π. && ((m.angle - self.angle + PI).rem_euclid(TAU) - PI).abs() < 1e-5 && across < size * 0.05 - && (m.origin - self.end).dot(dir) > -size * 0.25 + // After the line's end, or, for type tracked tighter than that, still ahead of the + // last glyph's start (by more than rounding); the layout check decides whether it fits. + && ((m.origin - self.end).dot(dir) > -size * 0.25 + || self.matches.last().is_some_and(|last| (m.origin - last.origin).dot(dir) > size * 1e-3)) + } + + fn size(&self) -> f64 { + self.scale * self.face.units_per_em() + } + + /// The shapes of the one-contour glyphs that stand alone on this line: neither the glyph before + /// nor the one after continues it by starting after the end of the glyph before it. A glyph + /// that joined the line only through the tight-tracking test counts as alone. A line of three + /// glyphs or more is type (its tracking can be read), so none of its glyphs is alone. + fn lone_one_contour(&self) -> Vec { + if self.matches.len() >= 3 { + return vec![]; + } + let dir = self.dir(); + let size = self.size(); + // Does glyph `k` start after the end of the glyph before it, less a quarter em? + let after_previous = |k: usize| match (k.checked_sub(1).and_then(|j| self.matches.get(j)), self.matches.get(k)) { + (Some(a), Some(b)) => (b.origin - (a.origin + dir * (a.face.advance(a.gid) * a.scale))).dot(dir) > -size * 0.25, + _ => false, + }; + let n = self.matches.len(); + (0..n) + .filter(|&k| !after_previous(k) && !after_previous(k + 1)) + .filter_map(|k| self.matches.get(k).filter(|m| m.contours == 1).and_then(|_| self.pieces.get(k).copied())) + .collect() + } + + /// The line's tracking in points. + fn tracking_pt(&self) -> f64 { + self.tracking * self.size() / 1000.0 } fn push(&mut self, id: NodeId, m: &GlyphMatch) { - // A gap wider than half a space before the glyph is spaces the outlines left no shape for. + // A gap, past the tracking, wider than half a space before the glyph is spaces the + // outlines left no shape for. Each space takes the tracking too. let dir = self.dir(); - let gap = (m.origin - self.end).dot(dir); - let space = space_advance(&self.face) * self.scale; - if space > 0.0 && gap > space * 0.5 { - let n = ((gap / space).round() as usize).clamp(1, 64); + let gap = (m.origin - self.end).dot(dir) - self.tracking_pt(); + // Tracking tighter than a space's width gives each space a negative advance. + let space = space_advance(&self.face) * self.scale + self.tracking_pt(); + let spaces = if space.abs() > 1e-9 { gap / space } else { 0.0 }; + if spaces.is_finite() && spaces > 0.5 { + let n = (spaces.round() as usize).clamp(1, 64); self.text.extend(std::iter::repeat_n(' ', n)); } self.text.push(m.ch); @@ -222,13 +264,49 @@ impl Line { self.end = m.origin + dir * (m.face.advance(m.gid) * m.scale); } - /// The line of this one's glyphs `from..to`, with its group, paint and transparency. + /// The line of this one's glyphs `from..to`, with its group, paint, transparency, tracking and + /// the spaces between those glyphs. fn part(&self, from: usize, to: usize) -> Option { + let mut text = String::new(); + let mut glyph = 0usize; + for c in self.text.chars() { + // The text after glyph `to - 1` is not read. + if glyph >= to { + break; + } + if c == ' ' { + // Spaces before glyph `glyph`, after glyph `glyph - 1`. + if glyph > from { + text.push(c); + } + continue; + } + if glyph >= from { + text.push(c); + } + glyph += 1; + } + if glyph != to || to > self.matches.len() { + return self.respaced(from, to, self.tracking); + } + let mut l = self.respaced(from, to.min(from.saturating_add(1)), self.tracking)?; + l.pieces = self.pieces.get(from..to)?.to_vec(); + l.matches = self.matches.get(from..to)?.to_vec(); + let last = l.matches.last()?; + l.end = last.origin + l.dir() * (last.face.advance(last.gid) * last.scale); + l.text = text; + Some(l) + } + + /// The line of this one's glyphs `from..to` at `tracking`, with its group, paint and + /// transparency, its spaces read again from the gaps at that tracking. + fn respaced(&self, from: usize, to: usize, tracking: f64) -> Option { let (ids, ms) = (self.pieces.get(from..to)?, self.matches.get(from..to)?); let (first, m) = (ids.first()?, ms.first()?); let dir = Vec2::new(m.angle.cos(), m.angle.sin()); let mut l = Line { pieces: vec![*first], + tracking, matches: vec![m.clone()], first_cands: vec![], text: m.ch.to_string(), @@ -248,8 +326,8 @@ impl Line { Some(l) } - /// The point type that sets this line. - fn text_object(&self, system_layout: bool) -> TextObject { + /// The point type that sets this line, not yet laid out (for a layout check). + fn probe(&self, system_layout: bool) -> TextObject { let style = CharStyle { font_family: self.face.family.clone(), font_style: self.face.style.clone(), @@ -258,6 +336,7 @@ impl Line { // Each outlined glyph was drawn on its own; a ligature would draw another shape. features: vec!["-liga".into()], size: self.scale * self.face.units_per_em(), + tracking: self.tracking, fill: self.appearance.fill_paint(), stroke: self.appearance.stroke_paint(), stroke_width: self.appearance.stroke_width(), @@ -277,6 +356,12 @@ impl Line { } t.para = super::create::new_type_para(); t.system_layout = system_layout; + t + } + + /// The point type that sets this line, laid out and measured. + fn text_object(&self, system_layout: bool) -> TextObject { + let mut t = self.probe(system_layout); super::typecmd::refresh_bounds(&mut t); t } @@ -285,27 +370,262 @@ impl Line { /// (a substitution the font makes) or the same glyph elsewhere (tracking, manual spacing, /// more space than whole spaces make); `None` when the type draws every glyph in its place. fn first_mismatch(&self, t: &TextObject) -> Option { - let lay = vectorcraft_text::layout(FontDb::global(), t); - let mut drawn = lay.glyphs.iter().filter(|g| !g.outline.elements().is_empty()); - let tol = (self.scale * self.face.units_per_em() * 0.01).max(0.01); - for (k, m) in self.matches.iter().enumerate() { - let Some(g) = drawn.next() else { return Some(k) }; - let at = t.xf * (g.xf * Point::ORIGIN); - if g.font_id != m.face.id() || g.gid != m.gid || at.distance(m.origin) > tol { - return Some(k); + first_mismatch(t, &self.matches, self.size()) + } + + /// Along the line, where its first glyph starts and its last glyph's advance ends, from + /// `from` (the tracking after the last glyph left out). + fn span_from(&self, from: Point) -> (f64, f64) { + let dir = self.dir(); + let last = self.matches.last().map_or(self.end, |m| m.origin + dir * (m.face.advance(m.gid) * m.scale)); + ((self.origin - from).dot(dir), (last - from).dot(dir)) + } + + /// This line with the tracking its glyphs are spaced by, when it has at least three glyphs. + /// The glyphs are laid out untracked and without spaces, so each gap's extra is how much + /// further apart the outlines are than the font's advances and pair kerning set them; a gap + /// read as word spaces is measured from the glyph's own advance instead, as no pair kerning + /// crosses a space. The extra most gaps share (the lower median, so that the word spaces of a + /// few gaps do not count) places the word spaces; the tracking is then the lower median, over + /// the gaps, of each gap's extra less its spaces, per character. The upper median of the + /// extras is tried next, for a line whose word spaces are its tighter gaps, and last the lower + /// median less one space, halved, for a line most of whose gaps hold a word space. A tracking within + /// 0.05 of a whole number is tried rounded to it first, then as measured. A tracked line is + /// kept when its type draws the whole line in place, or more of it from its start than + /// untracked type does. When untracked type with the spaces also draws the whole line, the line stays + /// untracked if the tracking is under one unit or the tracked reading drops a gap untracked + /// type reads as one space. The line also stays as it is when its tracking is 0 or outside + /// -1000..10000, and when its tracking is negative and the line does not paint the same as one + /// object ([`paints_as_one`]: its glyphs may overlap). Each of the nine layouts at most takes + /// its characters, spaces included, from `budget` before it runs; without enough left, the + /// line stays as it is, or becomes the best tracked reading laid out before the budget ran out. + fn tracked(self, system_layout: bool, budget: &mut usize) -> Line { + let size = self.size(); + let n = self.pieces.len(); + if n < 3 || size <= 0.0 { + return self; + } + // Each layout takes its characters, spaces included, from `budget` before it runs. + let mut take = |text: &str| match budget.checked_sub(text.chars().count()) { + Some(left) => { + *budget = left; + true + } + None => false, + }; + if !take(&self.text) { + return self; + } + let plain_miss = self.first_mismatch(&self.probe(system_layout)); + let dir = self.dir(); + // Where untracked type draws the glyphs of `text` (each layout dropped once read). + let mut bare = self.clone(); + bare.tracking = 0.0; + let mut origins = |text: String| -> Vec { + bare.text = text; + let t = bare.probe(system_layout); + let lay = vectorcraft_text::layout(FontDb::global(), &t); + lay.glyphs.iter().filter(|g| !g.outline.elements().is_empty()).map(|g| t.xf * (g.xf * Point::ORIGIN)).collect() + }; + // With no spaces. + let joined: String = self.matches.iter().map(|m| m.ch).collect(); + if !take(&joined) { + return self; + } + let drawn = origins(joined); + if drawn.len() != n { + return self; + } + // And with one space between each two glyphs (kerning against the space included). + let spaced = self.matches.iter().map(|m| m.ch.to_string()).collect::>().join(" "); + if !take(&spaced) { + return self; + } + let drawn_spaced = origins(spaced); + // A font whose space has ink draws more glyphs: then the glyph's own advance stands in. + let spaced_ok = drawn_spaced.len() == n; + let space = space_advance(&self.face) * self.scale; + // Each gap's extra over the joined pair, and over the pair with one space between them + // plus a space (so the extra counts the spaces as the joined pair's extra counts none). + let gaps: Vec<(f64, f64)> = self + .matches + .windows(2) + .enumerate() + .zip(drawn.windows(2)) + .filter_map(|((i, m), p)| match (m, p) { + ([a, b], [pa, pb]) => { + let d = (b.origin - a.origin).dot(dir); + let apart = match (spaced_ok, drawn_spaced.get(i), drawn_spaced.get(i + 1)) { + (true, Some(qa), Some(qb)) => d - (*qb - *qa).dot(dir) + space, + _ => d - a.face.advance(a.gid) * a.scale, + }; + Some((d - (*pb - *pa).dot(dir), apart)) + } + _ => None, + }) + .collect(); + let extra: Vec = gaps.iter().map(|g| g.0).collect(); + // The spaces in each gap at a tracking of `tr` points: each space takes the tracking too, + // and tracking tighter than a space's width gives it a negative advance. A gap reads as + // spaces when they fit it better than the joined pair does. + let spaces = |tr: f64| -> Vec { + gaps.iter() + .map(|(joined, apart)| { + let step = space + tr; + // Spaces with no advance: one space, which still breaks the pair's kerning. + let s = if step.abs() > 1e-9 { (apart - tr) / step } else { 1.0 }; + if !s.is_finite() { + return 0; + } + // At least one space: the space's own kerning can make it fit a narrower gap. + let k = (s.round().max(1.0) as usize).clamp(1, 64); + // Spaces only where they fit better by more than rounding (1/100,000 em). + if (apart - tr - k as f64 * step).abs() + size * 1e-5 < (joined - tr).abs() { k } else { 0 } + }) + .collect() + }; + // The tracking the gaps give when the word spaces are placed by `seed`. + let measure = |seed: f64| -> Option { + let per: Vec = gaps + .iter() + .zip(spaces(seed)) + .map(|((joined, apart), s)| if s == 0 { *joined } else { (apart - s as f64 * space) / (s + 1) as f64 }) + .collect(); + median(per, false).map(|g| g / size * 1000.0) + }; + // The lower median of the extras places the word spaces first; the upper one second, for a + // line whose word spaces are its tighter gaps (tracking tighter than a space). + let lower = median(extra.clone(), false); + // A line whose word gaps are most of its gaps has a space and two trackings in each extra + // (tracking is added after the glyph and after the space): the seed then places the spaces + // from the extra less one space, shared by the two. It goes last, so a reading that fits + // without it is kept (an untracked "a b c" has no such tracking). + // Where untracked type already draws the whole line, a space and a tracking of half its + // advance less draw it too: that reading is not tried. + let spaced_seed = lower.filter(|_| plain_miss.is_some()).map(|e| (e - space) / 2.0); + let mut tries = vec![]; + for seed in [lower, median(extra, true), spaced_seed].into_iter().flatten() { + let Some(measured) = measure(seed) else { continue }; + for t in [round_tracking(measured), measured] { + if !tries.contains(&t) { + tries.push(t); + } } } - // Ink the outlines did not have: the last glyph is where it went wrong. - drawn.next().map(|_| self.matches.len().saturating_sub(1)) + // The spaces in each gap of the line as it is (the reading `plain_miss` checked). + let mut plain_gaps = vec![]; + let mut run = 0usize; + for (i, c) in self.text.chars().enumerate() { + if c == ' ' { + run += 1; + } else { + if i > 0 { + plain_gaps.push(run); + } + run = 0; + } + } + let mut best: Option<(usize, Line)> = None; + for t in tries { + if t == 0.0 || !TRACKING.contains(&t) { + continue; + } + if t < 0.0 && !paints_as_one(&self) { + return self; + } + let mut tracked = self.clone(); + tracked.tracking = t; + tracked.text = String::new(); + let gaps = spaces(t * size / 1000.0); + for (k, (m, s)) in self.matches.iter().zip(std::iter::once(0).chain(gaps.iter().copied())).enumerate() { + if k > 0 { + tracked.text.extend(std::iter::repeat_n(' ', s)); + } + tracked.text.push(m.ch); + } + // A reading the budget cannot lay out is skipped; the next may be shorter. + if !take(&tracked.text) { + continue; + } + // When both draw the whole line (gaps as wide as whole spaces), the tracked reading is + // kept unless it drops a gap that untracked type reads as one space: such a gap is a + // word space ("a b c"), and the line keeps its spaces. + let drops_a_word_space = plain_gaps.iter().zip(&gaps).any(|(plain, tracked)| *plain == 1 && *tracked == 0); + match (tracked.first_mismatch(&tracked.probe(system_layout)), plain_miss) { + // Under a unit of tracking, or a word space the tracked reading drops, where + // untracked type draws the line: no tracking. + (None, None) if t.abs() < 1.0 || drops_a_word_space => return self, + (None, _) => return tracked, + (Some(k), Some(p)) if k > p && best.as_ref().is_none_or(|(b, _)| k > *b) => best = Some((k, tracked)), + _ => {} + } + } + best.map_or(self, |(_, l)| l) } } +/// Does line `l` paint the same as one object as glyph by glyph where its glyphs overlap: opaque, +/// Normal blend, a solid fill or none, and no stroke? One object composites its transparency and +/// blend once, spans a gradient over all of it, and strokes after filling every glyph. +fn paints_as_one(l: &Line) -> bool { + l.opacity == 1.0 + && l.blend == vectorcraft_color::BlendMode::Normal + && matches!(l.appearance.fill_paint(), vectorcraft_color::Paint::None | vectorcraft_color::Paint::Solid { .. }) + && matches!(l.appearance.stroke_paint(), vectorcraft_color::Paint::None) +} + +/// The tracking Retype sets, in 1/1000 em. +const TRACKING: std::ops::RangeInclusive = -1000.0..=10000.0; + +/// The lower median of the finite values of `v`, or the upper one when `upper`; None for fewer +/// than two. +fn median(mut v: Vec, upper: bool) -> Option { + v.retain(|x| x.is_finite()); + if v.len() < 2 { + return None; + } + v.sort_by(f64::total_cmp); + v.get(if upper { v.len() / 2 } else { (v.len() - 1) / 2 }).copied() +} + +/// Tracking `t` rounded to a whole number when it is within 0.05 of one. +fn round_tracking(t: f64) -> f64 { + if (t - t.round()).abs() < 0.05 { t.round() } else { t } +} + +/// The first of `matches` that type `t` (at `size`) does not draw as the outlines did: another +/// glyph (a substitution the font makes) or the same glyph elsewhere (tracking, manual spacing, +/// more space than whole spaces make); `None` when the type draws every glyph in its place. +fn first_mismatch(t: &TextObject, matches: &[GlyphMatch], size: f64) -> Option { + let lay = vectorcraft_text::layout(FontDb::global(), t); + let mut drawn = lay.glyphs.iter().filter(|g| !g.outline.elements().is_empty()); + let tol = (size * 0.01).max(0.01); + for (k, m) in matches.iter().enumerate() { + let Some(g) = drawn.next() else { return Some(k) }; + let at = t.xf * (g.xf * Point::ORIGIN); + if g.font_id != m.face.id() || g.gid != m.gid || at.distance(m.origin) > tol { + return Some(k); + } + } + // Ink the outlines did not have: the last glyph is where it went wrong. + drawn.next().map(|_| matches.len().saturating_sub(1)) +} + /// `lines` checked against their own layout: a line splits where its type stops drawing the /// outlines, and a glyph its type cannot draw even on its own stays an outline (`unmatched`). /// The glyphs laid out are bounded by a multiple of the number of glyphs. fn verified(lines: Vec, system_layout: bool, unmatched: &mut Vec) -> Vec { // Glyphs laid out in all, at most: past it, the glyphs left unchecked stay outlines. let mut budget = lines.iter().map(|l| l.pieces.len()).sum::().saturating_mul(16).saturating_add(256); + // Measuring the tracking of the glyphs after a split has a budget of its own, so it cannot + // leave glyphs unchecked; past it they keep no tracking. Each measure takes the glyphs to + // rebuild the rest and the characters it lays out (see [`Line::tracked`]); the budget covers + // one measure of each whole line, as `retype` gives the first, and the glyph checks' budget. + // The glyphs measured again after splits are limited apart from it, at six times each rest's + // glyphs from half as much again as the glyph checks' budget. + let mut remeasured = budget.saturating_add(budget / 2); + let mut track_budget = + lines.iter().map(|l| l.text.chars().count().saturating_add(l.pieces.len().saturating_mul(394))).fold(budget, usize::saturating_add); let mut todo: std::collections::VecDeque = lines.into(); let mut out = vec![]; while let Some(l) = todo.pop_front() { @@ -323,28 +643,58 @@ fn verified(lines: Vec, system_layout: bool, unmatched: &mut Vec) break; }; budget = left; - match part.first_mismatch(&part.text_object(system_layout)) { + match part.first_mismatch(&part.probe(system_layout)) { // The whole line is drawn as it was: one object. None if e == n => { out.push(part); break; } None => w = w.saturating_mul(2), - // The first glyph on its own may still be drawn as it was (a contextual form - // changed it in the line); else it stays an outline. Checked again either way. - Some(0) if n > 1 => { - todo.extend_front_parts(&l, [(0, 1), (1, n)]); + // Tracking that type does not set as the outlines are spaced: the line is + // checked again without it. + Some(k) if l.tracking != 0.0 && k < 2 => { + match l.respaced(0, n, 0.0) { + Some(p) => todo.push_front(p), + None => unmatched.extend(l.pieces.iter().copied()), + } break; } - Some(0) => { + // A single glyph its type cannot draw as it was stays an outline. + Some(0) if n == 1 => { unmatched.extend(l.pieces.first().copied()); break; } // The glyphs before the mismatch, then the rest, each checked as a line of its // own: the type before the mismatch may draw otherwise without what follows it (a - // font can place a glyph by the glyph after it). + // font can place a glyph by the glyph after it), and the first glyph on its own + // may still be drawn as it was (a contextual form changed it in the line). The + // rest takes the tracking its own glyphs are spaced by, while the budget for + // measuring it lasts and when type draws its first glyph as it was, followed by the + // next two (else that glyph splits off first, and the tracking is measured from the + // next one); past it, an untracked line's rest keeps its text as it is. Some(k) => { - todo.extend_front_parts(&l, [(0, k), (k, n)]); + let k = k.max(1); + // A measure takes at least six times the rest's glyphs from each budget. + let measurable = n - k >= 3 && remeasured >= (n - k).saturating_mul(6) && track_budget >= (n - k).saturating_mul(6); + let first_drawn = measurable && { + budget = budget.saturating_sub(3); + l.respaced(k, k + 3, l.tracking).is_some_and(|p| p.first_mismatch(&p.probe(system_layout)) != Some(0)) + }; + let rest = if first_drawn { + // Rebuilding the rest for the measure takes its glyphs from the budget. + remeasured = remeasured.saturating_sub((n - k).saturating_mul(6)); + track_budget = track_budget.saturating_sub(n - k); + l.respaced(k, n, 0.0).map(|r| r.tracked(system_layout, &mut track_budget)) + } else if l.tracking == 0.0 { + l.part(k, n) + } else { + l.respaced(k, n, 0.0) + }; + match rest { + Some(r) => todo.push_front(r), + None => unmatched.extend(l.pieces.get(k..).unwrap_or_default().iter().copied()), + } + todo.extend_front_parts(&l, [(0, k)]); break; } } @@ -353,6 +703,290 @@ fn verified(lines: Vec, system_layout: bool, unmatched: &mut Vec) out } +/// Most units (anchors, subpaths and shapes) that Text Wrap objects may copy into the wrap shapes +/// of the area type on the layers Retype changes +/// ([`vectorcraft_doc::text::wrap_copy_units`]) when Retype checks how they flow new area type. +const MAX_WRAP_WORK: usize = 2_000_000; + +#[cfg(not(test))] +fn max_wrap_work() -> usize { + MAX_WRAP_WORK +} + +#[cfg(test)] +thread_local! { + /// [`MAX_WRAP_WORK`], lowered by tests on their own thread. + static WRAP_LIMIT: std::cell::Cell = const { std::cell::Cell::new(MAX_WRAP_WORK) }; +} + +#[cfg(test)] +fn max_wrap_work() -> usize { + WRAP_LIMIT.with(|c| c.get()) +} + +/// Lines farther apart than this many times their size do not join into one object. +const MAX_LEADING: f64 = 3.0; + +/// What Retype makes: one type object and the shapes it replaces. +struct Made { + t: TextObject, + /// For area type, the point type that also draws the glyphs in place: the type kept when + /// Text Wrap objects above it change the area type's layout. + point: Option, + /// The glyphs the type must draw, in order. + matches: Vec, + pieces: Vec, + text: String, + face: Arc, + size: f64, + tracking: f64, + /// The leading set on the type: None for Auto or a single line. + leading: Option, + opacity: f32, + blend: vectorcraft_color::BlendMode, +} + +impl Made { + fn line(l: &Line, system_layout: bool) -> Made { + Made { + t: l.text_object(system_layout), + point: None, + matches: l.matches.clone(), + pieces: l.pieces.clone(), + text: l.text.clone(), + face: l.face.clone(), + size: l.size(), + tracking: l.tracking, + leading: None, + opacity: l.opacity, + blend: l.blend, + } + } +} + +/// The alignments lines can share, in the order one is chosen: their starts, their ends, their +/// centers. +const ALIGNS: [vectorcraft_doc::Justify; 3] = [vectorcraft_doc::Justify::Left, vectorcraft_doc::Justify::Right, vectorcraft_doc::Justify::Center]; + +/// A run of lines that may become one object: lines after the first, each one leading further +/// across, in the same group, paint, transparency, font, size, turn and tracking, lined up alike. +struct Block { + lines: Vec, + /// The mean distance between baselines, from the first line's to the last line's. + leading: f64, + /// Which of [`ALIGNS`] every line so far shares. + aligns: [bool; 3], + /// The tracking of the first line that has one ([`Block::spaced`]). + tracking: Option, +} + +impl Block { + fn new(l: Line) -> Block { + let tracking = Block::spaced(&l).then_some(l.tracking); + Block { lines: vec![l], leading: 0.0, aligns: [true; 3], tracking } + } + + /// Does line `l` have a tracking of its own? A line of fewer than three glyphs that kept no + /// tracking has no gaps to measure it by ([`Line::tracked`]): it takes the block's. + fn spaced(l: &Line) -> bool { + l.pieces.len() >= 3 || l.tracking != 0.0 + } + + /// Add `l` when it continues the block; `l` back when it does not. `follows` tells whether the + /// shape `l` starts with comes right after the block's last shape, with nothing between them + /// in paint order. + fn take(&mut self, l: Line, follows: impl Fn(NodeId, NodeId) -> bool) -> Option { + let (Some(first), Some(prev)) = (self.lines.first(), self.lines.last()) else { return Some(l) }; + let (Some(a), Some(b)) = (prev.pieces.last(), l.pieces.first()) else { return Some(l) }; + let size = first.size(); + let tol = (size * 0.01).max(0.01); + let same = follows(*a, *b) + && l.parent == first.parent + && l.appearance == first.appearance + && l.opacity == first.opacity + && l.blend == first.blend + && l.face.id() == first.face.id() + && (l.scale - first.scale).abs() <= first.scale * 1e-4 + && ((l.angle - first.angle + PI).rem_euclid(TAU) - PI).abs() < 1e-5 + // The lines' estimates may differ a little; the layout check decides. + && (!Block::spaced(&l) || self.tracking.is_none_or(|t| (l.tracking - t).abs() < 1.0)) + // Lines whose ink overlaps, or a gradient spanning them, would paint otherwise as one. + && paints_as_one(first); + if !same { + return Some(l); + } + // Across the lines, down from the first line's baseline. + let across = Vec2::new(-first.angle.sin(), first.angle.cos()); + let down = (l.origin - first.origin).dot(across); + let n = self.lines.len() as f64; + // The mean distance between the baselines so far, which this line's must continue. + let leading = if self.lines.len() == 1 { down } else { self.leading }; + // A quarter of the size is the least leading; the outlines' positions are rounded. + if !(leading >= size * 0.25 * (1.0 - 1e-6) && leading <= size * MAX_LEADING) || (down - n * leading).abs() > tol { + return Some(l); + } + let leading = down / n; + let (s0, e0) = first.span_from(first.origin); + let (s, e) = l.span_from(first.origin); + let fits = [(s - s0).abs() <= tol, (e - e0).abs() <= tol, ((s + e) - (s0 + e0)).abs() * 0.5 <= tol]; + let aligns = [self.aligns[0] && fits[0], self.aligns[1] && fits[1], self.aligns[2] && fits[2]]; + if !aligns.contains(&true) { + return Some(l); + } + self.leading = leading; + self.aligns = aligns; + if self.tracking.is_none() && Block::spaced(&l) { + self.tracking = Some(l.tracking); + } + self.lines.push(l); + None + } + + /// The block as one area type object when type draws every glyph in its place as area type, + /// else as one point type object when that does. When neither does, the lines before the line + /// of the first glyph the type moves are made again as a block, and the lines from that one on + /// are joined again ([`blocks`]); the first line on its own stays one object. Area type whose + /// frame would reach past [`crate::MAX_COORD`] stays point type, and point type whose bounds + /// would stays one object per line. Each try takes six times the + /// block's glyphs from `budget` (point and area type are each laid out, measured and checked); + /// without enough left, each line is one object. + fn made(self, system_layout: bool, budget: &mut usize) -> Vec { + let single = |lines: &[Line]| lines.iter().map(|l| Made::line(l, system_layout)).collect::>(); + let (Some(first), true) = (self.lines.first(), self.lines.len() > 1) else { return single(&self.lines) }; + let Some(justify) = ALIGNS.iter().zip(self.aligns).find(|(_, ok)| *ok).map(|(j, _)| *j) else { return single(&self.lines) }; + let glyphs = self.lines.iter().map(|l| l.pieces.len()).fold(0usize, usize::saturating_add); + let Some(left) = budget.checked_sub(glyphs.saturating_mul(6)) else { return single(&self.lines) }; + *budget = left; + let mut all = first.clone(); + all.tracking = self.tracking.unwrap_or(first.tracking); + all.text = self.lines.iter().map(|l| l.text.as_str()).collect::>().join("\n"); + let mut t = all.probe(system_layout); + t.para.justify = justify; + let size = first.size(); + let mut set_leading = None; + if let Some(r) = t.runs.first_mut() { + // The leading that puts the last baseline where the last line's is: Auto when Auto + // does, else the mean distance between baselines, to a thousandth of a point (as + // typed leading is) when that still puts the last baseline in place. + let gaps = self.lines.len().saturating_sub(1) as f64; + let across = Vec2::new(-first.angle.sin(), first.angle.cos()); + let span = self.lines.last().map_or(0.0, |l| (l.origin - first.origin).dot(across)); + if (t.para.effective_leading(&r.style) * gaps - span).abs() > size * 1e-4 { + let exact = span / gaps; + let rounded = (exact * 1000.0).round() / 1000.0; + let leading = if ((rounded - exact) * gaps).abs() <= size * 1e-4 { rounded } else { exact }; + r.style.leading = Some(leading); + set_leading = Some(leading); + } + } + let matches: Vec = self.lines.iter().flat_map(|l| l.matches.iter().cloned()).collect(); + // Aligned at its end or center, point type starts its first line elsewhere: the type moves + // so its first glyph is where the first outline is. + let lay = vectorcraft_text::layout(FontDb::global(), &t); + if let (Some(g), Some(m)) = (lay.glyphs.iter().find(|g| !g.outline.elements().is_empty()), matches.first()) { + let at = t.xf * (g.xf * Point::ORIGIN); + t.xf = kurbo::Affine::translate(m.origin - at) * t.xf; + } + super::typecmd::refresh_bounds(&mut t); + if let Some(k) = first_mismatch(&t, &matches, size) { + // The line that holds glyph `k`. + let mut seen = 0usize; + let at = self.lines.iter().position(|l| { + seen = seen.saturating_add(l.pieces.len()); + k < seen + }); + let Block { mut lines, leading, aligns, .. } = self; + let rest = lines.split_off(at.unwrap_or(0).clamp(1, lines.len())); + let mut out = if lines.len() > 1 { + let tracking = lines.iter().find(|l| Block::spaced(l)).map(|l| l.tracking); + Block { lines, leading, aligns, tracking }.made(system_layout, budget) + } else { + single(&lines) + }; + // The lines of the rest followed each other in the block. + out.extend(blocks(rest, |_, _| true, system_layout, budget)); + return out; + } + // The edit is refused when an object's bounds reach past the coordinate limit. A turned + // block's box can reach a corner that none of its lines does: the lines then stay apart. + let in_range = + |t: &TextObject| Node::new(NodeId(0), NodeKind::Text(Box::new(t.clone()))).geometric_bounds().is_none_or(crate::sanity::rect_in_range); + if !in_range(&t) { + return single(&self.lines); + } + let mut area = t.clone(); + super::typemenu::point_to_area(&mut area); + let mut point = None; + if in_range(&area) && first_mismatch(&area, &matches, size).is_none() { + point = Some(std::mem::replace(&mut t, area)); + } + vec![Made { + t, + point, + matches, + pieces: self.lines.iter().flat_map(|l| l.pieces.iter().copied()).collect(), + text: all.text, + face: first.face.clone(), + size, + tracking: all.tracking, + leading: set_leading, + opacity: first.opacity, + blend: first.blend, + }] + } +} + +/// A line of two untracked glyphs has one gap, too few to measure a tracking by +/// ([`Line::tracked`]). It is set at the tracking of the nearest tracked line of the same font, +/// size and turn, so the layout check ([`verified`]) tries it as that line is set: the check falls +/// back to the line untracked, and then splits it, when the pair is not spaced so. A pair that +/// untracked type already draws in place keeps its text, and negative tracking goes only to a pair +/// that paints the same as one object ([`paints_as_one`]). +fn share_tracking(lines: &mut [Line], system_layout: bool) { + for i in 0..lines.len() { + let Some(l) = lines.get(i).filter(|l| l.pieces.len() == 2 && l.tracking == 0.0) else { continue }; + if l.first_mismatch(&l.probe(system_layout)).is_none() { + continue; + } + let like = |o: &Line| { + o.tracking != 0.0 + && o.parent == l.parent + && o.face.id() == l.face.id() + && (o.scale - l.scale).abs() <= l.scale * 1e-4 + && ((o.angle - l.angle + PI).rem_euclid(TAU) - PI).abs() < 1e-5 + }; + let nearest = lines.iter().enumerate().filter(|(_, o)| like(o)).min_by_key(|(j, _)| j.abs_diff(i)).map(|(_, o)| o.tracking); + if let Some(p) = nearest.filter(|t| *t > 0.0 || paints_as_one(l)).and_then(|t| l.respaced(0, 2, t)) { + lines[i] = p; + } + } +} + +/// `lines`, in paint order, as the objects Retype makes: runs of lines that stack as the lines of +/// one paragraph do become one object ([`Block`]). `follows(a, b)`: shape `b` comes right after +/// shape `a`, with nothing between them in paint order. `budget`: see [`Block::made`]. +fn blocks(lines: Vec, follows: impl Fn(NodeId, NodeId) -> bool, system_layout: bool, budget: &mut usize) -> Vec { + let mut out = vec![]; + let mut block: Option = None; + for l in lines { + let l = match block.as_mut() { + Some(b) => match b.take(l, &follows) { + None => continue, + Some(l) => l, + }, + None => l, + }; + if let Some(b) = block.take() { + out.extend(b.made(system_layout, budget)); + } + block = Some(Block::new(l)); + } + if let Some(b) = block { + out.extend(b.made(system_layout, budget)); + } + out +} + /// Puts parts of a line at the front of the work list, in order. trait FrontParts { fn extend_front_parts(&mut self, l: &Line, ranges: [(usize, usize); N]); @@ -407,6 +1041,7 @@ fn reposed(l: &Line, id: NodeId, m: &GlyphMatch) -> Line { let dir = Vec2::new(m.angle.cos(), m.angle.sin()); Line { pieces: vec![id], + tracking: 0.0, matches: vec![m.clone()], first_cands: l.first_cands.clone(), text: m.ch.to_string(), @@ -428,6 +1063,7 @@ fn new_line(pc: &Piece, cands: &[GlyphMatch]) -> Option { let dir = Vec2::new(m.angle.cos(), m.angle.sin()); Some(Line { pieces: vec![pc.id], + tracking: 0.0, matches: vec![m.clone()], first_cands: cands.to_vec(), text: m.ch.to_string(), @@ -531,8 +1167,15 @@ fn retype(s: &mut Session, p: &Value) -> Result { // art (a dot, a bar): beside other shapes it stays an outline. Selected on its own, it is // what was asked for. Lone means alone on its baseline as the outlines lie, before the // layout check splits lines (tracking and manual kerning split them glyph by glyph). - let lone_pieces: std::collections::HashSet = - lines.iter().filter(|l| matches!(l.matches.as_slice(), [m] if m.contours == 1)).flat_map(|l| l.pieces.iter().copied()).collect(); + let lone_pieces: std::collections::HashSet = lines.iter().flat_map(Line::lone_one_contour).collect(); + // Each line's tracking is measured with nine layouts at most: the line as read (its + // characters), its glyphs without and with one space between them (three times its + // glyphs) and six tracked readings of at most 64 spaces in each gap (390 times its + // glyphs), so every line has what its measure can take. + let mut budget = + lines.iter().map(|l| l.text.chars().count().saturating_add(l.pieces.len().saturating_mul(393))).fold(256usize, usize::saturating_add); + let mut lines: Vec = lines.into_iter().map(|l| l.tracked(system_layout, &mut budget)).collect(); + share_tracking(&mut lines, system_layout); let mut lines = verified(lines, system_layout, &mut unmatched); if pieces.len() > 1 { lines.retain(|l| { @@ -543,20 +1186,29 @@ fn retype(s: &mut Session, p: &Value) -> Result { !lone }); } - (lines, unmatched, truncated) + let at: std::collections::HashMap = pieces.iter().enumerate().map(|(i, pc)| (pc.id, i)).collect(); + let follows = |a: NodeId, b: NodeId| match (at.get(&a), at.get(&b)) { + (Some(i), Some(j)) => *j == i + 1 && pieces.get(*j).is_some_and(|pc| !pc.after_barrier), + _ => false, + }; + // Joining lines takes at most four tries' work per glyph (see [`Block::made`]), with room + // for small blocks. + let mut budget = lines.iter().map(|l| l.pieces.len()).fold(0usize, usize::saturating_add).saturating_mul(24).saturating_add(256); + (blocks(lines, follows, system_layout, &mut budget), unmatched, truncated) }; if lines.is_empty() { return Err(EngineError::Other(format!("Retype: no selected shape matches a glyph of an available font ({} checked)", unmatched.len()))); } let made = s.edit("Retype", |d, sel| { + // The layers as they were, for the Text Wrap check below. + let before = lines.iter().any(|l| l.point.is_some()).then(|| d.clone()); let mut ids = vec![]; let mut emptied = vec![]; for l in &lines { let Some(first) = l.pieces.first() else { continue }; let (par, idx, _) = d.position(*first).ok_or(EngineError::NoNode(*first))?; - let t = l.text_object(system_layout); let id = d.alloc_id(); - let mut node = Node::new(id, NodeKind::Text(Box::new(t))); + let mut node = Node::new(id, NodeKind::Text(Box::new(l.t.clone()))); // The glyphs' own transparency (the group's, kept, still applies over it). node.opacity = l.opacity; node.blend = l.blend; @@ -603,15 +1255,66 @@ fn retype(s: &mut Session, p: &Value) -> Result { } } } + // Text Wrap objects above new area type flow it once the edit is done: area type they + // would move a glyph of becomes the point type that draws it in place. + if let Some(before) = &before { + // Worked out on a copy, so the edit's own Text Wrap refresh still sees every other + // area type whose wrap changes, and only on the layers this edit changed, as that + // refresh is. The copy holds only the changed layers while the work is counted; past + // the limit, the new area type is not flowed and all of it becomes its point type. + let mut probe = d.clone(); + let all = std::mem::take(&mut probe.layers); + probe.layers = all + .iter() + .enumerate() + .filter(|(i, layer)| { + // As resolve_wrap tells an unchanged layer: the same layer at its index first. + !(before.layers.get(*i).is_some_and(|b| Arc::ptr_eq(b, layer)) + || before.layers.iter().any(|b| b.id == layer.id && Arc::ptr_eq(b, layer))) + }) + .map(|(_, layer)| layer.clone()) + .collect(); + let units = vectorcraft_doc::text::wrap_copy_units(&probe); + let flowed = units <= max_wrap_work(); + probe.layers = all; + if flowed && units > 0 { + vectorcraft_doc::text::resolve_wrap(Some(before), &mut probe); + } + // With nothing to copy, no area type on those layers has a wrap shape. + for (l, id) in lines.iter().zip(&ids).filter(|_| units > 0) { + let Some(point) = &l.point else { continue }; + let Some(NodeKind::Text(t)) = probe.node(*id).map(|n| &n.kind) else { continue }; + if flowed && (t.wrap.is_empty() || first_mismatch(t, &l.matches, l.size).is_none()) { + continue; + } + if let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) { + **t = point.clone(); + } + } + } let mut keep: Vec = roots.iter().copied().filter(|r| d.node(*r).is_some()).collect(); keep.extend(&ids); sel.set(keep); Ok(ids) })?; + let d = &s.doc()?.doc; + let area = + |id: &NodeId| matches!(d.node(*id).map(|n| &n.kind), Some(NodeKind::Text(t)) if matches!(t.kind, vectorcraft_doc::TextKind::Area { .. })); Ok(json!({ "ids": made.iter().map(|i| i.0).collect::>(), "texts": lines.iter().map(|l| l.text.clone()).collect::>(), - "fonts": lines.iter().map(|l| json!({"family": l.face.family, "style": l.face.style, "size": l.scale * l.face.units_per_em()})).collect::>(), + "fonts": lines + .iter() + .zip(&made) + .map(|(l, id)| json!({ + "family": l.face.family, + "style": l.face.style, + "size": l.size, + "tracking": l.tracking, + "leading": l.leading, + "area": area(id), + })) + .collect::>(), "unmatched": unmatched.iter().map(|i| i.0).collect::>(), "truncated": truncated, })) diff --git a/crates/engine/src/cmd/retype_tests.rs b/crates/engine/src/cmd/retype_tests.rs index d691ab34fa..80361f1e0a 100644 --- a/crates/engine/src/cmd/retype_tests.rs +++ b/crates/engine/src/cmd/retype_tests.rs @@ -477,10 +477,10 @@ fn tracked_one_contour_letters_still_become_type() { let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap(); s.execute("select.set", &json!({"ids": [g]})).unwrap(); let r = s.execute("type.retype", &json!({})).unwrap(); - let texts: Vec = r["texts"].as_array().unwrap().iter().map(|t| t.as_str().unwrap().to_owned()).collect(); - assert_eq!(texts.concat(), text, "split by the tracking, every letter still becomes type: {r}"); - assert!(texts.len() > 1, "the tracking splits the line: {r}"); + assert_eq!(r["texts"], json!([text]), "evenly tracked, the line is one object: {r}"); + assert_eq!(r["fonts"][0]["tracking"], json!(50.0), "{r}"); assert_eq!(r["unmatched"], json!([]), "{r}"); + assert_eq!(text_of(&s, r["ids"][0].as_u64().unwrap()).first_style().tracking, 50.0); } } @@ -521,8 +521,8 @@ fn timing_with_hundreds_of_cjk_outlines() { #[test] fn a_long_tracked_line_is_checked_in_time() { - // Tracking splits the line at every glyph: the layout check must not lay out the rest of the - // line again after each split. + // Even tracking is kept on the line; the layout check of a long line must not lay out the rest + // of the line again after each window. let text = "abe".repeat(150); let mut s = session(); let id = s.execute("text.create", &json!({"x": 10, "y": 100, "text": text, "size": 4})).unwrap()["id"].as_u64().unwrap(); @@ -533,7 +533,706 @@ fn a_long_tracked_line_is_checked_in_time() { let t0 = std::time::Instant::now(); let r = s.execute("type.retype", &json!({})).unwrap(); let texts: Vec = r["texts"].as_array().unwrap().iter().map(|t| t.as_str().unwrap().to_owned()).collect(); - assert_eq!(texts.concat(), text); + assert_eq!(texts, vec![text], "the whole line is one object: {r}"); + assert_eq!(r["fonts"][0]["tracking"], json!(50.0), "{r}"); assert_eq!(r["unmatched"], json!([])); eprintln!("450 tracked glyphs: {:?}, {} objects", t0.elapsed(), texts.len()); } + +#[test] +fn two_overlapping_lone_glyphs_beside_art_stay_outlines() { + // Two M outlines start 0.3 em apart, closer than the first one's advance: a tight-tracking + // line of two, which the layout check splits again. Each is still a lone one-contour glyph. + let mut s = session(); + let a = outlined(&mut s, json!({"x": 40, "y": 100, "text": "M", "size": 30})); + let b = outlined(&mut s, json!({"x": 49, "y": 100, "text": "M", "size": 30})); + let dot = s.execute("shape.ellipse", &json!({"x": 300, "y": 60, "width": 8, "height": 8})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [a, b, dot]})).unwrap(); + // Nothing is left to retype: both stay outlines, as the lone bar beside art does. + let e = s.execute("type.retype", &json!({})).unwrap_err(); + assert!(format!("{e:?}").contains("no selected shape matches"), "{e:?}"); +} + +/// Where type `t` draws each glyph that has ink, in document space. +fn glyph_places(t: &TextObject) -> Vec { + let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t); + lay.glyphs.iter().filter(|g| !g.outline.elements().is_empty()).map(|g| t.xf * (g.xf * kurbo::Point::ORIGIN)).collect() +} + +/// Type made with `p` (and `setup` run on its id), outlined and retyped: the original type, and +/// Retype's result. +fn retyped(s: &mut Session, p: serde_json::Value, setup: &[serde_json::Value]) -> (TextObject, serde_json::Value) { + let id = s.execute("text.create", &p).unwrap()["id"].as_u64().unwrap(); + for q in setup { + let mut q = q.clone(); + q["id"] = json!(id); + s.execute("text.setRangeStyle", &q).unwrap(); + } + let before = text_of(s, id); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + (before, s.execute("type.retype", &json!({})).unwrap()) +} + +fn assert_same_places(a: &TextObject, b: &TextObject) { + let (pa, pb) = (glyph_places(a), glyph_places(b)); + assert_eq!(pa.len(), pb.len()); + for (x, y) in pa.iter().zip(&pb) { + assert!(x.distance(*y) < 0.05, "{x:?} vs {y:?}"); + } +} + +#[test] +fn several_lines_become_one_area_type_object() { + let mut s = session(); + let text = "First line\nSecond one\nThird"; + let (before, r) = retyped(&mut s, json!({"x": 40, "y": 100, "text": text, "size": 24}), &[]); + assert_eq!(r["texts"], json!([text]), "{r}"); + assert_eq!(r["fonts"][0]["area"], json!(true), "{r}"); + assert_eq!(r["fonts"][0]["leading"], json!(null), "Auto leading gives the lines' spacing: {r}"); + let t = text_of(&s, r["ids"][0].as_u64().unwrap()); + assert!(matches!(t.kind, vectorcraft_doc::TextKind::Area { .. })); + assert_eq!(t.plain_text(), text); + assert_same_places(&before, &t); +} + +#[test] +fn lines_a_quarter_of_the_size_apart_join_and_closer_ones_do_not() { + // At 20 pt, 5 pt is the least leading that joins lines. + // 4.9999999 pt is 5 pt to the rounding of the outlines' positions. + for (leading, objects) in [(5.0, 1), (4.9999999, 1), (4.9, 2)] { + let mut s = session(); + let text = "One\nTwo"; + let (_, r) = retyped(&mut s, json!({"x": 40, "y": 100, "text": text, "size": 20}), &[json!({"leading": leading})]); + assert_eq!(r["texts"].as_array().unwrap().len(), objects, "{leading}: {r}"); + } +} + +#[test] +fn a_two_glyph_line_takes_the_tracking_of_the_lines_around_it() { + let mut s = session(); + let text = "MMM\nMM\nMMM"; + let (before, r) = retyped(&mut s, json!({"x": 40, "y": 100, "text": text, "size": 24}), &[json!({"tracking": 50})]); + assert_eq!(r["texts"], json!([text]), "{r}"); + assert_eq!(r["fonts"][0]["tracking"], json!(50.0), "{r}"); + assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap())); +} + +#[test] +fn lines_keep_their_leading_and_alignment() { + for justify in ["left", "center", "right"] { + let mut s = session(); + let text = "Wide first line\nmid\nlast one"; + let (before, r) = retyped(&mut s, json!({"x": 300, "y": 100, "text": text, "size": 20, "justify": justify}), &[json!({"leading": 31})]); + assert_eq!(r["texts"], json!([text]), "{justify}: {r}"); + assert!(near(r["fonts"][0]["leading"].as_f64().unwrap(), 31.0, 1e-3), "{justify}: {r}"); + assert_eq!(r["fonts"][0]["area"], json!(true), "{justify}: {r}"); + let t = text_of(&s, r["ids"][0].as_u64().unwrap()); + assert!(matches!(t.kind, vectorcraft_doc::TextKind::Area { .. }), "{justify}"); + assert_eq!(t.para.justify, before.para.justify, "{justify}"); + assert_same_places(&before, &t); + } +} + +#[test] +fn a_long_block_near_auto_leading_keeps_its_own_leading() { + // 24.001 pt is Auto's 24 pt within a ten-thousandth of the size per line, but 250 lines + // move the last one a quarter of a point. + let mut s = session(); + let text = vec!["ab"; 250].join("\n"); + let (before, r) = retyped(&mut s, json!({"x": 40, "y": 40, "text": text, "size": 20}), &[json!({"leading": 24.001})]); + assert_eq!(r["texts"], json!([text]), "{}", r["fonts"].as_array().map_or(0, |f| f.len())); + assert!(near(r["fonts"][0]["leading"].as_f64().unwrap(), 24.001, 1e-4), "{}", r["fonts"][0]); + assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap())); +} + +#[test] +fn a_long_block_at_auto_leading_of_a_fractional_size_keeps_auto() { + // Auto leading of 20.002 pt is 24.0024 pt, finer than the thousandth of a point the leading + // between two lines is read to. + let mut s = session(); + // Six hundred lines: read to a thousandth, each gap would be 0.0004 pt short, and the last + // line 0.24 pt off. + let text = vec!["ab"; 600].join("\n"); + let (before, r) = retyped(&mut s, json!({"x": 40, "y": 40, "text": text, "size": 20.002}), &[]); + assert_eq!(r["texts"], json!([text]), "{}", r["fonts"].as_array().map_or(0, |f| f.len())); + assert_eq!(r["fonts"][0]["leading"], json!(null), "{}", r["fonts"][0]); + assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap())); +} + +#[test] +fn a_long_block_at_a_leading_finer_than_a_thousandth_keeps_it() { + // 23.9996 pt read to a thousandth is 24 pt, Auto for 20 pt type: over 600 lines the last one + // would be 0.24 pt off. + let mut s = session(); + let text = vec!["ab"; 600].join("\n"); + let (before, r) = retyped(&mut s, json!({"x": 40, "y": 40, "text": text, "size": 20}), &[json!({"leading": 23.9996})]); + assert_eq!(r["texts"], json!([text]), "{}", r["fonts"].as_array().map_or(0, |f| f.len())); + assert!(near(r["fonts"][0]["leading"].as_f64().unwrap(), 23.9996, 1e-6), "{}", r["fonts"][0]); + assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap())); +} + +#[test] +fn a_block_whose_first_gap_is_a_little_off_stays_one_object() { + // The second line moved up 0.004 pt: its gap read alone, carried over 100 lines, would put + // the last one 0.4 pt off. + let mut s = session(); + let text = ["ab"; 100].join("\n"); + let id = s.execute("text.create", &json!({"x": 40, "y": 40, "text": text, "size": 20})).unwrap()["id"].as_u64().unwrap(); + s.execute("text.setRangeStyle", &json!({"id": id, "leading": 24.004})).unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap(); + let kids = children_of(&s, g); + s.execute("select.set", &json!({"ids": kids[2..4]})).unwrap(); + s.execute("object.move", &json!({"dx": 0, "dy": -0.004})).unwrap(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!(r["texts"], json!([text]), "{}", r["fonts"].as_array().map_or(0, |f| f.len())); + assert!(near(r["fonts"][0]["leading"].as_f64().unwrap(), 24.004, 1e-3), "{}", r["fonts"][0]); +} + +#[test] +fn lines_whose_frame_would_pass_the_coordinate_limit_stay_point_type() { + let mut s = session(); + let text = "Wide line\nWide"; + let id = s.execute("text.create", &json!({"x": 3_999_000, "y": 100, "text": text, "size": 20})).unwrap()["id"].as_u64().unwrap(); + let right = s.doc().unwrap().doc.node(NodeId(id)).unwrap().geometric_bounds().unwrap().x1; + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + // The ink ends 2 pt short of the limit; Convert To Area Type's slack would reach past it. + s.execute("object.move", &json!({"dx": vectorcraft_doc::MAX_COORD - 2.0 - right, "dy": 0})).unwrap(); + let before = text_of(&s, id); + let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!(r["texts"], json!([text]), "{r}"); + assert_eq!(r["fonts"][0]["area"], json!(false), "{r}"); + assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap())); +} + +#[test] +fn a_line_type_cannot_join_ends_the_block_there() { + // The fourth line keeps a fraction of a unit of tracking that the others do not: joined, it + // moves, so the lines before it stay one object and the lines after it join again. + let mut s = session(); + let line = "M".repeat(40); + let text = [line.as_str(); 6].join("\n"); + let start = 3 * 41; + let (before, r) = + retyped(&mut s, json!({"x": 20, "y": 40, "text": text, "size": 20}), &[json!({"start": start, "end": start + 40, "tracking": 0.6})]); + let texts: Vec = r["texts"].as_array().unwrap().iter().map(|t| t.as_str().unwrap().to_owned()).collect(); + assert_eq!(texts.len(), 3, "{texts:?} {}", r["fonts"]); + assert_eq!(texts.join("\n"), text); + let places: Vec = r["ids"].as_array().unwrap().iter().flat_map(|id| glyph_places(&text_of(&s, id.as_u64().unwrap()))).collect(); + let want = glyph_places(&before); + assert_eq!(places.len(), want.len()); + for (x, y) in places.iter().zip(&want) { + assert!(x.distance(*y) < 0.05, "{x:?} vs {y:?}"); + } +} + +/// The glyphs of the outline groups `others` moved to the end of group `g`, in order, and the +/// emptied groups removed. +fn into_one_group(s: &mut Session, g: u64, others: &[u64]) { + s.edit("test", |d, _| { + for o in others { + let kids: Vec<_> = d.node(NodeId(*o)).unwrap().children().unwrap().to_vec(); + d.remove(NodeId(*o))?; + for k in kids { + let at = d.node(NodeId(g)).unwrap().children().unwrap().len(); + d.insert(Some(NodeId(g)), at, (*k).clone())?; + } + } + Ok(()) + }) + .unwrap(); +} + +#[test] +fn lines_that_do_not_stack_as_a_paragraph_stay_apart() { + let mut s = session(); + // Far apart, then lined up at nothing. + let a = outlined(&mut s, json!({"x": 40, "y": 100, "text": "Top", "size": 20})); + let b = outlined(&mut s, json!({"x": 40, "y": 300, "text": "Far", "size": 20})); + let c = outlined(&mut s, json!({"x": 75, "y": 324, "text": "Askew", "size": 20})); + into_one_group(&mut s, a, &[b, c]); + s.execute("select.set", &json!({"ids": [a]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!(r["texts"], json!(["Top", "Far", "Askew"]), "{r}"); + assert!(r["fonts"].as_array().unwrap().iter().all(|f| f["area"] == json!(false)), "{r}"); +} + +#[test] +fn a_shape_between_lines_keeps_them_apart() { + let mut s = session(); + let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "AB\nCD", "size": 30})); + let rect = s.execute("shape.rectangle", &json!({"x": 30, "y": 60, "width": 80, "height": 80})).unwrap()["id"].as_u64().unwrap(); + s.edit("test", |d, _| { + let n = d.node(NodeId(rect)).unwrap().clone(); + d.remove(NodeId(rect))?; + d.insert(Some(NodeId(g)), 2, n)?; + Ok(()) + }) + .unwrap(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!(r["texts"], json!(["AB", "CD"]), "the rectangle is painted between the lines: {r}"); +} + +#[test] +fn tracked_lines_keep_their_tracking_and_spaces() { + let mut s = session(); + let text = "SPACED OUT\nTITLE"; + let (before, r) = retyped(&mut s, json!({"x": 40, "y": 100, "text": text, "size": 24}), &[json!({"tracking": 400})]); + assert_eq!(r["texts"], json!([text]), "{r}"); + assert_eq!(r["fonts"][0]["tracking"], json!(400.0), "{r}"); + assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap())); +} + +#[test] +fn a_short_line_takes_the_tracking_of_its_block() { + // One glyph has no gap to measure tracking by: it joins the tracked lines. + for text in ["TITLE\nB", "B\nTITLE", "TITLE\nB\nTITLE"] { + let mut s = session(); + let (before, r) = retyped(&mut s, json!({"x": 40, "y": 100, "text": text, "size": 24}), &[json!({"tracking": 400})]); + assert_eq!(r["texts"], json!([text]), "{r}"); + assert_eq!(r["fonts"][0]["tracking"], json!(400.0), "{r}"); + assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap())); + } +} + +#[test] +fn unevenly_tracked_type_still_becomes_type() { + let mut s = session(); + // Less than half a space more after e: no gap can be read as a word space. + let text = "abcdefgh"; + let (before, r) = retyped( + &mut s, + json!({"x": 40, "y": 100, "text": text, "size": 30}), + &[json!({"start": 0, "end": 4, "tracking": 50}), json!({"start": 4, "end": 8, "tracking": 120})], + ); + let texts: Vec = r["texts"].as_array().unwrap().iter().map(|t| t.as_str().unwrap().to_owned()).collect(); + assert_eq!(texts.concat(), text, "{r}"); + assert!(texts.len() > 1, "{r}"); + assert_eq!(r["unmatched"], json!([]), "{r}"); + // Each object's glyphs are where the outlines were. + let places: Vec = r["ids"].as_array().unwrap().iter().flat_map(|id| glyph_places(&text_of(&s, id.as_u64().unwrap()))).collect(); + let want = glyph_places(&before); + assert_eq!(places.len(), want.len()); + for (x, y) in places.iter().zip(&want) { + assert!(x.distance(*y) < 0.05, "{x:?} vs {y:?}"); + } + // The second half keeps its own tracking. + assert_eq!(r["fonts"].as_array().unwrap().last().unwrap()["tracking"], json!(120.0), "{r}"); +} + +#[test] +fn a_tracked_line_keeps_its_tracking_and_spaces() { + let mut s = session(); + let text = "SPACED OUT"; + let (before, r) = retyped(&mut s, json!({"x": 40, "y": 100, "text": text, "size": 24}), &[json!({"tracking": 400})]); + assert_eq!(r["texts"], json!([text]), "{r}"); + assert_eq!(r["fonts"][0]["tracking"], json!(400.0), "{r}"); + assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap())); +} + +#[test] +fn a_long_line_tracked_two_spaces_wide_keeps_its_tracking() { + // Read as it is, the line holds two spaces in each gap, which the tracking measure lays out too. + let mut s = session(); + let text = "M".repeat(400); + let (_, r) = retyped(&mut s, json!({"x": 10, "y": 100, "text": text, "size": 10}), &[json!({"tracking": 400})]); + assert_eq!(r["texts"], json!([text]), "{}", r["fonts"]); + assert_eq!(r["fonts"][0]["tracking"], json!(400.0), "{}", r["fonts"]); +} + +#[test] +fn a_long_tightly_tracked_line_keeps_its_word_spaces() { + // Read as it is, the line holds no spaces; the tracked reading holds eight in each word gap. + let mut s = session(); + let text = vec!["MMM"; 100].join(" "); + let (_, r) = retyped(&mut s, json!({"x": 10, "y": 100, "text": text, "size": 10}), &[json!({"tracking": -180})]); + assert_eq!(r["texts"], json!([text]), "{}", r["fonts"]); + assert_eq!(r["fonts"][0]["tracking"], json!(-180.0), "{}", r["fonts"]); +} + +#[test] +fn spaced_letters_keep_their_spaces_when_type_draws_them() { + // Most gaps are word spaces: untracked type with the spaces draws every glyph in place. + // Every gap one word space: tracking a space wide would draw them too, without the spaces. + // L T J: without its spaces the pairs kern, which a measure of the gaps would read as more space. + for text in ["a a a aa", "1 2 3", "a b c d", "x = y + 1", "L T J"] { + let mut s = session(); + let (before, r) = retyped(&mut s, json!({"x": 40, "y": 100, "text": text, "size": 30}), &[]); + assert_eq!(r["texts"], json!([text]), "{r}"); + assert_eq!(r["fonts"][0]["tracking"], json!(0.0), "{r}"); + assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap())); + } +} + +#[test] +fn slight_tracking_without_spaces_is_kept() { + // Tracking 3 moves the last glyph less than the layout check notices: both readings draw it. + // A word space both readings keep does not cost the tracking either. + for text in ["MMM", "M MM"] { + let mut s = session(); + let (before, r) = retyped(&mut s, json!({"x": 40, "y": 100, "text": text, "size": 30}), &[json!({"tracking": 3})]); + assert_eq!(r["texts"], json!([text]), "{r}"); + assert_eq!(r["fonts"][0]["tracking"], json!(3.0), "{r}"); + assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap())); + } +} + +/// The lines Retype reads from the outlines in group `g` (all in the face of its first glyph's +/// first match), before their tracking is measured and their layout checked. +fn lines_in(s: &Session, g: u64) -> Vec { + let d = &s.doc().unwrap().doc; + let (mut barrier, mut truncated, mut pieces) = (true, false, vec![]); + super::collect(d.node(NodeId(g)).unwrap(), d.parent_of(NodeId(g)), 0, &mut barrier, &mut truncated, &mut pieces); + let db = vectorcraft_text::FontDb::global(); + let wanted = pieces.iter().filter_map(|pc| vectorcraft_text::retype::shape_key(&pc.path)).collect(); + let index = super::RetypeIndex::build(db, super::candidate_faces(db, d, &[]), &wanted); + let face = index.matches(&pieces[0].path)[0].face.id(); + let mut lines: Vec = vec![]; + for pc in &pieces { + let cands: Vec<_> = index.matches(&pc.path).into_iter().filter(|m| m.face.id() == face).collect(); + if !lines.last_mut().is_some_and(|l| super::join(l, pc, &cands)) { + lines.extend(super::new_line(pc, &cands)); + } + } + lines +} + +#[test] +fn the_glyphs_after_one_type_cannot_draw_keep_their_tracking() { + // Glyph `bad` of a tracked line read as another glyph of its font, as when the line's type + // would draw another form there: the glyphs after it are still one tracked object. + for bad in [0usize, 1] { + let mut s = session(); + let id = s.execute("text.create", &json!({"x": 40, "y": 100, "text": "MMMMMM", "size": 30})).unwrap()["id"].as_u64().unwrap(); + s.execute("text.setRangeStyle", &json!({"id": id, "tracking": 300})).unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap(); + let lines = lines_in(&s, g); + assert_eq!(lines.len(), 1); + let mut budget = 1000; + let mut l = lines.into_iter().next().unwrap().tracked(false, &mut budget); + assert_eq!(l.tracking, 300.0); + let other = l.matches[bad].gid + 1; + l.matches[bad].gid = other; + let bad_id = l.pieces[bad]; + let mut unmatched = vec![]; + let out = super::verified(vec![l], false, &mut unmatched); + assert_eq!(unmatched, vec![bad_id], "{bad}"); + let last = out.last().unwrap(); + assert_eq!(last.pieces.len(), 5 - bad, "{bad}: {:?}", out.iter().map(|l| (l.pieces.len(), l.tracking)).collect::>()); + assert_eq!(last.tracking, 300.0, "{bad}"); + } +} + +#[test] +fn the_tracking_measure_counts_the_spaces_it_lays_out() { + // Three glyphs ten spaces apart: a budget of six times the glyphs, short of the first + // layout's 23 characters, lays nothing out. + let mut s = session(); + let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "a b c", "size": 30})); + let lines = lines_in(&s, g); + assert_eq!(lines.len(), 1); + assert!(lines[0].text.chars().filter(|c| *c == ' ').count() >= 20, "{}", lines[0].text); + let mut budget = 3 * 6; + let l = lines.into_iter().next().unwrap().tracked(false, &mut budget); + assert_eq!((budget, l.tracking), (3 * 6, 0.0)); +} + +#[test] +fn the_tracking_measure_needs_only_the_layouts_it_runs() { + // The line as read, without spaces, with one space per gap, then the tracked reading: a + // budget of exactly those characters recovers the tracking. + let mut s = session(); + let id = s.execute("text.create", &json!({"x": 40, "y": 100, "text": "MMMMMM", "size": 30})).unwrap()["id"].as_u64().unwrap(); + s.execute("text.setRangeStyle", &json!({"id": id, "tracking": 300})).unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap(); + let lines = lines_in(&s, g); + assert_eq!(lines.len(), 1); + let mut budget = lines[0].text.chars().count() + 6 + 11 + 6; + let l = lines.into_iter().next().unwrap().tracked(false, &mut budget); + assert_eq!((budget, l.tracking), (0, 300.0)); +} + +#[test] +fn the_rest_of_a_widely_tracked_line_keeps_its_tracking_after_a_split() { + // Tracking 40 spaces wide: read untracked, the rest after the split holds 40 spaces per gap, + // and its measure still has the budget to lay them out. + let mut s = session(); + let id = s.execute("text.create", &json!({"x": 10, "y": 100, "text": "M".repeat(100), "size": 2})).unwrap()["id"].as_u64().unwrap(); + s.execute("text.setRangeStyle", &json!({"id": id, "tracking": 8000})).unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap(); + let mut budget = 100_000; + let mut l = lines_in(&s, g).into_iter().next().unwrap().tracked(false, &mut budget); + assert_eq!(l.tracking, 8000.0); + l.matches[0].gid += 1; + let mut unmatched = vec![]; + let out = super::verified(vec![l], false, &mut unmatched); + assert_eq!(unmatched.len(), 1); + let last = out.last().unwrap(); + assert_eq!((last.pieces.len(), last.tracking), (99, 8000.0), "{:?}", out.iter().map(|l| (l.pieces.len(), l.tracking)).collect::>()); +} + +#[test] +fn glyphs_type_cannot_draw_do_not_use_up_the_tracking_measure() { + // A long tracked line whose first five glyphs are read as other glyphs: the rest is still one + // tracked object. + let mut s = session(); + let id = s.execute("text.create", &json!({"x": 10, "y": 100, "text": "i".repeat(100), "size": 10})).unwrap()["id"].as_u64().unwrap(); + s.execute("text.setRangeStyle", &json!({"id": id, "tracking": 300})).unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap(); + let mut budget = 1000; + let mut l = lines_in(&s, g).into_iter().next().unwrap().tracked(false, &mut budget); + assert_eq!(l.tracking, 300.0); + for m in l.matches.iter_mut().take(5) { + m.gid += 1; + } + let mut unmatched = vec![]; + let out = super::verified(vec![l], false, &mut unmatched); + assert_eq!(unmatched.len(), 5); + let last = out.last().unwrap(); + assert_eq!((last.pieces.len(), last.tracking), (95, 300.0), "{:?}", out.iter().map(|l| (l.pieces.len(), l.tracking)).collect::>()); +} + +#[test] +fn tightly_tracked_type_keeps_its_tracking() { + // Tracking tighter than a space: the space moves the next glyph back. + // M MM: of its two gaps, the word space is the tighter, and the lower median. + // M M MM: most gaps hold a word space, so the tightest extras alone seed a tracking that + // splits the last glyph. + for text in ["MMMM", "MMMM MM", "M MM", "MM M", "M M MM"] { + let mut s = session(); + let (before, r) = retyped(&mut s, json!({"x": 40, "y": 100, "text": text, "size": 30}), &[json!({"tracking": -300})]); + assert_eq!(r["texts"], json!([text]), "{r}"); + assert_eq!(r["fonts"][0]["tracking"], json!(-300.0), "{r}"); + assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap())); + } +} + +#[test] +fn kerned_pairs_in_tight_tracking_are_not_read_as_spaces() { + // Tracking -250 gives a space a negative advance; the pair kerning of T and a is no space. + let mut s = session(); + let text = "MMMTaMMM"; + let (before, r) = retyped(&mut s, json!({"x": 40, "y": 100, "text": text, "size": 30}), &[json!({"tracking": -250})]); + assert_eq!(r["texts"], json!([text]), "{r}"); + assert_eq!(r["fonts"][0]["tracking"], json!(-250.0), "{r}"); + assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap())); +} + +#[test] +fn a_word_space_between_kerned_letters_is_read_as_a_space() { + // T and a kern when they touch; with a space between them they do not. + let mut s = session(); + let text = "MMMT aMMM"; + let (before, r) = retyped(&mut s, json!({"x": 40, "y": 100, "text": text, "size": 30}), &[json!({"tracking": -250})]); + assert_eq!(r["texts"], json!([text]), "{r}"); + assert_eq!(r["fonts"][0]["tracking"], json!(-250.0), "{r}"); + assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap())); + // Tracking that cancels the space's advance: the space still stops the pair kerning. + let mut s = session(); + let text = "MMMT aMMM"; + let (before, r) = retyped(&mut s, json!({"x": 40, "y": 100, "text": text, "size": 30}), &[json!({"tracking": -200})]); + assert_eq!(r["texts"], json!([text]), "{r}"); + assert_eq!(r["fonts"][0]["tracking"], json!(-200.0), "{r}"); + assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap())); + // Tracking that nearly cancels it: the space still moves the glyphs after it a little. + let mut s = session(); + let text = "MMMM MM"; + let (before, r) = retyped(&mut s, json!({"x": 40, "y": 100, "text": text, "size": 30}), &[json!({"tracking": -199.5})]); + assert_eq!(r["texts"], json!([text]), "{r}"); + assert!(near(r["fonts"][0]["tracking"].as_f64().unwrap(), -199.5, 1e-3), "{r}"); + assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap())); + // A word space a little narrower than its tracking makes it (the word after it moved left by + // less than the layout check notices): one space still fits better than the kerned pair. + for (tracking, dx) in [(-190, -0.18), (-193, -0.24)] { + let mut s = session(); + let id = s.execute("text.create", &json!({"x": 40, "y": 100, "text": "MMMc aMMM", "size": 30})).unwrap()["id"].as_u64().unwrap(); + s.execute("text.setRangeStyle", &json!({"id": id, "tracking": tracking})).unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap(); + let kids = children_of(&s, g); + assert_eq!(kids.len(), 8); + s.execute("select.set", &json!({"ids": kids[4..]})).unwrap(); + s.execute("object.move", &json!({"dx": dx, "dy": 0})).unwrap(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!(r["texts"], json!(["MMMc aMMM"]), "{tracking}: {r}"); + } + // A space that kerns with the letter after it. + let mut s = session(); + let text = "MMMd TMMM"; + let p = json!({"x": 40, "y": 100, "text": text, "size": 30, "font": "Source Serif 4", "style": "Regular"}); + let (before, r) = retyped(&mut s, p, &[json!({"tracking": -217})]); + assert_eq!(r["texts"], json!([text]), "{r}"); + assert_eq!(r["fonts"][0]["tracking"], json!(-217.0), "{r}"); + assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap())); +} + +#[test] +fn an_untracked_word_is_not_read_as_spaced_letters_in_tight_tracking() { + // Letters, each followed by a space, at tracking of minus half a space, sit where the word's + // letters do. + let mut s = session(); + let (_, r) = retyped(&mut s, json!({"x": 40, "y": 100, "text": "Third", "size": 24}), &[]); + assert_eq!(r["texts"], json!(["Third"]), "{r}"); + assert_eq!(r["fonts"][0]["tracking"], json!(0.0), "{r}"); +} + +#[test] +fn glyphs_barely_ahead_of_each_other_stay_one_line() { + let mut s = session(); + let (before, r) = retyped(&mut s, json!({"x": 40, "y": 100, "text": "MMMM", "size": 30}), &[json!({"tracking": -700})]); + assert_eq!(r["texts"], json!(["MMMM"]), "{r}"); + assert_eq!(r["fonts"][0]["tracking"], json!(-700.0), "{r}"); + assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap())); +} + +#[test] +fn tracking_near_a_whole_number_is_kept_as_measured_when_rounding_moves_glyphs() { + let mut s = session(); + let text = "i".repeat(400); + let (before, r) = retyped(&mut s, json!({"x": 10, "y": 100, "text": text, "size": 10}), &[json!({"tracking": 50.04})]); + assert_eq!(r["texts"], json!([text]), "{r}"); + assert!(near(r["fonts"][0]["tracking"].as_f64().unwrap(), 50.04, 1e-3), "{}", r["fonts"]); + assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap())); +} + +#[test] +fn overlapping_translucent_glyphs_are_not_tracked_into_one_object() { + let mut s = session(); + let id = s.execute("text.create", &json!({"x": 40, "y": 100, "text": "MMMM", "size": 30})).unwrap()["id"].as_u64().unwrap(); + s.execute("text.setRangeStyle", &json!({"id": id, "tracking": -300})).unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap(); + let kids = children_of(&s, g); + s.edit("test", |d, _| { + for k in &kids { + d.node_mut(NodeId(*k)).unwrap().opacity = 0.5; + } + Ok(()) + }) + .unwrap(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + // Each glyph composites on its own over the one it overlaps, as the outlines did. + assert_eq!(r["texts"], json!(["M", "M", "M", "M"]), "{r}"); + assert!(r["fonts"].as_array().unwrap().iter().all(|f| f["tracking"] == json!(0.0)), "{r}"); +} + +#[test] +fn translucent_gradient_or_stroked_lines_stay_apart() { + for case in ["opacity", "blend", "gradient", "stroke"] { + let mut s = session(); + let g = outlined(&mut s, json!({"x": 40, "y": 100, "text": "One\nTwo", "size": 30})); + let kids = children_of(&s, g); + match case { + "gradient" => { + let gradient = json!({"kind": "linear", "stops": [{"offset": 0, "color": "#000"}, {"offset": 1, "color": "#fff"}]}); + s.execute("paint.setFill", &json!({"gradient": gradient, "ids": kids})).unwrap(); + } + "stroke" => { + s.execute("paint.setStroke", &json!({"color": "#ff0000", "ids": kids})).unwrap(); + } + _ => { + s.edit("test", |d, _| { + for k in &kids { + let n = d.node_mut(NodeId(*k)).unwrap(); + if case == "opacity" { + n.opacity = 0.5; + } else { + n.blend = vectorcraft_color::BlendMode::Multiply; + } + } + Ok(()) + }) + .unwrap(); + } + } + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!(r["texts"], json!(["One", "Two"]), "{case}: one object would composite or fill the lines as one: {r}"); + } +} + +#[test] +fn lines_stay_point_type_past_the_text_wrap_limit_of_their_layer() { + // A Text Wrap object above the lines that moves no glyph, on their layer or on another one, + // with the limit lowered to nothing: only on their layer does it count. + for same_layer in [true, false] { + let mut s = session(); + let text = "First line\nSecond one"; + let id = s.execute("text.create", &json!({"x": 40, "y": 100, "text": text, "size": 24})).unwrap()["id"].as_u64().unwrap(); + let before = text_of(&s, id); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap(); + if !same_layer { + // Area type below the Text Wrap object on the other layer: work there, none on this one. + s.execute("layer.new", &json!({})).unwrap(); + let other = s.execute("text.create", &json!({"x": 450, "y": 300, "text": "Other", "size": 12})).unwrap()["id"].as_u64().unwrap(); + s.execute("type.convertToAreaType", &json!({"ids": [other]})).unwrap(); + } + let rect = s.execute("shape.rectangle", &json!({"x": 500, "y": 330, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.textWrap.make", &json!({"ids": [rect]})).unwrap(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + super::WRAP_LIMIT.with(|c| c.set(0)); + let r = s.execute("type.retype", &json!({})); + super::WRAP_LIMIT.with(|c| c.set(super::MAX_WRAP_WORK)); + let r = r.unwrap(); + assert_eq!(r["texts"], json!([text]), "{r}"); + assert_eq!(r["fonts"][0]["area"], json!(!same_layer), "{same_layer}: {r}"); + assert_same_places(&before, &text_of(&s, r["ids"][0].as_u64().unwrap())); + } +} + +#[test] +fn empty_subpaths_of_a_text_wrap_object_count_as_wrap_work() { + // Each one is copied into the wrap shapes of the area type below it. + let mut s = session(); + let t = s.execute("text.create", &json!({"x": 40, "y": 100, "text": "Area", "size": 12})).unwrap()["id"].as_u64().unwrap(); + s.execute("type.convertToAreaType", &json!({"ids": [t]})).unwrap(); + let rect = s.execute("shape.rectangle", &json!({"x": 300, "y": 300, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.textWrap.make", &json!({"ids": [rect]})).unwrap(); + let base = vectorcraft_doc::text::wrap_copy_units(&s.doc().unwrap().doc); + let file_work = vectorcraft_doc::text::wrap_work(&s.doc().unwrap().doc); + s.edit("test", |d, _| { + if let NodeKind::Path { path, .. } = &mut d.node_mut(NodeId(rect)).unwrap().kind { + for _ in 0..100 { + path.subpaths.push(vectorcraft_geom::SubPath::new(vec![], true)); + } + } + Ok(()) + }) + .unwrap(); + assert!(vectorcraft_doc::text::wrap_copy_units(&s.doc().unwrap().doc) >= base + 100); + // The count file import and the `.ai` editing copy use stays anchors and shapes only. + assert_eq!(vectorcraft_doc::text::wrap_work(&s.doc().unwrap().doc), file_work); +} + +#[test] +fn lines_under_a_text_wrap_object_stay_point_type() { + let mut s = session(); + let text = "First line\nSecond one"; + let id = s.execute("text.create", &json!({"x": 40, "y": 100, "text": text, "size": 24})).unwrap()["id"].as_u64().unwrap(); + let before = text_of(&s, id); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let g = s.execute("type.createOutlines", &json!({})).unwrap()["ids"][0].as_u64().unwrap(); + // Above the outlines, over the end of both lines: area type would wrap round it. + let rect = s.execute("shape.rectangle", &json!({"x": 90, "y": 70, "width": 60, "height": 50})).unwrap()["id"].as_u64().unwrap(); + s.execute("object.textWrap.make", &json!({"ids": [rect]})).unwrap(); + s.execute("select.set", &json!({"ids": [g]})).unwrap(); + let r = s.execute("type.retype", &json!({})).unwrap(); + assert_eq!(r["texts"], json!([text]), "{r}"); + assert_eq!(r["fonts"][0]["area"], json!(false), "{r}"); + let t = text_of(&s, r["ids"][0].as_u64().unwrap()); + assert!(matches!(t.kind, vectorcraft_doc::TextKind::Point)); + assert_same_places(&before, &t); +} diff --git a/crates/engine/src/cmd/stroke.rs b/crates/engine/src/cmd/stroke.rs index f1e47b889a..cb5d1fd374 100644 --- a/crates/engine/src/cmd/stroke.rs +++ b/crates/engine/src/cmd/stroke.rs @@ -11,7 +11,7 @@ use vectorcraft_geom::PathData; use vectorcraft_tools::builder::is_live_paint; use super::appearance::{ItemTarget, edit_items, item_target}; -use super::paint::{live_paint_parts, live_paint_parts_skipped, painted}; +use super::paint::{live_paint_covered, live_paint_parts_skipped, painted}; use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, has_doc, ok, str_param}; use crate::DocState; use crate::inspect::{ALIGNS, CAPS, JOINS, StrokeMixed, node_stroke, scale_layer}; @@ -250,10 +250,15 @@ fn stroke_set(s: &mut Session, p: &Value) -> Result { } else if item == ItemTarget::Top { own_stroke_or_leaves(s, p)? } else { - item.targets(s, p)? + item.targets_for(s, p, false)? }; // A Live Paint group without edges was still selected or given: the options do not go to new art. - let live_paint = !bucket && item == ItemTarget::Top && !live_paint_parts_skipped(&s.doc()?.doc, &super::targets(s, p)?, false).is_empty(); + let live_paint = !bucket + && if item == ItemTarget::Top { + !live_paint_parts_skipped(&s.doc()?.doc, &super::targets(s, p)?, false).is_empty() + } else { + !super::appearance::contents_skipped(s, p, false)?.is_empty() + }; let new_art = bucket || (no_targets(&ids, p) && !live_paint); let given = !ids.is_empty() || live_paint; // The art of a graph design in a series keeps the design's stroke. @@ -445,7 +450,7 @@ impl Session { /// selection's stroke. pub fn shown_stroke(&self) -> Option { let st = self.active()?; - if self.tool_id() == super::paint::LIVE_PAINT_BUCKET { + if self.bucket_paints() { return Some(self.new_art_stroke()); } if let Some(part) = st.selected_symbol_part() { @@ -453,12 +458,15 @@ impl Session { } let Some(first) = st.selection.objects.first() else { return Some(self.new_art_stroke()) }; let first = st.doc.node(*first)?; + // Only an active Appearance row is shown here: it is a row of the first selected object. if let Some(i) = first.appearance.item_of_kind(self.appearance_item(), false) { return first.appearance.stroke_at(Some(i)).cloned(); } // A Live Paint group without edges shows the next selected object's stroke; any other object - // without a painted object shows none. - for id in &st.selection.objects { + // without a painted object shows none. A face or edge selected with its Live Paint group counts + // with the group, wherever it is in the selection. + let covered = live_paint_covered(&st.doc, &st.selection.objects); + for id in st.selection.objects.iter().filter(|id| !covered.contains(*id)) { let Some(n) = st.doc.node(*id) else { continue }; let mut nodes = vec![]; painted(n, true, true, &mut nodes); @@ -532,7 +540,7 @@ impl DocState { } else { let selected: Vec<&Node> = self.selection.objects.iter().filter_map(|id| self.doc.node(*id)).collect(); // The faces and edges of the selected Live Paint groups: selected as well, they count with their group's. - let covered: std::collections::HashSet = selected.iter().flat_map(|n| live_paint_parts(n)).collect(); + let covered = live_paint_covered(&self.doc, &self.selection.objects); for n in selected.into_iter().filter(|n| !covered.contains(&n.id)) { painted(n, true, true, &mut nodes); } diff --git a/crates/engine/src/cmd/swatchlib.rs b/crates/engine/src/cmd/swatchlib.rs index f072a75bf3..e4d89b9c13 100644 --- a/crates/engine/src/cmd/swatchlib.rs +++ b/crates/engine/src/cmd/swatchlib.rs @@ -17,7 +17,7 @@ use vectorcraft_color::swatch::REGISTRATION; use vectorcraft_color::{Paint, Swatch, SwatchGroup, SwatchLibrary, default_swatches}; use vectorcraft_doc::pattern::pattern_paint; -use super::fileio::{create_dir, extension, read_file, write_file, write_new_file}; +use super::fileio::{create_dir, extension, read_file, read_file_head, write_file, write_new_file}; use super::menucmds::squash; use super::package::free_name; use super::patternlib; @@ -76,7 +76,7 @@ pub fn specs() -> Vec { "Other Library…", ["Window", "Swatch Libraries"], None, - "{path? | data?: file text | dataBase64?, name?: file name (default: the path's)} load a .vcswatches, .gpl, .ase (swatch exchange) or .acb (color book, read only) library, or the swatches of any document VectorCraft opens (see document.formats), such as a .ai or .eps swatch library, for the library panel (Window → Swatch Libraries lists it until the app quits; a file of the user library folder, or a file with the same extension and bytes as one there, opens as that User Defined library). A document's colors, tints, gradients and pattern swatches come in, in its order and color groups; swatch.library.add brings a pattern swatch's pattern with it. A document with no swatches is an error, and so is a .ai, .eps or PostScript file whose swatches are only the default ones (it has no palette of its own) → {library: id, name, count}", + "{path? | data?: file text | dataBase64?, name?: file name (default: the path's)} load a .vcswatches, .gpl, .ase (swatch exchange) or .acb (color book, read only) library, or the swatches of any document VectorCraft opens (see document.formats), such as a .ai or .eps swatch library, for the library panel (Window → Swatch Libraries lists it until the app quits; a file of the user library folder, or a file with the same extension and bytes as one there, opens as that User Defined library). A document's colors, tints, gradients and pattern swatches come in, in its order and color groups; swatch.library.add brings a pattern swatch's pattern with it. A document's graph designs are offered by Object › Graph › Column… and Marker… (graph.column, graph.marker and graph.design take the library's id) until the app quits. A document with no swatches is an error, and so is a .ai, .eps or PostScript file whose swatches are only the default ones (it has no palette of its own), unless it has graph designs, which then load with no swatches. A file larger than 256 MB is refused before it is read → {library: id, name, count, graphDesigns: the document's graph designs (0 for a library file)}", always, load ), @@ -92,6 +92,45 @@ pub fn specs() -> Vec { ] } +/// The graph designs of the documents Other Library… loaded (`swatch.library.load`), which the +/// Graph Column and Graph Marker dialogs offer besides the document's own; not saved. +#[derive(Clone, Debug, Default)] +pub struct DesignLibraries { + libs: Vec, +} + +/// A document loaded as a swatch library that holds graph designs ([`DesignLibraries`]). +#[derive(Clone, Debug)] +pub struct DesignLibrary { + /// The id `swatch.library.load` gave the swatch library. A User Defined copy of it + /// (`swatch.library.copyToUser`) holds the swatches alone, so the designs stay under this id. + pub id: String, + pub name: String, + /// The designs and the resources their art uses. + pub doc: Arc, +} + +impl DesignLibraries { + /// The libraries, in the order they were loaded. + pub fn iter(&self) -> impl Iterator { + self.libs.iter() + } + + /// The library loaded as swatch library `id`. + pub fn get(&self, id: &str) -> Option<&DesignLibrary> { + self.libs.iter().find(|l| l.id == id) + } + + /// Keep `doc`'s graph designs as library `id` named `name`, in place of the ones loaded as `id` + /// before; with no designs, `id` no longer has any. + fn set(&mut self, id: &str, name: &str, doc: Option) { + self.libs.retain(|l| l.id != id); + if let Some(doc) = doc { + self.libs.push(DesignLibrary { id: id.to_string(), name: name.to_string(), doc: Arc::new(doc) }); + } + } +} + /// The libraries beyond the built-in ones: User Defined (the library files in the user library /// folder, as last scanned) and loaded ones (`swatch.library.load`). Graphic style libraries use /// the same with [`vectorcraft_doc::StyleLibrary`] ([`super::stylelib`]). @@ -354,12 +393,32 @@ impl Libraries { /// or a file with the same extension and bytes as one there, is that User Defined library; /// others are listed as loaded until the app quits. pub(crate) fn load(&mut self, p: &Value, cmd: &str, parse: impl FnOnce(&[u8], &str) -> Result) -> Result<(LibraryInfo, Arc)> { + self.load_within(p, cmd, None, parse) + } + + /// [`Self::load`], with a file at `path` read up to `max` bytes and refused when it is longer. + pub(crate) fn load_within( + &mut self, + p: &Value, + cmd: &str, + max: Option, + parse: impl FnOnce(&[u8], &str) -> Result, + ) -> Result<(LibraryInfo, Arc)> { let path = text_param(p, "path", cmd)?; let data = text_param(p, "data", cmd)?; let data_base64 = text_param(p, "dataBase64", cmd)?; let name = text_param(p, "name", cmd)?; let bytes = match (path, data, data_base64) { - (Some(path), ..) => read_file(path)?, + (Some(path), ..) => match max { + Some(max) => { + let bytes = read_file_head(path, max.saturating_add(1))?; + if bytes.len() > max { + return Err(bad(cmd, too_big_message(max))); + } + bytes + } + None => read_file(path)?, + }, (None, Some(text), _) => text.as_bytes().to_vec(), (None, None, Some(b64)) => vectorcraft_format::base64_decode(b64).ok_or_else(|| bad(cmd, "bad dataBase64"))?, _ => return Err(bad(cmd, "give `path`, `data` or `dataBase64`")), @@ -777,12 +836,40 @@ fn save(s: &mut Session, p: &Value) -> Result { Ok(out) } +/// The error for a library file larger than `max` bytes. +fn too_big_message(max: usize) -> String { + format!("the file is larger than {} MB", max >> 20) +} + +/// Whether the library `p` gives (`path`, `data` or `dataBase64`) is larger than `max` bytes, +/// checked before the file is read, copied or decoded. +pub(crate) fn library_too_big(p: &Value, cmd: &str, max: usize) -> Result { + Ok(match text_param(p, "path", cmd)? { + Some(path) => super::fileio::file_stamp(path).is_some_and(|(len, _)| len > max as u64), + None => match text_param(p, "data", cmd)? { + Some(text) => text.len() > max, + // Base64 holds 3 bytes in every 4 characters (padding and white space hold none). + None => { + text_param(p, "dataBase64", cmd)?.is_some_and(|b| b.bytes().filter(|c| *c != b'=' && !c.is_ascii_whitespace()).count() * 3 / 4 > max) + } + }, + }) +} + fn load(s: &mut Session, p: &Value) -> Result { const C: &str = "swatch.library.load"; + let max = super::place::document::MAX_FILE; + if library_too_big(p, C, max)? { + return Err(bad(C, too_big_message(max))); + } + let mut designs = None; // The document a library with pattern swatches was read from, which holds their patterns. let mut patterns = None; - let (info, lib) = s.swatch_libraries.load(p, C, |bytes, file| { - // A library file, or a document whose swatches become the library. + // The file is read no further than the limit, so a file that grew since it was checked is + // refused too. + let (info, lib) = s.swatch_libraries.load_within(p, C, Some(max), |bytes, file| { + // A library file, or a document whose swatches become the library and whose graph + // designs the Graph Column and Graph Marker dialogs offer. if palette_io::sniff_bytes(bytes) { return palette_io::read_bytes(bytes, stem(file)).map_err(|e| bad(C, e)); } @@ -792,10 +879,17 @@ fn load(s: &mut Session, p: &Value) -> Result { } // A `.ai`, EPS or PostScript file without a palette of its own opens with the default swatches. let defaults = matches!(loaded.format.id, "ai" | "ait" | "eps" | "ps") && has_only_default_swatches(&loaded.doc); - let lib = document_library(&loaded.doc, &[], stem(file).to_string(), true, C)?; + let mut lib = document_library(&loaded.doc, &[], stem(file).to_string(), true, C)?; + let doc_designs = super::clipboard::resources::graph_design_library(&loaded.doc); if defaults || lib.is_empty() { - return Err(bad(C, format!("`{file}` has no swatches of its own"))); + // A document with graph designs loads for them, with no swatches. + if doc_designs.is_none() { + return Err(bad(C, format!("`{file}` has no swatches of its own"))); + } + lib.swatches.clear(); + lib.groups.clear(); } + designs = doc_designs; if lib.iter().any(|w| matches!(w.paint, Paint::Pattern { .. })) { patterns = Some(Arc::new(loaded.doc)); } @@ -804,7 +898,9 @@ fn load(s: &mut Session, p: &Value) -> Result { if info.category == "loaded" { s.swatch_libraries.set_pattern_doc(&info.id, patterns); } - Ok(json!({"library": shown_library_id(s, &info.id), "name": info.name, "count": lib.len()})) + let count = designs.as_ref().map_or(0, |d| d.graph_designs.len()); + s.graph_design_libraries.set(&info.id, &info.name, designs); + Ok(json!({"library": shown_library_id(s, &info.id), "name": info.name, "count": lib.len(), "graphDesigns": count})) } /// `d`'s swatches and color groups are exactly the default ones of a color mode, as a new diff --git a/crates/engine/src/cmd/symboledit.rs b/crates/engine/src/cmd/symboledit.rs index a413631bb3..3b5d7cdf48 100644 --- a/crates/engine/src/cmd/symboledit.rs +++ b/crates/engine/src/cmd/symboledit.rs @@ -424,6 +424,19 @@ fn each_changed_instance(n: &mut Node, name: &str, f: &mut dyn FnMut(&mut Vec) { + let Some(new) = d.symbols.iter().find(|s| s.name == name).map(|s| s.art.clone()) else { return }; + let parts = |art: &Arc| match (&art.kind, art.children()) { + (NodeKind::Group { .. }, Some(ch)) => (ch.to_vec(), true), + _ => (vec![art.clone()], false), + }; + let (old, new) = (parts(old), parts(&new)); + follow_objects(d, name, (&old.0, old.1), (&new.0, new.1)); +} + /// Each instance's appearance changes to objects of symbol `name`'s art follow those objects /// through an edit of the editing layer (see [`follow_paths`]), and keep only the changes the art /// still draws ([`fit_parts`]). That covers the instances on the layers and in the art of the diff --git a/crates/engine/src/cmd/typecmd.rs b/crates/engine/src/cmd/typecmd.rs index f50a2c7364..185baf734f 100644 --- a/crates/engine/src/cmd/typecmd.rs +++ b/crates/engine/src/cmd/typecmd.rs @@ -122,7 +122,7 @@ pub fn specs() -> Vec { "Move Type Path Handle", [], None, - "{id, subpath?, anchor, which: \"in\"|\"out\", x, y, independent?: bool} move a direction handle of an anchor of type on a path's path to (x, y), as path.setHandle moves a path's (independent: that side only, the anchor becomes a corner); the start and end brackets keep their fractions of the path and the text reflows along it (what Direct Selection does dragging a handle of the path); no undo step when the handle is already there and the path does not change", + "{id, subpath?, anchor, which: \"in\"|\"out\", x, y, independent?: bool, symmetric?: bool} move a direction handle of an anchor of type on a path's path to (x, y), as path.setHandle moves a path's (independent: that side only, the anchor becomes a corner; symmetric: mirror the other handle about the anchor without changing its kind, except at an open end of the path; independent and symmetric cannot both be true; both default false); the start and end brackets keep their fractions of the path and the text reflows along it (what Direct Selection does dragging a handle of the path); no undo step when the handle is already there and the path does not change", has_doc, set_path_handle ), @@ -1449,6 +1449,10 @@ fn set_path_handle(s: &mut Session, p: &Value) -> Result { let out = super::object::choice(p, C, "which", &["in", "out"])? != Some("in"); let pos = vectorcraft_geom::Point::new(f64_req(p, "x", C)?, f64_req(p, "y", C)?); let independent = switch_or(p, "independent", false, C)?; + let symmetric = switch_or(p, "symmetric", false, C)?; + if symmetric && independent { + return Err(bad(C, "`independent` and `symmetric` cannot both be true")); + } let node = s.doc()?.doc.node(id); let on_path = matches!(node.map(|n| &n.kind), Some(NodeKind::Text(t)) if matches!(t.kind, vectorcraft_doc::TextKind::OnPath { .. })); if !on_path || node.is_some_and(|n| n.extras().perspective.is_some()) { @@ -1461,7 +1465,7 @@ fn set_path_handle(s: &mut Session, p: &Value) -> Result { let within = |t: &TextObject| { t.type_path().and_then(|p| p.bounds()).is_some_and(|b| [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.abs() <= crate::MAX_COORD)) }; - if !(t.set_path_handle((si, ai), out, pos, independent) && within(t)) { + if !(t.set_path_handle_with_symmetry((si, ai), out, pos, independent, symmetric) && within(t)) { t.kind = before; return Err(bad(C, "no such path anchor, or the path would reach past the canvas")); } diff --git a/crates/engine/src/cmd/typemenu.rs b/crates/engine/src/cmd/typemenu.rs index e9c316157f..b66a50bc19 100644 --- a/crates/engine/src/cmd/typemenu.rs +++ b/crates/engine/src/cmd/typemenu.rs @@ -634,34 +634,40 @@ fn to_area(s: &mut Session, p: &Value) -> Result { if !matches!(t.kind, TextKind::Point) { continue; } - let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t); - // The frame is worked out in line space, where the lines are; vertical type turns it - // into text space with the lines. - let text_bounds = if lay.bounds.area() > 0.0 { lay.bounds } else { t.estimate_bounds() }; - let mut b = lay.line_xf.inverse().transform_rect_bbox(text_bounds); - // Across, the frame spans the lines as they are aligned: from their starts to their ends - // without the tracking after their last characters (`LineInfo::trailing`), not to the - // ink, which tracking can pull past an advance. Area type aligns them alike. - let (x0, x1) = lay.lines.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(a, z), l| (a.min(l.x0), z.max(l.x1 - l.trailing))); - if x0.is_finite() && x1.is_finite() && x0 <= x1 { - (b.x0, b.x1) = (x0, x1); - } - // Line breaking counts that tracking: the slack holds the most of it. - let trailing = lay.lines.iter().map(|l| l.trailing).filter(|t| t.is_finite()).fold(0.0, f64::max); - let size = t.first_style().size; - // A little slack on the right so the text doesn't rewrap. - let top = lay.lines.first().map(|l| l.baseline - l.ascent).unwrap_or(b.y0).min(b.y0); - let slack = size * 0.5 + trailing; - let (sl, sr) = slack_sides(t.para_at(0).justify, lay.lines.first().is_some_and(|l| l.rtl), slack); - let frame = lay.line_xf.transform_rect_bbox(Rect::new(b.x0 - sl, top, b.x1 + sr, b.y1.max(top + 1.0))); - t.kind = TextKind::Area { frame: shapes::rectangle(frame) }; - refresh_bounds(t); + point_to_area(t); } Ok(()) })?; Ok(ids_json(&ids)) } +/// Point type `t` turned into area type in a frame around its lines, with a little slack where its +/// alignment leaves room, so the text stays where it is and does not rewrap. +pub(super) fn point_to_area(t: &mut TextObject) { + let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t); + // The frame is worked out in line space, where the lines are; vertical type turns it + // into text space with the lines. + let text_bounds = if lay.bounds.area() > 0.0 { lay.bounds } else { t.estimate_bounds() }; + let mut b = lay.line_xf.inverse().transform_rect_bbox(text_bounds); + // Across, the frame spans the lines as they are aligned: from their starts to their ends + // without the tracking after their last characters (`LineInfo::trailing`), not to the + // ink, which tracking can pull past an advance. Area type aligns them alike. + let (x0, x1) = lay.lines.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(a, z), l| (a.min(l.x0), z.max(l.x1 - l.trailing))); + if x0.is_finite() && x1.is_finite() && x0 <= x1 { + (b.x0, b.x1) = (x0, x1); + } + // Line breaking counts that tracking: the slack holds the most of it. + let trailing = lay.lines.iter().map(|l| l.trailing).filter(|t| t.is_finite()).fold(0.0, f64::max); + let size = t.first_style().size; + // A little slack on the right so the text doesn't rewrap. + let top = lay.lines.first().map(|l| l.baseline - l.ascent).unwrap_or(b.y0).min(b.y0); + let slack = size * 0.5 + trailing; + let (sl, sr) = slack_sides(t.para_at(0).justify, lay.lines.first().is_some_and(|l| l.rtl), slack); + let frame = lay.line_xf.transform_rect_bbox(Rect::new(b.x0 - sl, top, b.x1 + sr, b.y1.max(top + 1.0))); + t.kind = TextKind::Area { frame: shapes::rectangle(frame) }; + refresh_bounds(t); +} + /// How `slack` added to point type's lines in a frame is shared before and after them: where the /// alignment leaves room, so the text doesn't move or rewrap. fn slack_sides(justify: Justify, rtl: bool, slack: f64) -> (f64, f64) { diff --git a/crates/engine/src/cmd/xform.rs b/crates/engine/src/cmd/xform.rs index c592e552a4..ba8f7e94ab 100644 --- a/crates/engine/src/cmd/xform.rs +++ b/crates/engine/src/cmd/xform.rs @@ -21,7 +21,7 @@ pub fn specs() -> Vec { "Free Distort", [], None, - "{corners: [[x,y]×4] (TL, TR, BR, BL), from?: [x0,y0,x1,y1] (default: selection bounds), angle?: degrees (counter-clockwise; `from`, or the selection bounds, is then a box in the frame turned by it, as a rotated bounding box is; default 0), ids?} projective warp of anchors and handles; a linked opacity mask's art is warped with its object, an unlinked one stays; each warped object's bounding box (the objects inside groups and the art of linked masks too) turns as the warp turns the art at its center (object.resetBoundingBox squares it again); corners where the box already stands change nothing and add no undo step", + "{corners: [[x,y]×4] (TL, TR, BR, BL), from?: [x0,y0,x1,y1] (default: selection bounds), angle?: degrees (counter-clockwise; `from`, or the selection bounds, is then a box in the frame turned by it, as a rotated bounding box is; default 0), ids?} projective warp of anchors and handles; an image's four corners go exactly where the warp takes them and its pixels are drawn in perspective between them (an error, and nothing changes, when an image's corners would fold over, fall on one line, cross the warp's horizon or lie too close together for a perspective map); a linked opacity mask's art is warped with its object, an unlinked one stays; each warped object's bounding box (the objects inside groups and the art of linked masks too) turns as the warp turns the art at its center (object.resetBoundingBox squares it again); corners where the box already stands change nothing and add no undo step", has_doc, distort ), @@ -86,6 +86,15 @@ impl Projective { Self { m: [a, b, p0.x, d, e, p0.y, g, h], src, pre: bx.to_doc().inverse() } } + /// Whether `p` maps in front of the warp's horizon, on the side the box's own corners are. + fn in_front(&self, p: Point) -> bool { + let [.., g, h] = self.m; + let p = self.pre * p; + let u = if self.src.width().abs() > 1e-12 { (p.x - self.src.x0) / self.src.width() } else { 0.0 }; + let v = if self.src.height().abs() > 1e-12 { (p.y - self.src.y0) / self.src.height() } else { 0.0 }; + g * u + h * v + 1.0 > 1e-9 + } + pub fn apply(&self, p: Point) -> Point { let [a, b, c, d, e, f, g, h] = self.m; let p = self.pre * p; @@ -138,6 +147,15 @@ fn warp_node(n: &mut Node, pr: &Projective) -> Option { // A clip group is bounded by its clip path. NodeKind::Group { children, clip: true } => warp_children(children, pr, |i| i == 0), NodeKind::Group { children, .. } | NodeKind::Compound { children, .. } => warp_children(children, pr, |i| i >= skip), + // An image's corners follow the warp exactly ([`Node::set_image_corners`]); [`distort`] + // has checked that they stay convex. + NodeKind::Image(_) => { + let b = n.geometric_bounds(); + if let Some(q) = n.image_corners() { + let _ = n.set_image_corners(q.map(|p| pr.apply(p))); + } + b + } _ => { // No editable points: the affine approximation (which maps the gradients too). let b = n.geometric_bounds(); @@ -157,6 +175,21 @@ fn warp_node(n: &mut Node, pr: &Projective) -> Option { before } +/// Whether the warp from `src` to `q` ([`Projective::from_box`]) takes the corners of `src` to `q`, +/// within a millionth of `q`'s shortest side plus the rounding error of coordinates as far from `q`'s +/// first corner as the others. The warp is solved and measured with `src` and `q` moved to the +/// origin, so coordinates far from it do not widen the allowance. +fn reaches_corners(src: OrientedBox, q: [Point; 4]) -> bool { + let origin = q[0].to_vec2(); + let q = q.map(|p| p - origin); + let src = OrientedBox { rect: src.rect - src.rect.origin().to_vec2(), ..src }; + let pr = Projective::from_box(src, q); + let side = (0..4).map(|i| q[i].distance(q[(i + 1) % 4])).fold(f64::INFINITY, f64::min); + let far = q.iter().map(|p| p.x.abs().max(p.y.abs())).fold(0.0, f64::max); + let tol = side * 1e-6 + far * 1e-12; + side.is_finite() && side > 0.0 && src.corners().iter().zip(q).all(|(c, want)| pr.apply(*c).distance(want) <= tol) +} + /// Warps each of `children` and returns the union of the pre-warp bounds of those `counts` picks /// by index. fn warp_children(children: &mut [Arc], pr: &Projective, counts: impl Fn(usize) -> bool) -> Option { @@ -166,6 +199,76 @@ fn warp_children(children: &mut [Arc], pr: &Projective, counts: impl Fn(us }) } +/// The first image in `n` (its children and the art of linked opacity masks, as [`warp_node`] +/// reaches them) whose corners `pr` would fold, collapse or carry past the warp's horizon, with +/// why. +fn unwarpable_image(n: &Node, pr: &Projective) -> Option<(vectorcraft_doc::NodeId, Unwarpable)> { + if let (Some(q), NodeKind::Image(im)) = (n.image_corners(), &n.kind) { + if !q.iter().all(|p| pr.in_front(*p)) { + return Some((n.id, Unwarpable::Horizon)); + } + if let Err(e) = vectorcraft_doc::image_quad::check_for(im, &q.map(|p| pr.apply(p))) { + return Some(( + n.id, + match e { + vectorcraft_doc::image_quad::QuadError::NotFinite | vectorcraft_doc::image_quad::QuadError::NotConvex => Unwarpable::NotConvex, + vectorcraft_doc::image_quad::QuadError::TooNarrow => Unwarpable::TooNarrow, + }, + )); + } + } + warped_parts(n).into_iter().find_map(|c| unwarpable_image(c, pr)) +} + +/// The first image in `n` that [`warp_node`] reaches (its children and the art of linked opacity +/// masks). +fn first_image(n: &Node) -> Option { + if matches!(n.kind, NodeKind::Image(_)) { + return Some(n.id); + } + warped_parts(n).into_iter().find_map(first_image) +} + +/// The objects inside `n` that [`warp_node`] warps point by point: the children of layers, groups +/// and compound paths, and the art of a linked opacity mask on those, paths and images. Other +/// objects (blends, envelopes, repeats and the rest) take the warp's affine approximation whole. +fn warped_parts(n: &Node) -> Vec<&Node> { + let inside = matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. } | NodeKind::Compound { .. }); + let mask_too = inside || matches!(n.kind, NodeKind::Path { .. } | NodeKind::Image(_)); + let children = n.children().filter(|_| inside).into_iter().flatten().map(|c| &**c); + let mask = n.extras().mask.as_deref().filter(|m| mask_too && m.linked).map(|m| &*m.art); + children.chain(mask).collect() +} + +/// The error of `command` on image `id`, which is distorted (Perspective Distort or Free Distort) +/// in a way the command cannot keep. +pub(crate) fn distorted_image_error(command: &str, id: vectorcraft_doc::NodeId) -> EngineError { + bad(command, format!("object {} is an image changed by Perspective Distort or Free Distort, which this command does not work on", id.0)) +} + +/// Why an image cannot follow the corners of a distort. +#[derive(Clone, Copy)] +enum Unwarpable { + /// Its corners would fold over, meet or fall on one line. + NotConvex, + /// A corner would cross the warp's horizon. + Horizon, + /// Its corners would be too close together for a perspective map to place them. + TooNarrow, +} + +/// The error of `object.distort` when image `id` cannot follow its corners. +fn unwarpable_error(id: vectorcraft_doc::NodeId, why: Unwarpable) -> EngineError { + const C: &str = "object.distort"; + match why { + Unwarpable::NotConvex => bad(C, format!("image {} cannot be distorted this way: its corners would not make a convex shape", id.0)), + Unwarpable::Horizon => bad(C, format!("image {} cannot be distorted this way: its corners would cross the warp's horizon", id.0)), + Unwarpable::TooNarrow => { + bad(C, format!("image {} cannot be distorted this way: its corners would be too close together for a perspective map", id.0)) + } + } +} + fn distort(s: &mut Session, p: &Value) -> Result { const C: &str = "object.distort"; // All four corners or nothing, each exactly [x, y]: nothing malformed is left out. @@ -208,6 +311,26 @@ fn distort(s: &mut Session, p: &Value) -> Result { return Ok(ids_json); } let pr = Projective::from_box(src, [tl, tr, br, bl]); + // An image's corners follow the handles exactly, so they must stay a convex shape: nothing + // changes when one would not. + let doc = &s.doc()?.doc; + // Corners that do not make a convex shape give no perspective map (the warp falls back to an + // affine one), so an image cannot follow them. + if vectorcraft_doc::image_quad::check(&[tl, tr, br, bl]).is_err() + && let Some(id) = ids.iter().filter_map(|id| doc.node(*id)).find_map(first_image) + { + return Err(unwarpable_error(id, Unwarpable::NotConvex)); + } + // Corners so close together that the map falls back to an affine one: the box's corners do + // not reach the handles, so an image cannot follow them either. + if !reaches_corners(src, [tl, tr, br, bl]) + && let Some(id) = ids.iter().filter_map(|id| doc.node(*id)).find_map(first_image) + { + return Err(unwarpable_error(id, Unwarpable::TooNarrow)); + } + if let Some((id, why)) = ids.iter().filter_map(|id| doc.node(*id)).find_map(|n| unwarpable_image(n, &pr)) { + return Err(unwarpable_error(id, why)); + } s.edit("Free Distort", |d, _| { for id in &ids { if let Some(n) = d.node_mut(*id) { @@ -233,6 +356,7 @@ pub struct FillAttrs { impl FillAttrs { pub const ALL: Self = Self { color: true, transparency: true, overprint: true }; + pub const NONE: Self = Self { color: false, transparency: false, overprint: false }; } impl Default for FillAttrs { @@ -260,6 +384,8 @@ pub struct StrokeAttrs { impl StrokeAttrs { pub const ALL: Self = Self { color: true, transparency: true, overprint: true, weight: true, cap: true, join: true, miter: true, dash: true }; + pub const NONE: Self = + Self { color: false, transparency: false, overprint: false, weight: false, cap: false, join: false, miter: false, dash: false }; } impl Default for StrokeAttrs { diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 1e9ef6d699..e2e6430f1e 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -74,6 +74,10 @@ pub struct Session { /// While Cmd lends `tool` (a selection tool) for a drag: the tool it was lent to, which comes /// back as it was at the release ([`Session::pointer`]). pub(crate) lender: Option>, + /// Set while tool actions that end by switching back to the Live Paint Bucket are applied (the + /// Eyedropper's sample into a stop of the bucket's gradient): their paint commands change the + /// colors the bucket paints with ([`Session::bucket_paints`]). + pub(crate) back_to_bucket: bool, /// Pointer and key input that came while the tool computed an edit on another thread, each with /// its number and view, made in order once the edit is applied. held_input: std::collections::VecDeque<(u64, tooling::HeldInput, ViewInfo)>, @@ -149,6 +153,9 @@ pub struct Session { pub(crate) pending_paint: Option, /// User Defined and loaded swatch libraries (Window → Swatch Libraries); not saved. pub swatch_libraries: cmd::swatchlib::Libraries, + /// The graph designs of the documents loaded as swatch libraries (Window → Swatch Libraries → + /// Other Library…), for the Graph Column and Graph Marker dialogs; not saved. + pub graph_design_libraries: cmd::swatchlib::DesignLibraries, /// The selected freeform gradient point (`paint.freeform.selectPoint`) and whose gradient it /// was selected on: read it with [`Session::selected_freeform_point`]. pub(crate) freeform_point: Option<(usize, cmd::gradient::StopOwner)>, @@ -160,6 +167,8 @@ pub struct Session { pub brush_libraries: cmd::brushlib::Libraries, /// The custom arrowheads of the arrowheads file (`stroke.arrowheads.*`); none without one. pub arrowheads: cmd::arrowheads::Arrowheads, + /// The custom bevels of the bevels file (`threeD.bevels.*`); none without one. + pub bevels: cmd::bevels::Bevels, /// The id each loaded library outside a request's read roots has been shown under, by its own id /// ([`cmd::swatchlib::concealed_library_ids`]), kept for the session. shown_library_ids: std::sync::Mutex>, @@ -329,6 +338,9 @@ pub struct Session { /// The id and persistent options of the tool when the press under way began, which a dropped /// press puts back ([`Session::drop_tool_press`]). pub(crate) press_options: Option<(String, serde_json::Map)>, + /// An option of the active tool was set during the press under way, which stored all of its + /// options, so a dropped press stores the options it puts back. + pub(crate) press_options_stored: bool, /// The engine saves the selection and active layer before a Type press and restores them if it drops. pub(crate) press_type_selection: Option<(Selection, Option)>, /// The freeform gradient point selected once the tool took the press under way, which a diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index 0bf8203463..2e0d0f9fe4 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -283,6 +283,11 @@ pub struct Prefs { pub low_res_proxy_eps: bool, pub anti_aliased_bitmaps: bool, pub update_links: String, + /// PDF Text: what the text of a PDF, `.ai` or `.ait` file opened or placed from the app + /// becomes when the open or place does not say (`text`: editable type in the file's fonts; + /// `outlines`: the glyph outlines the file draws). The Import PDF dialog starts from it and + /// keeps the choice it confirms. + pub pdf_text_as: String, // Clipboard Handling pub copy_as_svg: bool, pub copy_as_pdf: bool, @@ -589,6 +594,7 @@ impl Default for Prefs { low_res_proxy_eps: false, anti_aliased_bitmaps: false, update_links: s("askWhenModified"), + pdf_text_as: s("text"), copy_as_svg: true, copy_as_pdf: false, copy_aicb: false, diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index c93239442d..61dbdb4491 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -55,6 +55,7 @@ impl Session { histories_seen: None, tool: vectorcraft_tools::create("selection"), lender: None, + back_to_bucket: false, held_input: Default::default(), input_count: 0, edit_started_by: None, @@ -84,11 +85,13 @@ impl Session { recent_colors: vec![], pending_paint: None, swatch_libraries: Default::default(), + graph_design_libraries: Default::default(), freeform_point: None, style_libraries: Default::default(), symbol_libraries: Default::default(), brush_libraries: Default::default(), arrowheads: Default::default(), + bevels: Default::default(), shown_library_ids: Default::default(), libraries: Default::default(), pdf_preset_dir: None, @@ -137,6 +140,7 @@ impl Session { plane_widget_press: false, pointer_held: false, press_options: None, + press_options_stored: false, press_type_selection: None, press_point: None, ruler_guide: None, diff --git a/crates/engine/src/session/edit.rs b/crates/engine/src/session/edit.rs index ea697a0525..bbd20fa5bb 100644 --- a/crates/engine/src/session/edit.rs +++ b/crates/engine/src/session/edit.rs @@ -323,7 +323,7 @@ impl Session { } // While the Live Paint Bucket is active, paint previews change only the bucket's colors, so // each preview starts from the colors the interaction began with. - let bucket = self.tool_id() == cmd::LIVE_PAINT_BUCKET; + let bucket = self.bucket_paints(); let (paint, restore_paint) = { let menu = self.menu.clone(); let st = self.doc_mut()?; @@ -485,7 +485,7 @@ impl Session { self.pending_paint = None; // While the Live Paint Bucket is active, a previewed color is the bucket's color, which the // cancel puts back as well. - let bucket = self.tool_id() == cmd::LIVE_PAINT_BUCKET; + let bucket = self.bucket_paints(); if let Some(paint) = self .active() .and_then(|st| st.interaction.as_ref()) diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 0b785456a2..cbebd7d489 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -15,6 +15,7 @@ mod assets; mod assets_3d; mod attributes; mod bboxrotate; +mod bevels; mod blendfidelity; mod blendopts; mod blendspine; @@ -202,6 +203,7 @@ mod symbol_nine_slice; mod symbolbounds; mod symboledit; mod symbolism_options; +mod symbolism_shift; mod symbollib; mod tangent_line; mod targeting; diff --git a/crates/engine/src/tests/bevels.rs b/crates/engine/src/tests/bevels.rs new file mode 100644 index 0000000000..301ed61905 --- /dev/null +++ b/crates/engine/src/tests/bevels.rs @@ -0,0 +1,394 @@ +//! Custom bevels (`cmd/bevels.rs`): bevels read from the bevels file's symbols, listed, set on +//! Extrude & Bevel and Extrude & Bevel (Classic) by name, reloaded when the file is saved, and kept +//! with the documents that use them. + +use std::sync::Arc; + +use serde_json::{Value, json}; +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::{Appearance, Document, Node, Symbol}; +use vectorcraft_geom::{Anchor, PathData, Point, SubPath}; +use vectorcraft_render::effects; + +use crate::cmd::bevels::{self, bevels_of}; +use crate::*; + +fn line(pts: &[(f64, f64)], closed: bool) -> Node { + let pts: Vec = pts.iter().map(|&(x, y)| Point::new(x, y)).collect(); + Node::path(NodeId(0), PathData::single(SubPath::polyline(&pts, closed)), Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0)) +} + +fn add_symbol(d: &mut Document, name: &str, art: Node) { + let art = d.reid(&art); + d.symbols.push(Symbol { name: name.into(), art: Arc::new(art), dynamic: false }); +} + +/// A folder of its own for test `name`, emptied. +fn folder(name: &str) -> std::path::PathBuf { + let dir = std::env::temp_dir().join(format!("vectorcraft-bevels-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +fn close(a: (f64, f64), b: (f64, f64)) -> bool { + (a.0 - b.0).abs() < 1e-9 && (a.1 - b.1).abs() < 1e-9 +} + +#[test] +fn each_open_path_symbol_is_a_bevel_from_its_first_anchor_to_its_last() { + let mut d = Document::new(100.0, 100.0); + add_symbol(&mut d, "Notch", line(&[(0.0, 0.0), (20.0, 60.0), (70.0, 40.0), (100.0, 100.0)], false)); + // The same path mirrored across the page and drawn from the other side gives the same points. + add_symbol(&mut d, "Mirrored", line(&[(300.0, 50.0), (280.0, 110.0), (230.0, 90.0), (200.0, 150.0)], false)); + // In a group of one, at another size. + let small = line(&[(0.0, 0.0), (2.0, 6.0), (7.0, 4.0), (10.0, 10.0)], false); + add_symbol(&mut d, "Grouped", Node::group(NodeId(0), vec![Arc::new(small)])); + // Points past the ends are held to them. + add_symbol(&mut d, "Overshoot", line(&[(0.0, 0.0), (-20.0, 50.0), (100.0, 120.0), (100.0, 100.0)], false)); + add_symbol(&mut d, "Closed", line(&[(0.0, 0.0), (10.0, 0.0), (10.0, 10.0)], true)); + let two = Node::group(NodeId(0), vec![Arc::new(line(&[(0.0, 0.0), (1.0, 1.0)], false)), Arc::new(line(&[(0.0, 0.0), (1.0, 1.0)], false))]); + add_symbol(&mut d, "Two paths", two); + add_symbol(&mut d, "Upright", line(&[(0.0, 0.0), (5.0, 50.0), (0.0, 100.0)], false)); + let dense: Vec<(f64, f64)> = (0..=bevels::MAX_ANCHORS).map(|i| (i as f64, i as f64)).collect(); + add_symbol(&mut d, "Dense", line(&dense, false)); + add_symbol(&mut d, "Notch", line(&[(0.0, 0.0), (1.0, 1.0)], false)); + let read = bevels_of(&d); + let names: Vec<&str> = read.bevels.iter().map(|b| b.name.as_str()).collect(); + assert_eq!(names, ["Notch", "Mirrored", "Grouped", "Overshoot"]); + let notch = [(0.0, 0.0), (0.2, 0.6), (0.7, 0.4), (1.0, 1.0)]; + for b in &read.bevels[..3] { + assert_eq!(b.points.len(), 4, "{}", b.name); + assert!(b.points.iter().zip(notch).all(|(&a, b)| close(a, b)), "{}: {:?}", b.name, b.points); + } + assert!(close(read.bevels[3].points[1], (0.0, 0.5)) && close(read.bevels[3].points[2], (1.0, 1.0)), "{:?}", read.bevels[3].points); + let skipped: Vec<(&str, &str)> = read.skipped.iter().map(|(n, r)| (n.as_str(), r.as_str())).collect(); + assert_eq!( + skipped, + [ + ("Closed", "its art is not one open path"), + ("Two paths", "its art is not one open path"), + ("Upright", "its ends are not apart both across and down"), + ("Dense", "its path has too many anchors for a bevel"), + ("Notch", "another symbol has this name"), + ] + ); +} + +/// A curve is cut into straight lines, and a path of many points keeps the ones that matter, at +/// most 64 in all, ends included. +#[test] +fn curves_and_long_paths_fit_in_the_points_a_bevel_holds() { + let mut d = Document::new(100.0, 100.0); + // A quarter circle from (0, 0) to (100, 100), bulging up and right. + let k = 0.5523 * 100.0; + let mut a = Anchor::corner(Point::new(0.0, 0.0)); + a.h_out = Point::new(k, 0.0); + let mut b = Anchor::corner(Point::new(100.0, 100.0)); + b.h_in = Point::new(100.0, 100.0 - k); + let arc = Node::path(NodeId(0), PathData::single(SubPath::new(vec![a, b], false)), Appearance::default()); + add_symbol(&mut d, "Arc", arc); + let wavy: Vec<(f64, f64)> = (0..=3000).map(|i| (i as f64 / 30.0, i as f64 / 30.0 + 5.0 * (i as f64 / 50.0).sin())).collect(); + add_symbol(&mut d, "Wavy", line(&wavy, false)); + let read = bevels_of(&d); + assert!(read.skipped.is_empty(), "{:?}", read.skipped); + for b in &read.bevels { + assert!((3..=effects::BevelProfile::MAX_POINTS).contains(&b.points.len()), "{}: {}", b.name, b.points.len()); + assert!(close(b.points[0], (0.0, 0.0)) && close(*b.points.last().unwrap(), (1.0, 1.0)), "{}", b.name); + assert!(effects::BevelProfile::new(&b.points).is_some(), "{}", b.name); + } + // The arc's points lie on the circle: across first, then down. + let arc = &read.bevels[0]; + assert!(arc.points.iter().all(|&(x, y)| (((x - 0.0).powi(2) + (y - 1.0).powi(2)).sqrt() - 1.0).abs() < 0.01), "{:?}", arc.points); +} + +/// A path of many tall curves, cut into more straight lines than a bevel's path may take, is +/// skipped as too detailed. +#[test] +fn a_path_cut_into_too_many_lines_is_skipped() { + let mut d = Document::new(100.0, 100.0); + let anchors: Vec = (0..4000) + .map(|i| { + let p = Point::new(f64::from(i), f64::from(i) / 4.0); + let swing = if i % 2 == 0 { 1000.0 } else { -1000.0 }; + let mut a = Anchor::corner(p); + a.h_in = Point::new(p.x - 0.5, p.y - swing); + a.h_out = Point::new(p.x + 0.5, p.y + swing); + a + }) + .collect(); + let wild = Node::path(NodeId(0), PathData::single(SubPath::new(anchors, false)), Appearance::default()); + add_symbol(&mut d, "Wild", wild); + let read = bevels_of(&d); + assert!(read.bevels.is_empty()); + assert_eq!(read.skipped, [("Wild".to_string(), "its path is too detailed for a bevel".to_string())]); +} + +/// Simplifying the paths of one file measures at most a fixed number of point-to-line distances: +/// a path that needs more than are left is skipped as too detailed, and a short one still reads. +#[test] +fn simplifying_the_bevels_of_a_file_has_a_work_limit() { + let mut d = Document::new(100.0, 100.0); + let wavy: Vec<(f64, f64)> = (0..=3000).map(|i| (i as f64 / 30.0, i as f64 / 30.0 + 5.0 * (i as f64 / 50.0).sin())).collect(); + add_symbol(&mut d, "Wavy", line(&wavy, false)); + add_symbol(&mut d, "Notch", line(&[(0.0, 0.0), (20.0, 60.0), (70.0, 40.0), (100.0, 100.0)], false)); + let read = bevels::bevels_within(&d, 5_000); + let names: Vec<&str> = read.bevels.iter().map(|b| b.name.as_str()).collect(); + assert_eq!(names, ["Notch"]); + assert_eq!(read.skipped, [("Wavy".to_string(), "its path is too detailed for a bevel".to_string())]); + assert_eq!(bevels_of(&d).bevels.len(), 2); +} + +fn rect(s: &mut Session, x: u32) -> NodeId { + NodeId(s.execute("shape.rectangle", &json!({"x": x, "y": 100, "width": 60, "height": 60})).unwrap()["id"].as_u64().unwrap()) +} + +fn params(s: &Session, id: NodeId) -> Value { + s.doc().unwrap().doc.node(id).unwrap().appearance.effects[0].params.clone() +} + +#[test] +fn the_bevels_file_is_made_opened_and_reloaded_when_saved() { + let dir = folder("edit"); + let file = dir.join(bevels::FILE_NAME).to_string_lossy().to_string(); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + let id = rect(&mut s, 20); + s.attach_bevels_file(file.clone()); + let list = s.execute("threeD.bevels.list", &json!({})).unwrap(); + assert_eq!((list["bevels"].as_array().unwrap().len(), list["file"].as_str()), (0, Some(file.as_str()))); + let apply = json!({"effect": effects::EXTRUDE, "ids": [id.0], "item": null, "params": {"bevel": {"custom": "Example Bevel"}}}); + assert!(s.execute("effect.apply", &apply).unwrap_err().to_string().contains("no custom bevel Example Bevel")); + let r = s.execute("threeD.bevels.edit", &json!({})).unwrap(); + assert_eq!(r["created"], true); + assert_eq!(s.doc().unwrap().path.as_deref(), Some(file.as_str()), "the file is the active document"); + let list = s.execute("threeD.bevels.list", &json!({})).unwrap(); + assert_eq!(list["bevels"][0]["name"], "Example Bevel"); + assert_eq!(list["bevels"][0]["points"].as_array().unwrap().len(), 4); + // A second bevel drawn in the file is listed once the file is saved. + let st = s.doc_mut().unwrap(); + add_symbol(Arc::make_mut(&mut st.doc), "Steps", line(&[(0.0, 0.0), (0.0, 50.0), (50.0, 50.0), (50.0, 100.0), (100.0, 100.0)], false)); + assert_eq!(s.execute("threeD.bevels.list", &json!({})).unwrap()["bevels"].as_array().unwrap().len(), 1); + s.execute("document.save", &json!({})).unwrap(); + let list = s.execute("threeD.bevels.list", &json!({})).unwrap(); + let names: Vec<&str> = list["bevels"].as_array().unwrap().iter().filter_map(|b| b["name"].as_str()).collect(); + assert_eq!(names, ["Example Bevel", "Steps"]); + assert_eq!(s.execute("threeD.bevels.reload", &json!({})).unwrap()["count"], 2); + // Editing again brings the open file to the front, without making it anew. + s.execute("document.activate", &json!({"index": 0})).unwrap(); + assert_eq!(s.execute("threeD.bevels.edit", &json!({})).unwrap()["created"], false); + assert_eq!(s.documents().len(), 2); + // The rectangle takes the bevel with a copy of its points, in both Extrude & Bevels. + s.execute("document.activate", &json!({"index": 0})).unwrap(); + s.execute("effect.apply", &json!({"effect": effects::EXTRUDE, "ids": [id.0], "item": null, "params": {"bevel": {"custom": "Steps"}}})).unwrap(); + let p = params(&s, id); + assert_eq!((p["bevel"].as_str(), p[effects::BEVEL_NAME].as_str()), (Some("custom"), Some("Steps"))); + assert_eq!(p[effects::BEVEL_PROFILE], json!([[0.0, 0.0], [0.0, 0.5], [0.5, 0.5], [0.5, 1.0], [1.0, 1.0]])); + let set = |bevel: Value| json!({"ids": [id.0], "index": 0, "item": null, "params": {"bevel": bevel}}); + s.execute("effect.setParams", &set(json!({"custom": "Example Bevel"}))).unwrap(); + assert_eq!(params(&s, id)[effects::BEVEL_NAME], "Example Bevel"); + for bad in [json!({"custom": 3}), json!({"custom": "Nope"}), json!({"name": "Steps"})] { + let undo = s.doc().unwrap().history.undo.len(); + assert!(s.execute("effect.setParams", &set(bad.clone())).is_err(), "{bad}"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo, "{bad}: no undo step"); + } + let classic = rect(&mut s, 200); + s.execute( + "effect.apply", + &json!({"effect": effects::CLASSIC_EXTRUDE, "ids": [classic.0], "item": null, "params": {"bevel": {"custom": "Steps"}}}), + ) + .unwrap(); + assert_eq!(params(&s, classic)[effects::BEVEL_NAME], "Steps"); + // A built-in shape again draws that shape. + s.execute("effect.setParams", &set(json!("rounded"))).unwrap(); + assert!(matches!(effects::extrude_options(¶ms(&s, id)).bevel.map(|b| b.shape.id()), Some("rounded"))); + let _ = std::fs::remove_dir_all(&dir); +} + +/// `effect.apply` and `effect.setParams` given a custom bevel by name record its points as +/// `savedBevel`, so a replay draws that bevel after the bevels file no longer has it. +#[test] +fn a_replay_draws_the_custom_bevel_the_command_recorded() { + let dir = folder("replay"); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + let id = rect(&mut s, 20); + s.attach_bevels_file(dir.join(bevels::FILE_NAME).to_string_lossy().to_string()); + s.execute("threeD.bevels.edit", &json!({})).unwrap(); + s.execute("document.activate", &json!({"index": 0})).unwrap(); + let apply = json!({"effect": effects::EXTRUDE, "ids": [id.0], "item": null, "params": {"bevel": {"custom": "Example Bevel"}}}); + s.execute("effect.apply", &apply).unwrap(); + let applied = params(&s, id); + let (cmd, recorded) = s.journal.last().unwrap().clone(); + assert_eq!(cmd, "effect.apply"); + assert_eq!(recorded[bevels::SAVED_BEVEL], applied[effects::BEVEL_PROFILE]); + let set = json!({"ids": [id.0], "index": 0, "item": null, "params": {"bevel": {"custom": "Example Bevel"}, "bevelWidth": 9}}); + s.execute("effect.setParams", &set).unwrap(); + let edited = params(&s, id); + let (_, set_recorded) = s.journal.last().unwrap().clone(); + assert_eq!(set_recorded[bevels::SAVED_BEVEL], applied[effects::BEVEL_PROFILE]); + // The bevels file no longer has the bevel: by name it is refused, and the replays draw it. + s.attach_bevels_file(dir.join("Other.vectorcraft").to_string_lossy().to_string()); + assert!(s.execute("effect.apply", &apply).is_err()); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.doc().unwrap().doc.node(id).unwrap().appearance.effects.is_empty()); + s.replay("effect.apply", &recorded).unwrap(); + assert_eq!(params(&s, id), applied); + s.replay("effect.setParams", &set_recorded).unwrap(); + assert_eq!(params(&s, id), edited); + // Points given with the name are used in place of the file's. + let notch = json!([[0.0, 0.0], [0.2, 0.6], [0.7, 0.4], [1.0, 1.0]]); + let mut given = set.clone(); + given["savedBevel"] = notch.clone(); + s.execute("effect.setParams", &given).unwrap(); + assert_eq!((¶ms(&s, id)[effects::BEVEL_PROFILE], ¶ms(&s, id)[effects::BEVEL_NAME]), (¬ch, &json!("Example Bevel"))); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn a_document_keeps_its_custom_bevels_without_the_bevels_file() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 300, "height": 300})).unwrap(); + let id = rect(&mut s, 100); + let notch = json!([[0, 0], [0.2, 0.6], [0.7, 0.4], [1, 1]]); + let custom = json!({"bevel": "custom", "bevelName": "Notch", "bevelProfile": notch, "bevelWidth": 12, "bevelHeight": 12}); + s.execute("effect.apply", &json!({"effect": effects::EXTRUDE, "ids": [id.0], "item": null, "params": custom})).unwrap(); + let ink = |s: &Session| { + vectorcraft_render::Renderer::new().render(&s.doc().unwrap().doc, 300, 300, vectorcraft_geom::Affine::IDENTITY, &Default::default()) + }; + let with_bevel = ink(&s); + // Saved and opened in a session that has no bevels file: the bevel is drawn the same. + let saved = s.execute("document.export", &json!({"format": "vectorcraft"})).unwrap()["dataBase64"].clone(); + let mut o = Session::new(); + o.execute("document.open", &json!({"name": "a.vectorcraft", "dataBase64": saved})).unwrap(); + assert_eq!(params(&o, id)[effects::BEVEL_PROFILE], params(&s, id)[effects::BEVEL_PROFILE]); + assert_eq!(ink(&o).pixels, with_bevel.pixels); + // The classic chamfer draws differently. + let set = json!({"ids": [id.0], "index": 0, "item": null, "params": {"bevel": "classic"}}); + o.execute("effect.setParams", &set).unwrap(); + assert_ne!(ink(&o).pixels, with_bevel.pixels); + o.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(ink(&o).pixels, with_bevel.pixels); + // Points that do not make a bevel are refused before the document changes. + let bad = json!({"ids": [id.0], "index": 0, "item": null, "params": {"bevelProfile": [[0, 0], [0.5, 2], [1, 1]]}}); + assert!(o.execute("effect.setParams", &bad).unwrap_err().to_string().contains("bevelProfile must be")); +} + +#[test] +fn both_extrudes_take_a_custom_bevels_points_and_refuse_a_name_that_is_not_a_string() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 300, "height": 300})).unwrap(); + let notch = json!([[0, 0], [0.2, 0.6], [0.7, 0.4], [1, 1]]); + for effect in [effects::EXTRUDE, effects::CLASSIC_EXTRUDE] { + let id = rect(&mut s, 100); + let apply = |name: Value| json!({"effect": effect, "ids": [id.0], "item": null, "params": {"bevel": "custom", "bevelName": name, "bevelProfile": notch}}); + let before = s.doc().unwrap().doc.clone(); + let e = s.execute("effect.apply", &apply(json!(3))).unwrap_err().to_string(); + assert!(e.contains("bevelName must be a string"), "{effect}: {e}"); + assert_eq!(s.doc().unwrap().doc, before, "{effect}"); + s.execute("effect.apply", &apply(json!("Notch"))).unwrap(); + assert_eq!((¶ms(&s, id)[effects::BEVEL_PROFILE], ¶ms(&s, id)[effects::BEVEL_NAME]), (¬ch, &json!("Notch")), "{effect}"); + } +} + +#[test] +fn without_a_bevels_file_editing_is_refused_and_none_are_listed() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let list = s.execute("threeD.bevels.list", &json!({})).unwrap(); + assert_eq!((list["bevels"].as_array().unwrap().len(), &list["file"]), (0, &Value::Null)); + assert!(s.execute("threeD.bevels.edit", &json!({})).is_err()); + assert!(s.execute("threeD.bevels.reload", &json!({})).is_err()); + // A file that is not a document lists no bevels and says why. + let dir = folder("unreadable"); + let file = dir.join(bevels::FILE_NAME); + std::fs::write(&file, b"not a document").unwrap(); + s.attach_bevels_file(file.to_string_lossy().to_string()); + let list = s.execute("threeD.bevels.list", &json!({})).unwrap(); + assert!(list["error"].is_string(), "{list}"); + assert!(s.execute("threeD.bevels.reload", &json!({})).is_err()); + let _ = std::fs::remove_dir_all(&dir); +} + +/// Automation roots that grant reading `read` alone. +fn read_roots(read: &[&std::path::Path]) -> Arc { + crate::file_access::AutomationRoots::new(read, &[]).unwrap().unwrap() +} + +#[test] +fn an_agent_outside_the_bevels_files_folder_sees_its_file_name_alone_and_cannot_reload_it() { + let dir = folder("roots-list"); + let (prefs, other) = (dir.join("prefs"), dir.join("other")); + std::fs::create_dir_all(&prefs).unwrap(); + std::fs::create_dir_all(&other).unwrap(); + let file = prefs.join(bevels::FILE_NAME); + std::fs::write(&file, b"not a drawing").unwrap(); + let (file, prefs_text) = (file.to_string_lossy().to_string(), prefs.to_string_lossy().to_string()); + let mut s = Session::new(); + s.attach_bevels_file(file.clone()); + let (outside, inside) = (read_roots(&[&other]), read_roots(&[&prefs])); + let list = crate::file_access::confine(Some(&outside), || s.execute("threeD.bevels.list", &json!({}))).unwrap(); + assert_eq!(list["file"], Value::Null, "{list}"); + let error = list["error"].as_str().unwrap(); + assert!(error.starts_with(bevels::FILE_NAME) && !error.contains(&prefs_text), "{error}"); + let list = crate::file_access::confine(Some(&inside), || s.execute("threeD.bevels.list", &json!({}))).unwrap(); + assert_eq!(list["file"].as_str(), Some(file.as_str())); + assert!(list["error"].as_str().unwrap().starts_with(&file), "{list}"); + // A good file now: an agent outside the folder cannot have it read. + std::fs::write(&file, vectorcraft_format::save_file(&bevels::starter())).unwrap(); + let e = crate::file_access::confine(Some(&outside), || s.execute("threeD.bevels.reload", &json!({}))).unwrap_err().to_string(); + assert!(e.contains("outside the read root") && e.ends_with(bevels::FILE_NAME) && !e.contains(&prefs_text), "{e}"); + let list = s.execute("threeD.bevels.list", &json!({})).unwrap(); + assert!(list["bevels"].as_array().unwrap().is_empty() && list["error"].is_string(), "not read again: {list}"); + let r = crate::file_access::confine(Some(&inside), || s.execute("threeD.bevels.reload", &json!({}))).unwrap(); + assert_eq!(r["count"], 1); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn an_agent_edits_the_bevels_file_only_inside_its_read_roots() { + let dir = folder("roots-edit"); + let (prefs, other) = (dir.join("prefs"), dir.join("other")); + std::fs::create_dir_all(&other).unwrap(); + let file = prefs.join(bevels::FILE_NAME).to_string_lossy().to_string(); + let prefs_text = prefs.to_string_lossy().to_string(); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + s.attach_bevels_file(file.clone()); + let first_doc = s.doc().unwrap().uid; + let outside = read_roots(&[&other]); + let edit = |s: &mut Session, roots: &Arc| { + crate::file_access::confine(Some(roots), || s.execute("threeD.bevels.edit", &json!({}))) + }; + // Refused before the folder or the file is made, or anything is opened. + let e = edit(&mut s, &outside).unwrap_err().to_string(); + assert!(e.ends_with(bevels::FILE_NAME) && !e.contains(&prefs_text), "{e}"); + assert!(!prefs.exists(), "no folder made"); + assert_eq!((s.documents().len(), s.doc().unwrap().uid), (1, first_doc)); + // From the 3D and Materials panel (no roots), the file is made and opened. + assert_eq!(s.execute("threeD.bevels.edit", &json!({})).unwrap()["created"], true); + assert_eq!(s.documents().len(), 2); + // Open already: still not brought to the front for an agent outside the folder. + s.execute("document.activate", &json!({"index": 0})).unwrap(); + assert!(edit(&mut s, &outside).is_err()); + assert_eq!((s.documents().len(), s.doc().unwrap().uid), (2, first_doc)); + // Inside the read roots: opened under them, with its path. + let inside = read_roots(&[&prefs]); + let mut agent = Session::new(); + agent.attach_bevels_file(file.clone()); + let r = edit(&mut agent, &inside).unwrap(); + assert_eq!((r["path"].as_str(), &r["created"]), (Some(file.as_str()), &json!(false))); + let st = agent.doc().unwrap(); + assert_eq!(st.path.as_deref(), Some(file.as_str())); + assert!(st.opened_by.as_ref().is_some_and(|r| Arc::ptr_eq(r, &inside)), "opened under the agent's roots"); + // A missing file inside the roots is still made first. + let fresh = dir.join("fresh").join(bevels::FILE_NAME).to_string_lossy().to_string(); + let mut agent = Session::new(); + agent.attach_bevels_file(fresh.clone()); + let r = edit(&mut agent, &read_roots(&[&dir])).unwrap(); + assert_eq!(r["created"], true); + assert!(std::path::Path::new(&fresh).is_file()); + assert_eq!(agent.doc().unwrap().path.as_deref(), Some(fresh.as_str())); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/engine/src/tests/brushlib.rs b/crates/engine/src/tests/brushlib.rs index 3ed90b8f2c..756db7a859 100644 --- a/crates/engine/src/tests/brushlib.rs +++ b/crates/engine/src/tests/brushlib.rs @@ -114,6 +114,7 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() { "bristle-brushes", "paint", "pattern-borders", + "decorative", "scatter-shapes", "stipple", "game-trails", @@ -122,10 +123,26 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() { "tech-circuit", "engraving", "arrows", - "image-brush" + "image-brush", + "artistic", + "vector-packs" ] ); assert!(libs.iter().all(|l| l["category"] == "builtIn")); + // None of them is a default brush. + let defaults: Vec<&str> = vectorcraft_brush::defaults().iter().map(|b| b.name.as_str()).collect(); + for id in ids { + let (_, lib) = cmd::brushlib::library(&s, id).unwrap(); + assert!(lib.brushes.iter().all(|b| !defaults.contains(&b.name.as_str())), "{id}"); + } + assert!(s.execute("brush.library", &json!({"library": "nope"})).is_err()); +} + +#[test] +fn the_builtin_libraries_list_their_brush_names_and_counts() { + let mut s = Session::new(); + let list = run(&mut s, "brush.libraries", json!({})); + let libs = list["libraries"].as_array().unwrap(); // Looked up by id, so a library added to the list does not shift these checks. let entry = |id: &str| libs.iter().find(|l| l["id"] == id).unwrap(); let lib = run(&mut s, "brush.library", json!({"library": "art ribbons"})); @@ -134,6 +151,7 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() { ["Notched Ribbon", "Double Line", "Wave", "Teardrop", "Striped Ribbon"] ); assert_eq!(entry("art-ribbons")["count"].as_u64(), Some(5)); + assert_eq!((entry("decorative")["name"].as_str(), entry("decorative")["count"].as_u64()), (Some("Decorative"), Some(4))); let trails = run(&mut s, "brush.library", json!({"library": "game-trails"})); assert_eq!( trails["brushes"].as_array().unwrap().iter().map(|b| b["name"].as_str().unwrap()).collect::>(), @@ -163,6 +181,11 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() { let id = run(&mut s, "shape.rectangle", json!({"x": 10, "y": 20, "width": 40, "height": 8}))["id"].as_u64().unwrap(); let added = run(&mut s, "brush.addFromLibrary", json!({"library": "energy-beams", "name": "Laser Bolt", "apply": true, "ids": [id]})); assert_eq!(strs(&added["added"]), ["Laser Bolt"]); +} + +#[test] +fn every_builtin_library_brush_has_its_kind_and_draws() { + let s = Session::new(); // One kind of brush per library (Ink and Wash: art brushes and a calligraphic one), every // brush drawing something. for (id, kind) in [ @@ -173,6 +196,7 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() { ("bristle-brushes", "bristle"), ("paint", "art"), ("pattern-borders", "pattern"), + ("decorative", "pattern"), ("scatter-shapes", "scatter"), ("stipple", "scatter"), ("game-trails", "art"), @@ -180,6 +204,8 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() { ("dry-media", "art"), ("arrows", "art"), ("image-brush", "scatter"), + ("artistic", "art"), + ("vector-packs", "scatter"), ] { let (_, lib) = cmd::brushlib::library(&s, id).unwrap(); assert!(lib.len() >= 4, "{id}"); @@ -193,6 +219,11 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() { assert!(!vectorcraft_brush::stroke_pieces(&lib.doc, b, &line, &stroke).is_empty(), "{} draws nothing", b.name); } } +} + +#[test] +fn builtin_library_brushes_bring_the_resources_their_art_uses() { + let s = Session::new(); // The resources their art uses come with them: Striped Ribbon's pattern, Sparkles' symbol. let (_, ribbons) = cmd::brushlib::library(&s, "art-ribbons").unwrap(); assert_eq!(art_patterns(ribbons.brush("Striped Ribbon").unwrap()), ["Pinstripes"]); @@ -201,13 +232,88 @@ fn the_builtin_libraries_are_original_brushes_generated_in_code() { let BrushKind::Scatter(sparkles) = &shapes.brush("Sparkles").unwrap().kind else { panic!("not a scatter brush") }; assert!(matches!(&sparkles.art.kind, NodeKind::SymbolInstance { symbol, .. } if symbol == "Sparkle")); assert!(shapes.doc.symbols.iter().any(|x| x.name == "Sparkle")); - // None of them is a default brush. - let defaults: Vec<&str> = vectorcraft_brush::defaults().iter().map(|b| b.name.as_str()).collect(); - for id in ids { - let (_, lib) = cmd::brushlib::library(&s, id).unwrap(); - assert!(lib.brushes.iter().all(|b| !defaults.contains(&b.name.as_str())), "{id}"); +} + +#[test] +fn artistic_library_strokes_are_editable_and_reopen_from_a_saved_library() { + let mut s = session(); + let (_, lib) = cmd::brushlib::library(&s, "artistic").unwrap(); + let (_, alias) = cmd::brushlib::library(&s, "Artistic").unwrap(); + assert_eq!(alias.brushes, lib.brushes); + assert_eq!(run(&mut s, "brush.library", json!({"library": "Artistic"}))["id"], "artistic"); + let names = ["Orbit Lines", "Petal Garland", "Lattice Braid", "Facet Sweep"]; + assert_eq!(lib.brushes.iter().map(|b| b.name.as_str()).collect::>(), names); + let line = run(&mut s, "shape.line", json!({"x1": 10, "y1": 50, "x2": 190, "y2": 50}))["id"].as_u64().unwrap(); + let red = vectorcraft_doc::StrokeLayer::new(vectorcraft_color::Paint::solid(vectorcraft_color::Color::rgb(1.0, 0.0, 0.0)), 1.0); + for b in &lib.brushes { + let BrushKind::Art(a) = &b.kind else { panic!("{} is not an art brush", b.name) }; + assert!(art_paths(&a.art).len() >= 2, "{} has no editable vector art", b.name); + for path in [line_to(180.0), line_to(1.0)] { + assert!(!vectorcraft_brush::stroke_pieces(&lib.doc, b, &path, &black_stroke()).is_empty(), "{} draws nothing", b.name); + } + // The art is black, so with Tints every path takes the stroke color itself. + let mut fills = vec![]; + for piece in vectorcraft_brush::stroke_pieces(&lib.doc, b, &line_to(180.0), &red) { + piece.walk(&mut |n| { + if n.path_data().is_some() { + fills.push(n.appearance.fill_paint().color().map(|c| c.to_rgb())); + } + }); + } + let is_red = |c: &Option<[f32; 3]>| c.is_some_and(|[r, g, b]| (r - 1.0).abs() < 1e-5 && g.abs() < 1e-5 && b.abs() < 1e-5); + assert!(!fills.is_empty() && fills.iter().all(is_red), "{} does not take the stroke color: {fills:?}", b.name); + let before = undo_len(&s); + let added = run(&mut s, "brush.addFromLibrary", json!({"library": "artistic", "name": b.name, "apply": true, "ids": [line]})); + assert_eq!(strs(&added["added"]), [b.name.as_str()]); + assert_eq!(added["applied"], json!([line])); + assert_eq!(undo_len(&s), before + 1); } - assert!(s.execute("brush.library", &json!({"library": "nope"})).is_err()); + let saved = run(&mut s, "brush.saveLibrary", json!({"names": names})); + let bytes = vectorcraft_format::base64_decode(saved["dataBase64"].as_str().unwrap()).unwrap(); + let reopened = vectorcraft_format::load(&bytes).unwrap(); + assert_eq!(vectorcraft_brush::library(&reopened), lib.brushes); +} + +#[test] +fn vector_packs_marks_are_editable_and_survive_a_saved_library() { + let mut s = session(); + let (_, lib) = cmd::brushlib::library(&s, "vector-packs").unwrap(); + let names = ["Compass Rose", "Botanical Sprig", "Facet Diamond", "Tide Crest"]; + assert_eq!(lib.brushes.iter().map(|b| b.name.as_str()).collect::>(), names); + let line = run(&mut s, "shape.line", json!({"x1": 10, "y1": 50, "x2": 190, "y2": 50}))["id"].as_u64().unwrap(); + for b in &lib.brushes { + let BrushKind::Scatter(sc) = &b.kind else { panic!("{} is not a scatter brush", b.name) }; + assert!(art_paths(&sc.art).len() >= 2, "{} has no editable vector mark", b.name); + let pieces = vectorcraft_brush::stroke_pieces(&lib.doc, b, &line_to(180.0), &black_stroke()); + assert!(pieces.len() >= 3, "{} does not repeat along a path", b.name); + // The black marks take a non-black stroke color as their fill. + let teal = vectorcraft_color::Color::rgb(0.1, 0.6, 0.5); + let stroke = vectorcraft_doc::StrokeLayer::new(vectorcraft_color::Paint::solid(teal), 1.0); + let mut fills = vec![]; + for piece in vectorcraft_brush::stroke_pieces(&lib.doc, b, &line_to(180.0), &stroke) { + piece.walk(&mut |c| { + if c.path_data().is_some() { + fills.push(c.appearance.fill().map(|f| f.paint.clone())); + } + }); + } + assert!(!fills.is_empty(), "{} draws no paths", b.name); + for fill in fills { + let Some(vectorcraft_color::Paint::Solid { color, .. }) = fill else { panic!("{} draws a path without a solid fill: {fill:?}", b.name) }; + let (got, want) = (color.to_rgb(), teal.to_rgb()); + assert!(got.iter().zip(want).all(|(g, w)| (g - w).abs() < 1e-3), "{} fills {got:?}, not the stroke color {want:?}", b.name); + } + let before = undo_len(&s); + let added = run(&mut s, "brush.addFromLibrary", json!({"library": "vector-packs", "name": b.name, "apply": true, "ids": [line]})); + assert_eq!(strs(&added["added"]), [b.name.as_str()]); + assert_eq!(added["applied"], json!([line])); + assert_eq!(undo_len(&s), before + 1); + assert_eq!(doc(&s).node(NodeId(line)).unwrap().appearance.stroke().unwrap().brush.as_deref(), Some(b.name.as_str())); + } + let saved = run(&mut s, "brush.saveLibrary", json!({"names": names})); + let bytes = vectorcraft_format::base64_decode(saved["dataBase64"].as_str().unwrap()).unwrap(); + let reopened = vectorcraft_format::load(&bytes).unwrap(); + assert_eq!(vectorcraft_brush::library(&reopened), lib.brushes); } #[test] @@ -247,6 +353,26 @@ fn image_brush_stamps_draw_and_carry_their_pixels_when_added_and_saved() { assert_eq!(reopened.images, lib.doc.images); } +#[test] +fn a_loaded_library_named_artistic_keeps_its_name_ahead_of_the_builtin_alias() { + let mut file = vectorcraft_doc::Document::new(100.0, 100.0); + vectorcraft_brush::store(&mut file, &[vectorcraft_brush::defaults()[0].clone()]); + let b64 = vectorcraft_format::base64_encode(&vectorcraft_format::save_file(&file)); + let mut s = session(); + let loaded = run(&mut s, "brush.loadLibrary", json!({"dataBase64": b64, "name": "Artistic.vectorcraft"})); + assert_eq!(loaded["name"], "Artistic"); + let id = loaded["library"].as_str().unwrap(); + assert_eq!(run(&mut s, "brush.library", json!({"library": "Artistic"}))["id"], id); + assert_eq!(run(&mut s, "brush.library", json!({"library": "ARTISTIC"}))["id"], id); + assert_eq!(run(&mut s, "brush.library", json!({"library": "artistic"}))["id"], "artistic", "exact built-in id still works"); + // A name a built-in library has selects the built-in, as for every built-in; the loaded one keeps its id. + let full = run(&mut s, "brush.loadLibrary", json!({"dataBase64": b64, "name": "Artistic Brushes.vectorcraft"})); + assert_eq!(full["name"], "Artistic Brushes"); + let full_id = full["library"].as_str().unwrap(); + assert_eq!(run(&mut s, "brush.library", json!({"library": "Artistic Brushes"}))["id"], "artistic"); + assert_eq!(run(&mut s, "brush.library", json!({"library": full_id}))["id"], full_id); +} + /// Every path of brush art `n`: (anchors, opacity). fn art_paths(n: &vectorcraft_doc::Node) -> Vec<(usize, f32)> { let mut out = vec![]; @@ -500,6 +626,41 @@ fn the_tech_circuit_library_constructs_adds_and_applies_each_brush() { assert_eq!(vectorcraft_brush::library(&reopened), lib.brushes); } +#[test] +fn decorative_brushes_repeat_distinct_art_and_survive_a_saved_library() { + let mut s = session(); + let (_, lib) = cmd::brushlib::library(&s, "Decorative").unwrap(); + let names = ["Leaf Vine", "Blossom Chain", "Pennant Garland", "Lantern String"]; + assert_eq!(lib.brushes.iter().map(|b| b.name.as_str()).collect::>(), names); + let path = run(&mut s, "shape.line", json!({"x1": 10, "y1": 40, "x2": 190, "y2": 40}))["id"].as_u64().unwrap(); + let mut signatures = std::collections::HashSet::new(); + for b in &lib.brushes { + let BrushKind::Pattern(pattern) = &b.kind else { panic!("{} is not a pattern brush", b.name) }; + assert_eq!(pattern.colorization, vectorcraft_brush::Colorization::Tints); + let points = |len: f64| anchors(&vectorcraft_brush::stroke_pieces(&lib.doc, b, &line_to(len), &black_stroke()).iter().collect::>()); + let (one, four) = (points(48.0), points(192.0)); + assert!(!one.is_empty() && four.iter().all(|p| p.x.is_finite() && p.y.is_finite()), "{}", b.name); + // A path four tiles long places the motif four times, each copy one tile further along. + assert_eq!(four.len(), 4 * one.len(), "{} repeats its motif", b.name); + for (i, p) in four.iter().enumerate() { + let q = one[i % one.len()]; + let shift = 48.0 * (i / one.len()) as f64; + assert!((p.x - q.x - shift).abs() < 1e-3 && (p.y - q.y).abs() < 1e-3, "{} copy {} at {p:?}, not {q:?}", b.name, i / one.len()); + } + signatures.insert(one.iter().map(|p| ((p.x * 100.0).round() as i64, (p.y * 100.0).round() as i64)).collect::>()); + let before = undo_len(&s); + let applied = run(&mut s, "brush.addFromLibrary", json!({"library": "decorative", "name": b.name, "apply": true, "ids": [path]})); + assert_eq!((strs(&applied["added"]), &applied["applied"]), (vec![b.name.as_str()], &json!([path]))); + assert_eq!(undo_len(&s), before + 1); + assert_eq!(doc(&s).node(NodeId(path)).unwrap().appearance.stroke().unwrap().brush.as_deref(), Some(b.name.as_str())); + } + assert_eq!(signatures.len(), names.len(), "each design produces a different repeating shape"); + let saved = run(&mut s, "brush.saveLibrary", json!({"names": names})); + let bytes = vectorcraft_format::base64_decode(saved["dataBase64"].as_str().unwrap()).unwrap(); + let reopened = vectorcraft_format::load(&bytes).unwrap(); + assert_eq!(vectorcraft_brush::library(&reopened), lib.brushes); +} + #[test] fn pressure_sensitive_brushes_widen_with_pen_pressure_and_survive_a_saved_library() { let mut s = session(); diff --git a/crates/engine/src/tests/build.rs b/crates/engine/src/tests/build.rs index 424e5678bb..316e9b8ffc 100644 --- a/crates/engine/src/tests/build.rs +++ b/crates/engine/src/tests/build.rs @@ -3434,6 +3434,65 @@ fn live_paint_bucket_gradient_preset_and_sampled_stop_follow_the_active_proxy() assert_eq!(node(&s, rect), art, "the selection keeps its paint"); } +/// The Gradient panel's eyedropper, used on a stop of the Live Paint Bucket's gradient, samples the +/// color clicked into that stop of the bucket's fill, and the selection keeps its paint. A Cmd-click +/// with the bucket, or with the Eyedropper armed for it, which the selection tool takes, leaves the +/// bucket's colors as they were. +#[test] +fn live_paint_bucket_keeps_its_colors_through_the_stop_eyedropper_and_a_cmd_click() { + let v = ViewInfo::default(); + let click = |s: &mut Session, mods: Mods| { + for kind in [PointerKind::Down, PointerKind::Up] { + s.pointer(&PointerEvent::new(kind, 320.0, 320.0).with_mods(mods), v).unwrap(); + } + }; + let mut s = session(); + live(&mut s); + let rect = rect(&mut s, 300.0, 300.0, 40.0, 40.0); + s.execute("paint.setFill", &json!({"color": "#00ff00", "ids": [rect.0]})).unwrap(); + s.execute("appearance.setNewArtBasic", &json!({"on": false})).unwrap(); + s.execute("select.set", &json!({"ids": [rect.0]})).unwrap(); + s.select_tool("livePaintBucket", v).unwrap(); + s.execute("paint.editGradient", &json!({"stroke": false, "kind": "linear"})).unwrap(); + s.execute("gradient.selectStop", &json!({"index": 1})).unwrap(); + let art = node(&s, rect); + // The panel's eyedropper (`stop_eyedropper`): the Eyedropper, set to switch back to the bucket. + s.select_tool("eyedropper", v).unwrap(); + s.set_tool_option("stop", &json!("livePaintBucket")); + assert_eq!(s.selected_stop(), Some(1), "the bucket's stop stays selected for the pick"); + // A Cmd-click while the pick is armed selects the rectangle and leaves the bucket's gradient. + let fill = s.paint.fill.clone(); + s.execute("select.set", &json!({"ids": []})).unwrap(); + click(&mut s, Mods { cmd: true, ..Mods::default() }); + assert_eq!(s.doc().unwrap().selection.objects, vec![rect], "the selection tool took the click"); + assert_eq!((s.paint.fill.clone(), s.selected_stop()), (fill, Some(1)), "the bucket's fill and stop stay"); + click(&mut s, Mods::default()); + let Paint::Gradient(g) = &s.paint.fill else { panic!("the bucket's fill is not a gradient") }; + assert_eq!(g.gradient.stops[1].color, Color::from_hex("#00ff00").unwrap(), "the sampled stop"); + assert_eq!(node(&s, rect), art, "the selection keeps its paint"); + // A Cmd-click selects the rectangle; the bucket keeps its gradient. + s.select_tool("livePaintBucket", v).unwrap(); + let fill = s.paint.fill.clone(); + s.execute("select.set", &json!({"ids": []})).unwrap(); + click(&mut s, Mods { cmd: true, ..Mods::default() }); + assert_eq!(s.doc().unwrap().selection.objects, vec![rect], "the selection tool took the click"); + assert_eq!(s.paint.fill, fill, "the bucket's fill stays"); + // Armed again, a Cmd-click on another object deselects the stop; the next click (a Shift-click, + // which would sample a color) ends the pick and leaves the bucket's gradient. + let other = self::rect(&mut s, 400.0, 400.0, 40.0, 40.0); + s.execute("select.set", &json!({"ids": [rect.0]})).unwrap(); + s.execute("gradient.selectStop", &json!({"index": 1})).unwrap(); + s.select_tool("eyedropper", v).unwrap(); + s.set_tool_option("stop", &json!("livePaintBucket")); + for mods in [Mods { cmd: true, ..Mods::default() }, Mods { shift: true, ..Mods::default() }] { + for kind in [PointerKind::Down, PointerKind::Up] { + s.pointer(&PointerEvent::new(kind, 420.0, 420.0).with_mods(mods), v).unwrap(); + } + } + assert_eq!(s.doc().unwrap().selection.objects, vec![other], "the Cmd-click selected the other object"); + assert_eq!((s.paint.fill.clone(), s.tool_returns_to()), (fill, None), "the pick ended without a sample"); +} + /// A gradient stop selected on the selection's gradient is not selected once the Live Paint /// Bucket is active (its proxies show the default paint), and one selected on the bucket's /// gradient is not selected once another tool is chosen. @@ -4224,6 +4283,353 @@ fn live_paint_group_stroke_panel_edits_change_its_edges() { assert_eq!(node(&s, g).appearance.stroke().map(|st| st.width), Some(1.0)); } +/// A face or edge selected before its Live Paint group counts with the group: the Fill proxy shows +/// the faces' fill and the Stroke panel the edges' stroke, whatever the order of the selection. +#[test] +fn live_paint_group_proxies_do_not_depend_on_the_selection_order() { + let mut s = session(); + let g = live(&mut s); + s.execute("select.set", &json!({"ids": [g.0]})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#ff00ff"})).unwrap(); + s.execute("stroke.set", &json!({"weight": 6})).unwrap(); + let magenta = serde_json::to_value(Paint::solid(Color::from_hex("#ff00ff").unwrap())).unwrap(); + let edge = vectorcraft_tools::builder::edges(&node(&s, g))[0].id; + s.execute("select.set", &json!({"ids": [edge.0, g.0]})).unwrap(); + assert_eq!(s.execute("paint.proxies", &json!({})).unwrap()["fill"], magenta, "an edge first shows the faces' fill"); + // A face with a stroke of its own (from a file, say), selected first, shows the edges' stroke. + let face = vectorcraft_tools::builder::faces(&node(&s, g))[0].id; + s.edit("t", |d, _| { + let n = d.node_mut(face).unwrap(); + n.appearance.set_stroke(Paint::solid(Color::BLACK)); + n.appearance.stroke_at_mut(None).unwrap().width = 2.0; + Ok(()) + }) + .unwrap(); + s.execute("select.set", &json!({"ids": [face.0, g.0]})).unwrap(); + assert_eq!(s.shown_stroke().map(|st| st.width), Some(6.0), "a face first shows the edges' stroke"); +} + +/// The Eyedropper onto a whole selected Live Paint group, or reversed onto a clicked one, gives the +/// picked fill attributes to its faces and the picked stroke attributes to its edges; its hidden +/// source paths keep their paint. +#[test] +fn live_paint_group_eyedropper_gives_the_fill_to_faces_and_the_stroke_to_edges() { + for reverse in [false, true] { + let mut s = session(); + let g = live(&mut s); + let src = rect(&mut s, 400.0, 0.0, 50.0, 50.0); + s.execute("paint.setFill", &json!({"ids": [src.0], "color": "#ff00ff"})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [src.0], "color": "#0000ff"})).unwrap(); + s.execute("stroke.set", &json!({"ids": [src.0], "weight": 3})).unwrap(); + let (faces0, edges0) = part_looks(&s, g); + let sources0 = sources_looks(&s, g); + if reverse { + s.execute("select.set", &json!({"ids": [src.0]})).unwrap(); + s.execute("appearance.copyFrom", &json!({"source": g.0, "reverse": true})).unwrap(); + } else { + s.execute("select.set", &json!({"ids": [g.0]})).unwrap(); + s.execute("appearance.copyFrom", &json!({"source": src.0})).unwrap(); + } + let (faces1, edges1) = part_looks(&s, g); + let magenta = Paint::solid(Color::from_hex("#ff00ff").unwrap()); + let blue = Paint::solid(Color::from_hex("#0000ff").unwrap()); + for (f, f0) in faces1.iter().zip(&faces0) { + assert_eq!(f.fill_paint(), magenta, "reverse {reverse}: a face takes the fill"); + assert_eq!((f.stroke_paint(), f.stroke_width()), (f0.stroke_paint(), f0.stroke_width()), "reverse {reverse}: a face takes no stroke"); + } + for (e, e0) in edges1.iter().zip(&edges0) { + assert_eq!((e.stroke_paint(), e.stroke_width()), (blue.clone(), 3.0), "reverse {reverse}: an edge takes the stroke"); + assert_eq!(e.fill_paint(), e0.fill_paint(), "reverse {reverse}: an edge takes no fill"); + } + assert_eq!(sources_looks(&s, g), sources0, "reverse {reverse}: the hidden source paths keep their paint"); + } +} + +/// A whole-appearance Eyedropper pick of a source with several fills and strokes gives each face +/// of a selected Live Paint group every fill row and each edge every stroke row. +#[test] +fn live_paint_group_eyedropper_gives_every_fill_and_stroke_row() { + let mut s = session(); + let g = live(&mut s); + let src = rect(&mut s, 400.0, 0.0, 50.0, 50.0); + s.execute("paint.setFill", &json!({"ids": [src.0], "color": "#ff00ff"})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [src.0], "color": "#0000ff"})).unwrap(); + s.execute("appearance.addFill", &json!({"ids": [src.0]})).unwrap(); + s.execute("appearance.addStroke", &json!({"ids": [src.0]})).unwrap(); + let kinds = |a: &vectorcraft_doc::Appearance, fill: bool| a.items.iter().filter(|it| it.is_fill() == fill).count(); + let source = (*node(&s, src).appearance).clone(); + assert_eq!((kinds(&source, true), kinds(&source, false)), (2, 2)); + // A face with a stroke row below its fill keeps that row below the picked fills. + let face = vectorcraft_tools::builder::faces(&node(&s, g))[0].id; + s.edit("t", |d, _| { + let n = d.node_mut(face).unwrap(); + n.appearance.items.insert(0, vectorcraft_doc::AppearanceItem::Stroke(vectorcraft_doc::StrokeLayer::new(Paint::solid(Color::BLACK), 9.0))); + Ok(()) + }) + .unwrap(); + let (faces0, edges0) = part_looks(&s, g); + s.execute("select.set", &json!({"ids": [g.0]})).unwrap(); + s.execute("appearance.copyFrom", &json!({"source": src.0})).unwrap(); + let (faces1, edges1) = part_looks(&s, g); + let order: Vec = faces1[0].items.iter().map(|it| it.is_fill()).collect(); + assert_eq!(order.first(), Some(&false), "the face's lower stroke row stays below its fills: {order:?}"); + for (f, f0) in faces1.iter().zip(&faces0) { + assert_eq!(kinds(f, true), 2, "a face takes every fill row"); + assert_eq!(kinds(f, false), kinds(f0, false), "a face keeps its strokes"); + } + for (e, e0) in edges1.iter().zip(&edges0) { + assert_eq!(kinds(e, false), 2, "an edge takes every stroke row"); + assert_eq!(kinds(e, true), kinds(e0, true), "an edge keeps its fills"); + } +} + +/// The Appearance panel's edits of a Live Paint group's contents (`target: "contents"`) follow the +/// group's rule: a new fill goes on its faces, a new stroke on its edges, and its hidden source paths +/// keep their appearance under every contents edit. +#[test] +fn live_paint_group_contents_edits_follow_the_group_rule() { + let mut s = session(); + let g = live(&mut s); + s.execute("select.set", &json!({"ids": [g.0]})).unwrap(); + let (faces0, edges0) = part_looks(&s, g); + let sources0 = sources_looks(&s, g); + s.execute("appearance.addFill", &json!({"target": "contents"})).unwrap(); + let (faces1, edges1) = part_looks(&s, g); + assert!(faces1.iter().zip(&faces0).all(|(f, f0)| f.items.len() == f0.items.len() + 1), "every face takes a new fill"); + assert_eq!(edges1, edges0, "edges take no new fill"); + s.execute("appearance.addStroke", &json!({"target": "contents"})).unwrap(); + let (faces2, edges2) = part_looks(&s, g); + assert_eq!(faces2, faces1, "faces take no new stroke"); + assert!(edges2.iter().zip(&edges1).all(|(e, e0)| e.items.len() == e0.items.len() + 1), "every edge takes a new stroke"); + // A stroke row edit of the contents reaches the edges, not the faces. + s.execute("stroke.set", &json!({"target": "contents", "item": 0, "weight": 7})).unwrap(); + let (faces3, edges3) = part_looks(&s, g); + assert_eq!(faces3, faces2, "faces keep their rows"); + assert!(edges3.iter().all(|e| e.stroke_at(Some(0)).map(|st| st.width) == Some(7.0)), "every edge's stroke row takes the weight"); + s.execute("appearance.clear", &json!({"target": "contents"})).unwrap(); + assert_eq!(sources_looks(&s, g), sources0, "the hidden source paths keep their appearance"); +} + +/// Fill edits of a Live Paint group's contents with an `item` (a gradient vector, Invert, Overprint +/// Fill) change its faces and leave an edge's fill row as it is, and Overprint on the whole group goes +/// to the faces' fills and the edges' strokes, leaving the hidden source paths as they are. +#[test] +fn live_paint_group_item_edits_and_overprint_follow_the_group_rule() { + let mut s = session(); + let g = live(&mut s); + s.execute("select.set", &json!({"ids": [g.0]})).unwrap(); + s.execute("paint.setFill", &json!({"gradient": {}})).unwrap(); + // Each edge gets a copy of a face's gradient fill row, below its stroke. + let n = node(&s, g); + let face_row = vectorcraft_tools::builder::faces(&n)[0].appearance.items[0].clone(); + let edge_ids: Vec = vectorcraft_tools::builder::edges(&n).iter().map(|e| e.id).collect(); + let mut face_ids: Vec = vectorcraft_tools::builder::faces(&n).iter().map(|f| f.id.0).collect(); + face_ids.sort_unstable(); + s.edit("t", |d, _| { + for e in &edge_ids { + d.node_mut(*e).unwrap().appearance.items.insert(0, face_row.clone()); + } + Ok(()) + }) + .unwrap(); + let (faces0, edges0) = part_looks(&s, g); + let sources0 = sources_looks(&s, g); + let r = s.execute("paint.setGradientGeom", &json!({"stroke": false, "item": 0, "target": "contents", "start": [0, 0], "end": [100, 0]})).unwrap(); + let mut changed: Vec = r["ids"].as_array().unwrap().iter().map(|v| v.as_u64().unwrap()).collect(); + changed.sort_unstable(); + assert_eq!(changed, face_ids, "only the faces take the vector"); + assert_eq!(part_looks(&s, g).1, edges0, "an edge's fill row keeps its vector"); + let stops = |a: &vectorcraft_doc::Appearance| match a.fill_paint() { + Paint::Gradient(gr) => gr.gradient.stops.iter().map(|st| st.color).collect::>(), + _ => vec![], + }; + let before: Vec<_> = part_looks(&s, g).0.iter().map(stops).collect(); + s.execute("paint.invert", &json!({"stroke": false, "item": 0, "target": "contents"})).unwrap(); + for (f, b) in part_looks(&s, g).0.iter().zip(&before) { + assert_eq!(stops(f), b.iter().rev().copied().collect::>(), "the black-to-white stops of a face's fill are inverted"); + } + assert_ne!(part_looks(&s, g).0, faces0); + assert_eq!(part_looks(&s, g).1, edges0, "an edge's fill row is not inverted"); + s.execute("object.setOverprint", &json!({"fill": true, "item": 0, "target": "contents"})).unwrap(); + let (faces1, edges1) = part_looks(&s, g); + assert!(faces1.iter().all(|f| f.items[0].overprint()), "the faces' fill overprints"); + assert_eq!(edges1, edges0, "an edge's fill row does not overprint"); + s.execute("object.setOverprint", &json!({"fill": true, "stroke": true})).unwrap(); + let (_, edges2) = part_looks(&s, g); + assert!(edges2.iter().all(|e| e.items.iter().all(|it| it.overprint() != it.is_fill())), "only the edges' strokes overprint"); + assert_eq!(sources_looks(&s, g), sources0, "the hidden source paths keep their flags"); +} + +/// A face selected before an ordinary group that holds its Live Paint group counts with that group: +/// the Stroke panel shows the edges' stroke. +#[test] +fn live_paint_group_inside_a_selected_group_keeps_the_proxies_independent_of_order() { + let mut s = session(); + let g = live(&mut s); + s.execute("select.set", &json!({"ids": [g.0]})).unwrap(); + s.execute("stroke.set", &json!({"weight": 6})).unwrap(); + let outer = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + let face = vectorcraft_tools::builder::faces(&node(&s, g))[0].id; + s.edit("t", |d, _| { + let n = d.node_mut(face).unwrap(); + n.appearance.set_stroke(Paint::solid(Color::BLACK)); + n.appearance.stroke_at_mut(None).unwrap().width = 2.0; + Ok(()) + }) + .unwrap(); + s.execute("select.set", &json!({"ids": [face.0, outer.0]})).unwrap(); + assert_eq!(s.shown_stroke().map(|st| st.width), Some(6.0), "a face first shows the edges' stroke"); + assert!(!s.active().unwrap().stroke_mixed().weight, "the face's own stroke does not make the weight mixed"); + // An unfilled edge selected with the outer group does not make the faces' fill mixed. + s.execute("select.set", &json!({"ids": [g.0]})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + let edge = vectorcraft_tools::builder::edges(&node(&s, g))[0].id; + s.execute("select.set", &json!({"ids": [edge.0, outer.0]})).unwrap(); + let r = s.execute("paint.proxies", &json!({})).unwrap(); + assert_eq!(r["fill"], serde_json::to_value(Paint::solid(Color::from_hex("#ff0000").unwrap())).unwrap()); + assert_eq!(r["fillMixed"], false, "the edge counts with its group"); +} + +/// The Eyedropper picks up a whole Live Paint group as its faces' fill under its edges' stroke, and +/// `append` onto a whole group adds the picked fills and strokes without the picked effects. +#[test] +fn live_paint_group_eyedropper_picks_up_the_group_and_appends_without_effects() { + let mut s = session(); + let g = live(&mut s); + s.execute("select.set", &json!({"ids": [g.0]})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#ff00ff"})).unwrap(); + s.execute("paint.setStroke", &json!({"color": "#0000ff"})).unwrap(); + s.execute("stroke.set", &json!({"weight": 5})).unwrap(); + s.edit("t", |d, _| { + d.node_mut(g).unwrap().opacity = 0.5; + Ok(()) + }) + .unwrap(); + let target = rect(&mut s, 400.0, 0.0, 50.0, 50.0); + s.execute("select.set", &json!({"ids": [g.0]})).unwrap(); + s.execute("appearance.copyFrom", &json!({"source": target.0, "reverse": true})).unwrap(); + let a = (*node(&s, target).appearance).clone(); + assert_eq!(a.fill_paint(), Paint::solid(Color::from_hex("#ff00ff").unwrap()), "the faces' fill"); + assert_eq!((a.stroke_paint(), a.stroke_width()), (Paint::solid(Color::from_hex("#0000ff").unwrap()), 5.0), "the edges' stroke"); + assert_eq!(node(&s, target).opacity, 0.5, "the group's own opacity"); + // A Live Paint group with no face and no edge is not picked up: the next selected object is. + let empty = rect(&mut s, 600.0, 0.0, 50.0, 50.0); + s.execute("select.set", &json!({"ids": [empty.0]})).unwrap(); + let e = NodeId(s.execute("livePaint.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + let en = node(&s, e); + let parts: Vec = + vectorcraft_tools::builder::faces(&en).iter().chain(vectorcraft_tools::builder::edges(&en).iter()).map(|p| p.id).collect(); + assert!(!parts.is_empty()); + s.edit("t", |d, _| { + d.node_mut(e).unwrap().children_mut().unwrap().retain(|c| !parts.contains(&c.id)); + Ok(()) + }) + .unwrap(); + assert!(vectorcraft_tools::builder::is_live_paint(&node(&s, e))); + let other = rect(&mut s, 700.0, 0.0, 50.0, 50.0); + s.execute("paint.setFill", &json!({"ids": [other.0], "color": "#00ff00"})).unwrap(); + s.execute("select.set", &json!({"ids": [e.0, other.0]})).unwrap(); + s.execute("appearance.copyFrom", &json!({"source": target.0, "reverse": true})).unwrap(); + assert_eq!(node(&s, target).appearance.fill_paint(), Paint::solid(Color::from_hex("#00ff00").unwrap()), "the next selected object's fill"); + // Append a source with a drop shadow onto the whole group. + let src = rect(&mut s, 500.0, 0.0, 50.0, 50.0); + s.execute("select.set", &json!({"ids": [src.0]})).unwrap(); + s.execute("effect.apply", &json!({"effect": "stylize.dropShadow", "item": null})).unwrap(); + assert!(!node(&s, src).appearance.effects.is_empty()); + let (faces0, edges0) = part_looks(&s, g); + s.execute("select.set", &json!({"ids": [g.0]})).unwrap(); + s.execute("appearance.copyFrom", &json!({"source": src.0, "append": true})).unwrap(); + let (faces1, edges1) = part_looks(&s, g); + for (p, p0) in faces1.iter().chain(&edges1).zip(faces0.iter().chain(&edges0)) { + assert_eq!(p.effects, p0.effects, "a face or edge takes no effect"); + } + assert!(faces1.iter().zip(&faces0).all(|(f, f0)| f.items.len() > f0.items.len()), "every face takes the fill"); +} + +/// Reversed onto a clicked object, an empty Live Paint group first in the selection passes to the next +/// selected Live Paint group, whose faces' fill and edges' stroke are both picked up. +#[test] +fn live_paint_group_eyedropper_reversed_skips_an_empty_group_for_the_next_whole_group() { + let mut s = session(); + let g = live(&mut s); + s.execute("select.set", &json!({"ids": [g.0]})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#ff00ff"})).unwrap(); + s.execute("paint.setStroke", &json!({"color": "#0000ff"})).unwrap(); + s.execute("stroke.set", &json!({"weight": 5})).unwrap(); + let empty = rect(&mut s, 600.0, 0.0, 50.0, 50.0); + s.execute("select.set", &json!({"ids": [empty.0]})).unwrap(); + let e = NodeId(s.execute("livePaint.make", &json!({})).unwrap()["id"].as_u64().unwrap()); + let en = node(&s, e); + let parts: Vec = + vectorcraft_tools::builder::faces(&en).iter().chain(vectorcraft_tools::builder::edges(&en).iter()).map(|p| p.id).collect(); + s.edit("t", |d, _| { + d.node_mut(e).unwrap().children_mut().unwrap().retain(|c| !parts.contains(&c.id)); + Ok(()) + }) + .unwrap(); + let target = rect(&mut s, 400.0, 0.0, 50.0, 50.0); + s.execute("appearance.copyFrom", &json!({"source": target.0, "reverse": true, "ids": [e.0, g.0]})).unwrap(); + let a = (*node(&s, target).appearance).clone(); + assert_eq!(a.fill_paint(), Paint::solid(Color::from_hex("#ff00ff").unwrap()), "the faces' fill"); + assert_eq!((a.stroke_paint(), a.stroke_width()), (Paint::solid(Color::from_hex("#0000ff").unwrap()), 5.0), "the edges' stroke"); +} + +/// An Eyedropper pick whose source is the selected Live Paint group leaves the group's own faces and +/// edges as they are. +#[test] +fn live_paint_group_eyedropper_does_not_target_its_own_source_group() { + let mut s = session(); + let g = live(&mut s); + s.execute("livePaint.fill", &json!({"group": g.0, "point": [25, 50], "color": "#ff0000"})).unwrap(); + s.execute("livePaint.fill", &json!({"group": g.0, "point": [75, 50], "color": "#00ff00"})).unwrap(); + let before = part_looks(&s, g); + s.execute("select.set", &json!({"ids": [g.0]})).unwrap(); + s.execute("appearance.copyFrom", &json!({"source": g.0})).unwrap(); + assert_eq!(part_looks(&s, g), before); +} + +/// A Live Paint group left with only its hidden source paths is still a selection: a stroke edit of its +/// contents changes nothing and leaves the settings for new art as they are. +#[test] +fn live_paint_group_with_only_source_paths_leaves_new_art_alone_for_a_contents_edit() { + let mut s = session(); + let g = live(&mut s); + let n = node(&s, g); + let parts: Vec = vectorcraft_tools::builder::faces(&n).iter().chain(vectorcraft_tools::builder::edges(&n).iter()).map(|p| p.id).collect(); + s.edit("t", |d, _| { + d.children_mut(Some(g)).unwrap().retain(|c| !parts.contains(&c.id)); + Ok(()) + }) + .unwrap(); + s.execute("select.set", &json!({"ids": [g.0]})).unwrap(); + let (paint0, stroke0) = (s.paint.clone(), s.new_art_stroke()); + s.execute("stroke.setAdvanced", &json!({"target": "contents", "item": 0, "arrowScale": [200, 150]})).unwrap(); + assert_eq!((s.paint.clone(), s.new_art_stroke()), (paint0, stroke0), "new art keeps its stroke"); +} + +/// Adding a fill or a stroke to the contents of a Live Paint group left with only its hidden source paths +/// succeeds and changes nothing, while an empty selection is still refused. +#[test] +fn live_paint_group_with_only_source_paths_ignores_add_fill_and_add_stroke_of_its_contents() { + let mut s = session(); + let g = live(&mut s); + let n = node(&s, g); + let parts: Vec = vectorcraft_tools::builder::faces(&n).iter().chain(vectorcraft_tools::builder::edges(&n).iter()).map(|p| p.id).collect(); + s.edit("t", |d, _| { + d.children_mut(Some(g)).unwrap().retain(|c| !parts.contains(&c.id)); + Ok(()) + }) + .unwrap(); + s.execute("select.set", &json!({"ids": [g.0]})).unwrap(); + let before = node(&s, g); + for cmd in ["appearance.addFill", "appearance.addStroke"] { + s.execute(cmd, &json!({"target": "contents"})).unwrap(); + assert_eq!(node(&s, g), before, "{cmd} changes nothing"); + } + s.execute("select.none", &json!({})).unwrap(); + assert!(s.execute("appearance.addFill", &json!({"target": "contents"})).is_err(), "no selection is still refused"); +} + /// A selected Live Paint group with no part of the edited kind is still a selection: a stroke edit /// of a group without edges, or a fill gradient edit of a group without faces, changes nothing and /// leaves the settings for new art as they are. @@ -4245,6 +4651,8 @@ fn live_paint_group_without_parts_of_the_edited_kind_leaves_new_art_alone() { s.execute("stroke.set", &json!({"weight": 4})).unwrap(); s.execute("stroke.weightUp", &json!({})).unwrap(); s.execute("stroke.setAdvanced", &json!({"arrowScale": [200, 150]})).unwrap(); + // A stroke row edit of the group's contents finds no edge either. + s.execute("stroke.set", &json!({"target": "contents", "item": 0, "weight": 9})).unwrap(); assert_eq!((s.paint.clone(), s.new_art_stroke()), (paint0, stroke0), "new art keeps its stroke"); assert_eq!(part_looks(&s, g), looks); @@ -9221,6 +9629,111 @@ fn image_trace_built_in_presets_cannot_be_saved_over_or_deleted() { assert_eq!(six["params"], serde_json::to_value(vectorcraft_trace::preset("6 Colors").unwrap()).unwrap()); } +/// Saved tracing presets go out to a .vctracepresets file and come back with their names and +/// settings; a hand-written file in the documented layout imports too. +#[test] +fn image_trace_presets_export_and_import_round_trip() { + let mut s = session(); + assert!(s.execute("imageTrace.presets.export", &json!({})).unwrap_err().to_string().contains("no saved tracing presets")); + s.execute("imageTrace.presets.save", &json!({"name": "Poster", "preset": "6 Colors", "params": {"noise": 40, "ignoreWhite": true}})).unwrap(); + s.execute("imageTrace.presets.save", &json!({"name": "Ink", "params": {"threshold": 90, "fills": false, "strokes": true}})).unwrap(); + let e = s.execute("imageTrace.presets.export", &json!({"names": ["Default"]})).unwrap_err().to_string(); + assert!(e.contains("only saved presets are exported"), "{e}"); + assert!(s.execute("imageTrace.presets.export", &json!({"names": ["Nope"]})).is_err()); + let all = s.execute("imageTrace.presets.export", &json!({})).unwrap(); + assert_eq!(all["count"], 2); + let one = s.execute("imageTrace.presets.export", &json!({"names": ["poster", "Poster"]})).unwrap(); + assert_eq!(one["count"], 1); + let file: Value = serde_json::from_str(all["data"].as_str().unwrap()).unwrap(); + assert_eq!((file["format"].as_str(), file["version"].as_u64()), (Some("vctracepresets"), Some(1))); + let saved = s.prefs.trace_presets.clone(); + // Into a session without them: the same names and settings, and a new revision the panel follows. + let mut t = session(); + let before = t.trace_presets_revision(); + let r = t.execute("imageTrace.presets.import", &json!({"data": all["data"]})).unwrap(); + assert_eq!(r, json!({"imported": ["Poster", "Ink"], "replaced": [], "skipped": []})); + assert_eq!(t.prefs.trace_presets, saved); + assert_eq!(t.trace_presets_revision(), before + 2); + // A file written by hand in the documented layout: missing settings are Default's. + let hand = r#"{"format": "vctracepresets", "version": 1, "presets": [{"name": "Hand", "params": {"mode": "grayscale", "colors": 12}}]}"#; + t.execute("imageTrace.presets.import", &json!({ "dataBase64": vectorcraft_format::base64_encode(hand.as_bytes()) })).unwrap(); + let hand = t.trace_preset("hand").unwrap().params.clone(); + assert_eq!((hand.mode, hand.colors, hand.threshold), (vectorcraft_trace::Mode::Grayscale, 12, 128)); +} + +/// Export writes no file that import would refuse (more than 1,000 presets, or more than 4 MiB), +/// and no more than 1,000 tracing presets can be saved. +#[test] +fn image_trace_presets_export_keeps_to_what_import_reads() { + let mut s = session(); + let params = vectorcraft_trace::preset("Default").unwrap(); + let preset = |name: String| crate::cmd::TracePreset { name, params: params.clone() }; + s.prefs.trace_presets = (1..=1001).map(|i| preset(format!("P{i}"))).collect(); + let e = s.execute("imageTrace.presets.export", &json!({})).unwrap_err().to_string(); + assert!(e.contains("more than one file holds (1000)"), "{e}"); + s.prefs.trace_presets.pop(); + let all = s.execute("imageTrace.presets.export", &json!({})).unwrap(); + assert_eq!(all["count"], 1000); + let mut t = session(); + assert_eq!(t.execute("imageTrace.presets.import", &json!({"data": all["data"]})).unwrap()["imported"].as_array().map(Vec::len), Some(1000)); + // No more can be saved or imported then, so every saved preset still fits in one file; a + // saved preset can still change, and a file of saved names still replaces them. + let e = t.execute("imageTrace.presets.save", &json!({"name": "One More"})).unwrap_err().to_string(); + assert!(e.contains("delete one first"), "{e}"); + t.execute("imageTrace.presets.save", &json!({"name": "P1", "params": {"noise": 9}})).unwrap(); + let one = json!({"format": "vctracepresets", "version": 1, "presets": [{"name": "Fresh", "params": {}}]}).to_string(); + let e = t.execute("imageTrace.presets.import", &json!({ "data": one })).unwrap_err().to_string(); + assert!(e.contains("more than 1000 saved"), "{e}"); + let again = json!({"format": "vctracepresets", "version": 1, "presets": [{"name": "P2", "params": {}}]}).to_string(); + assert_eq!(t.execute("imageTrace.presets.import", &json!({"data": again, "replace": true})).unwrap()["replaced"], json!(["P2"])); + assert_eq!(t.prefs.trace_presets.len(), 1000); + s.prefs.trace_presets = vec![preset("x".repeat(4 << 20))]; + let e = s.execute("imageTrace.presets.export", &json!({})).unwrap_err().to_string(); + assert!(e.contains("larger than 4 MiB"), "{e}"); +} + +/// A saved preset of the same name is skipped unless `replace` is on; a file with a fault, or one +/// too large, changes nothing. +#[test] +fn image_trace_presets_import_checks_the_whole_file_first() { + let mut s = session(); + s.execute("imageTrace.presets.save", &json!({"name": "Poster", "params": {"noise": 40}})).unwrap(); + let file = |rows: Value| json!({"format": "vctracepresets", "version": 1, "presets": rows}).to_string(); + let data = file(json!([{"name": "poster", "params": {"noise": 7}}, {"name": "Fresh", "params": {}}])); + let r = s.execute("imageTrace.presets.import", &json!({ "data": data })).unwrap(); + assert_eq!(r, json!({"imported": ["Fresh"], "replaced": [], "skipped": ["poster"]})); + assert_eq!(s.trace_preset("Poster").unwrap().params.noise, 40); + let r = s.execute("imageTrace.presets.import", &json!({"data": data, "replace": true})).unwrap(); + assert_eq!(r, json!({"imported": [], "replaced": ["Poster", "Fresh"], "skipped": []})); + assert_eq!(s.trace_preset("Poster").unwrap().params.noise, 7); + assert!(s.execute("imageTrace.presets.import", &json!({"data": data, "replace": "yes"})).is_err()); + let saved = s.prefs.trace_presets.clone(); + let revision = s.trace_presets_revision(); + let bad_files = [ + (file(json!([{"name": "New One", "params": {}}, {"name": "[Default]", "params": {}}])), "built-in preset"), + (file(json!([{"name": "custom", "params": {}}])), "built-in preset"), + (file(json!([{"name": "Twice", "params": {}}, {"name": "twice", "params": {}}])), "two presets named"), + (file(json!([{"name": " ", "params": {}}])), "has no name"), + (file(json!([{"name": "No Params"}])), "has no `params`"), + (file(json!([{"name": "Neither", "params": {"fills": false, "strokes": false}}])), "Create needs fills"), + (file(json!([{"name": "Typo", "params": {"nosie": 3}}])), "nosie"), + (json!({"format": "vctracepresets", "version": 2, "presets": []}).to_string(), "newer"), + (json!({"format": "vcflattener", "version": 1, "presets": []}).to_string(), "not a tracing presets file"), + ("{".to_string(), "not a tracing presets file"), + (file(Value::Array(vec![json!({"name": "x", "params": {}}); 1001])), "more than 1000"), + (" ".repeat((4 << 20) + 1), "larger than 4 MiB"), + ]; + for (data, why) in bad_files { + let e = s.execute("imageTrace.presets.import", &json!({ "data": data })).unwrap_err().to_string(); + assert!(e.contains(why), "{why}: {e}"); + } + let big = vectorcraft_format::base64_encode(&vec![b' '; (4 << 20) + 1]); + assert!(s.execute("imageTrace.presets.import", &json!({ "dataBase64": big })).unwrap_err().to_string().contains("larger than 4 MiB")); + assert!(s.execute("imageTrace.presets.import", &json!({})).is_err()); + assert_eq!(s.prefs.trace_presets, saved, "nothing changed"); + assert_eq!(s.trace_presets_revision(), revision); +} + /// Saved tracing presets are kept with the preferences, are not a preference key, and survive /// resetting the preferences. #[test] @@ -9491,9 +10004,12 @@ fn image_trace_split_view_keeps_and_validates_its_divider() { assert_eq!((back.node(g).unwrap().trace_view(), back.node(g).unwrap().trace_split()), (vectorcraft_doc::TraceView::Split, 0.25)); // Bad dividers are refused and change nothing. let steps = s.doc().unwrap().history.undo.len(); - for bad in [json!(-0.1), json!(1.01), json!("0.5"), json!(true), json!([0.5])] { + for bad in [json!(-0.1), json!(1.01), json!("0.5"), json!(true), json!([0.5]), json!(null)] { assert!(s.execute("imageTrace.setView", &json!({"view": "split", "split": bad})).is_err(), "{bad}"); } + // A null divider with another view is refused too, and the view stays. + assert!(s.execute("imageTrace.setView", &json!({"view": "outlines", "split": null})).is_err()); + assert_eq!(node(&s, g).trace_view(), vectorcraft_doc::TraceView::Split); assert_eq!((s.doc().unwrap().history.undo.len(), node(&s, g).trace_split()), (steps, 0.25)); for edge in [0.0, 1.0] { s.execute("imageTrace.setView", &json!({"view": "split", "split": edge})).unwrap(); diff --git a/crates/engine/src/tests/circle_through.rs b/crates/engine/src/tests/circle_through.rs index e91c48e76a..c9b66f9f06 100644 --- a/crates/engine/src/tests/circle_through.rs +++ b/crates/engine/src/tests/circle_through.rs @@ -204,6 +204,35 @@ fn the_circle_is_not_moved_onto_the_pixel_grid() { assert!(!node(&s, id).extras().pixel_aligned); } +/// `anchors: "points"` puts an anchor exactly at each point, with one more on each half of a +/// diameter's circle; the circle is a plain path, not pixel-aligned, and one undo step. Any other +/// `anchors` value is an error and draws nothing. +#[test] +fn anchors_at_the_points_puts_an_anchor_at_each_point() { + let mut s = session(); + s.execute("document.setup", &json!({"alignNewObjectsToPixelGrid": true})).unwrap(); + let undo = undo_len(&s); + let points = [Point::new(0.3, 0.2), Point::new(80.6, 0.1), Point::new(0.4, 60.7)]; + let pairs: Vec = points.iter().map(|p| json!([p.x, p.y])).collect(); + let id = id_of(&s.execute(C, &json!({ "points": pairs, "anchors": "points" })).unwrap()); + let n = node(&s, id); + let anchors: Vec = n.path_data().unwrap().subpaths[0].anchors.iter().map(|a| a.p).collect(); + assert!(points.iter().all(|p| anchors.contains(p)), "{anchors:?}"); + assert!(matches!(n.kind, NodeKind::Path { live: None, .. }), "{:?}", n.kind); + assert!(!n.extras().pixel_aligned); + assert_eq!(undo_len(&s), undo + 1); + let id = id_of(&s.execute(C, &json!({ "points": [[0, 0], [100, 0]], "anchors": "points" })).unwrap()); + let anchors: Vec = node(&s, id).path_data().unwrap().subpaths[0].anchors.iter().map(|a| a.p).collect(); + assert_eq!(anchors.len(), 4, "{anchors:?}"); + assert_eq!((anchors[0], anchors[2]), (Point::new(0.0, 0.0), Point::new(100.0, 0.0))); + let (count, undo) = (object_count(&s), undo_len(&s)); + for bad in [json!("corners"), json!(true), json!(4), Value::Null] { + let e = s.execute(C, &json!({ "points": [[0, 0], [100, 0]], "anchors": bad })).unwrap_err().to_string(); + assert!(e.contains("`anchors` must be one of standard, points"), "{e}"); + } + assert_eq!((object_count(&s), undo_len(&s)), (count, undo)); +} + fn view() -> ViewInfo { ViewInfo { smart_guides: false, ..ViewInfo::default() } } diff --git a/crates/engine/src/tests/colormgmt.rs b/crates/engine/src/tests/colormgmt.rs index de28e1d01e..3e64f1557d 100644 --- a/crates/engine/src/tests/colormgmt.rs +++ b/crates/engine/src/tests/colormgmt.rs @@ -318,6 +318,45 @@ fn convert_query_and_intents() { assert!(s.execute("color.convert", &json!({"color": "#808080", "intent": "vivid"})).is_err()); } +/// `to: "oklch"` answers the OKLCH of the color's display sRGB, which converts back to the color; +/// a CMYK color's display color, not its naive separation, sets them. +#[test] +fn convert_to_oklch_answers_lightness_chroma_and_hue() { + let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner()); + let mut s = session(); + let r = s.execute("color.convert", &json!({"color": "#ff0000", "to": "oklch"})).unwrap(); + assert_eq!(r["model"], "oklch"); + let v: Vec = r["values"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect(); + assert!((v[0] - 62.80).abs() < 0.005 && (v[1] - 0.2577).abs() < 5e-5 && (v[2] - 29.23).abs() < 0.005, "{r}"); + let (rgb, lowered) = vectorcraft_color::oklab::from_oklch(v[0] / 100.0, v[1], v[2]); + assert!(!lowered); + assert_eq!(Color::rgb(rgb[0], rgb[1], rgb[2]).to_hex(), "#ff0000"); + assert_eq!(r["hex"], "#ff0000"); + let gray = s.execute("color.convert", &json!({"color": "#808080", "to": "oklch"})).unwrap(); + assert_eq!(gray["values"][2], 0.0, "{gray}"); + let ink = json!({"c": 1.0, "m": 0.0, "y": 0.0, "k": 0.0}); + let cyan = s.execute("color.convert", &json!({"color": ink, "to": "oklch"})).unwrap(); + let shown = vectorcraft_color::oklab::to_oklch(cms::active().display_rgb(&Color::cmyk(1.0, 0.0, 0.0, 0.0))); + let naive = vectorcraft_color::oklab::to_oklch([0.0, 1.0, 1.0]); + let c: Vec = cyan["values"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect(); + let got = [c[0] / 100.0, c[1], c[2]]; + assert!((0..3).all(|i| (got[i] - shown[i]).abs() < 1e-9) && shown[1] > 0.05, "{cyan} {shown:?}"); + assert!((got[0] - naive[0]).abs() > 0.02, "{cyan} {naive:?}"); + // A Lab color outside sRGB answers the OKLCH of its color clipped to sRGB. + let vivid = s.execute("color.convert", &json!({"color": {"l": 50.0, "a": 100.0, "b": 0.0}, "to": "oklch"})).unwrap(); + let w: Vec = vivid["values"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect(); + let shown = cms::active().display_rgb(&Color::lab(50.0, 100.0, 0.0)).map(|v| v.clamp(0.0, 1.0)); + let clipped = vectorcraft_color::oklab::to_oklch(shown); + assert!((w[0] / 100.0 - clipped[0]).abs() < 1e-9 && (w[1] - clipped[1]).abs() < 1e-9, "{vivid} {clipped:?}"); + assert!((w[2] - clipped[2]).abs() < 1e-9 && (0.0..360.0).contains(&w[2]), "{vivid} {clipped:?}"); + assert!(vectorcraft_color::oklab::in_srgb(vectorcraft_color::oklab::oklch_to_srgb(w[0] / 100.0, w[1], w[2])), "{vivid}"); + // RGB numbers past 0..1 answer the OKLCH of the clipped color `hex` reports: white. + let past = s.execute("color.convert", &json!({"color": [2.0, 2.0, 2.0], "to": "oklch"})).unwrap(); + assert_eq!(past["hex"], "#ffffff"); + let l = past["values"][0].as_f64().unwrap(); + assert!((l - 100.0).abs() < 0.01 && past["values"][1].as_f64().unwrap() < 1e-3, "{past}"); +} + #[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/dcs.rs b/crates/engine/src/tests/dcs.rs index 43bdf180a7..6e385cbb7e 100644 --- a/crates/engine/src/tests/dcs.rs +++ b/crates/engine/src/tests/dcs.rs @@ -1002,6 +1002,27 @@ fn dcs_transparency_counts_a_transparent_dcs_image_over_another() { assert!(marked(b), "the opaque image it overlaps"); } +/// Replace measures a DCS file's clipping group by its bounds, not by its plates' image, so a +/// distorted plate image does not stop an image replacing the group. +#[test] +fn replace_is_not_refused_for_a_dcs_group_whose_image_is_distorted() { + let dir = temp_dir("replace-distorted"); + let path = write(&dir, "pic.eps", &two_plates()); + let mut s = session(); + let r = s.execute("file.place", &json!({ "path": path, "at": [100, 100] })).unwrap(); + let group = r["ids"][0].clone(); + let image = image_of(&s, &group).id; + let b = s.doc().unwrap().doc.node(image).unwrap().geometric_bounds().unwrap(); + let (x0, y0, x1, y1) = (b.x0, b.y0, b.x1, b.y1); + let corners = json!([[x0 + 4.0, y0], [x1 - 4.0, y0], [x1, y1], [x0, y1]]); + s.execute("object.distort", &json!({ "ids": [image.0], "corners": corners })).unwrap(); + assert!(s.doc().unwrap().doc.node(image).unwrap().is_distorted_image()); + s.execute("select.set", &json!({ "ids": [group] })).unwrap(); + let png = crate::tests_links::png(2, 2, [0, 0, 255]); + let out = s.execute("file.place", &json!({"replace": true, "name": "b.png", "dataBase64": vectorcraft_format::base64_encode(&png)})); + assert!(out.is_ok(), "{out:?}"); +} + #[test] fn dcs_transparency_counts_characters_with_a_transparent_gradient() { use vectorcraft_color::{Gradient, GradientKind, GradientPaint, GradientStop}; diff --git a/crates/engine/src/tests/inline.rs b/crates/engine/src/tests/inline.rs index 1d68881b4d..37b72efa77 100644 --- a/crates/engine/src/tests/inline.rs +++ b/crates/engine/src/tests/inline.rs @@ -579,6 +579,9 @@ fn same_as_full_pass(full: &mut Session, fast: &mut Session, step: &dyn Fn(&mut /// natural size or anything else a symbol is measured with checks them all. #[test] fn refreshing_only_changed_trees_matches_the_full_pass() { + // Both sessions lay out type, and the test rescans the fonts: a font another test adds between + // the full pass and the fast one would change how the type resolves in only one of them. + let _fonts = crate::adding_fonts(); let setup = |s: &mut Session| { circle_symbol(s, "Tap", 10.0); circle_symbol(s, "Dot", 6.0); diff --git a/crates/engine/src/tests/links.rs b/crates/engine/src/tests/links.rs index 313d573206..5dd3357641 100644 --- a/crates/engine/src/tests/links.rs +++ b/crates/engine/src/tests/links.rs @@ -588,6 +588,81 @@ fn a_symbols_link_without_a_relative_path_follows_the_moved_file() { assert_eq!(paths, [moved.clone(), moved], "the layers' link, then the symbol's"); } +/// Update Links gives a distorted image its file's new pixels between the same corners: its +/// Placement Options' fill and clip do not move or clip it. Its transform takes the new pixel size, +/// and Link Info measures its scale at its middle. +#[test] +fn update_links_keeps_a_distorted_images_corners() { + let dir = Folder::new("distorted-update"); + let photo = dir.file("photo.png"); + write(&photo, &png(20, 10, RED)); + let mut s = session(); + let id = place(&mut s, &photo); + s.execute("links.placementOptions", &json!({"ids": [id.0], "preserve": "fill", "clip": true})).unwrap(); + s.execute("select.set", &json!({"ids": [id.0]})).unwrap(); + s.execute("object.distort", &json!({"corners": [[240, 300], [260, 300], [300, 400], [200, 400]]})).unwrap(); + let corners = |s: &Session| s.doc().unwrap().doc.node(id).unwrap().image_corners().unwrap(); + let before = corners(&s); + assert!(s.doc().unwrap().doc.node(id).unwrap().is_distorted_image()); + // The far corner of the pixels as the transform alone places them. + let far = |s: &Session| { + let NodeKind::Image(im) = &s.doc().unwrap().doc.node(id).unwrap().kind else { panic!("an image") }; + im.xf * vectorcraft_geom::Point::new(f64::from(im.width), f64::from(im.height)) + }; + let far_before = far(&s); + // Link Info measures the scale where the effective resolution is measured: at the middle. + let scale_matches_ppi = |s: &mut Session| { + let info = s.execute("links.info", &json!({"id": id.0})).unwrap(); + for i in 0..2 { + let (scale, ppi, eff) = (info["scale"][i].as_f64().unwrap(), info["ppi"][i].as_f64().unwrap(), info["effectivePpi"][i].as_f64().unwrap()); + assert!((scale - ppi / eff * 100.0).abs() < 1e-6, "{info}"); + } + }; + scale_matches_ppi(&mut s); + // A copy in a symbol, distorted the same way, shows the same file. + let copy = place(&mut s, &photo); + s.execute("links.placementOptions", &json!({"ids": [copy.0], "preserve": "fill", "clip": true})).unwrap(); + s.execute("select.set", &json!({"ids": [copy.0]})).unwrap(); + s.execute("object.distort", &json!({"corners": [[240, 300], [260, 300], [300, 400], [200, 400]]})).unwrap(); + s.execute("symbol.new", &json!({"name": "Mark", "ids": [copy.0]})).unwrap(); + let in_symbol = |s: &Session| { + let mut out = vec![]; + s.doc().unwrap().doc.symbols[0].art.walk(&mut |n| { + if let NodeKind::Image(im) = &n.kind { + out.push((n.is_distorted_image(), (im.width, im.height))); + } + }); + out + }; + let symbol_corners = |s: &Session| { + let mut out = vec![]; + s.doc().unwrap().doc.symbols[0].art.walk(&mut |n| out.extend(n.image_corners())); + out + }; + assert_eq!(in_symbol(&s), [(true, (20, 10))]); + let symbol_before = symbol_corners(&s); + assert_eq!(symbol_before.len(), 1); + write(&photo, &png(60, 20, BLUE)); + let u = s.execute("links.update", &json!({})).unwrap(); + assert_eq!(u["updated"].as_array().unwrap().len(), 2, "{u}"); + let d = &s.doc().unwrap().doc; + let n = d.node(id).unwrap(); + assert!(n.is_distorted_image()); + assert_eq!(corners(&s), before); + let NodeKind::Image(im) = &n.kind else { panic!("an image") }; + assert_eq!((im.width, im.height), (60, 20)); + // The transform takes the new pixel size, so a placement by the transform keeps the old size. + assert!(far(&s).distance(far_before) < 1e-9, "{:?} vs {far_before:?}", far(&s)); + let d = &s.doc().unwrap().doc; + assert!(!matches!(d.parent_of(id).and_then(|p| d.node(p)).map(|p| &p.kind), Some(NodeKind::Group { clip: true, .. })), "not clipped"); + let mut clipped = false; + d.symbols[0].art.walk(&mut |n| clipped |= matches!(n.kind, NodeKind::Group { clip: true, .. })); + assert!(!clipped, "the symbol's image is not clipped"); + assert_eq!(in_symbol(&s), [(true, (60, 20))]); + assert_eq!(symbol_corners(&s), symbol_before, "the symbol's image keeps its corners"); + scale_matches_ppi(&mut s); +} + /// Update Links reads a changed file again for the images inside symbols, patterns and opacity /// masks too: those showing the same content as an image in the layers, and those no object in the /// layers shows. Each takes the file's place as its own Placement Options say, in one undo step, diff --git a/crates/engine/src/tests/livecorners.rs b/crates/engine/src/tests/livecorners.rs index 1ea6e5091f..288f0236d1 100644 --- a/crates/engine/src/tests/livecorners.rs +++ b/crates/engine/src/tests/livecorners.rs @@ -59,6 +59,107 @@ fn a_whole_rectangle_rounds_all_corners_and_given_corners_alone() { assert_eq!(corners(&s, id).1[3], CornerKind::Chamfer); } +/// The Corner menus of Rectangle Properties: a kind for all four corners or one, set on corners +/// with no radius too and leaving the radii as they are, in one undo step; the kind the corners +/// already have adds no step. +#[test] +fn rectangle_kind_menu_targets_all_or_one_corner_and_skips_noop_undo() { + let (mut s, id) = session(); + run(&mut s, json!({"corners": [1], "radius": 12})); + let steps = |s: &Session| s.doc().unwrap().history.undo.len(); + let undo = steps(&s); + run(&mut s, json!({"corners": [0, 1, 2, 3], "kind": "invertedRound"})); + assert_eq!(corners(&s, id).0, [0.0, 12.0, 0.0, 0.0]); + assert_eq!(corners(&s, id).1, [CornerKind::InvertedRound; 4]); + assert_eq!(steps(&s), undo + 1); + run(&mut s, json!({"corners": [0, 1, 2, 3], "kind": "invertedRound"})); + run(&mut s, json!({"corners": [2], "kind": "invertedRound"})); + assert_eq!(steps(&s), undo + 1, "no step when nothing changes"); + run(&mut s, json!({"corners": [2], "kind": "chamfer"})); + assert_eq!(corners(&s, id).1, [CornerKind::InvertedRound, CornerKind::InvertedRound, CornerKind::Chamfer, CornerKind::InvertedRound]); + assert_eq!(corners(&s, id).0, [0.0, 12.0, 0.0, 0.0]); + assert_eq!(steps(&s), undo + 2); +} + +/// A kind the corners already have leaves a rectangle saved stretched by an older version as it +/// is, alone or beside a rectangle the kind changes: its scale stays in its transform. +#[test] +fn a_kind_the_corners_have_leaves_a_stretched_rectangle() { + let (mut s, id) = session(); + let other = NodeId(s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 40, "height": 40})).unwrap()["id"].as_u64().unwrap()); + let stretched = LiveShape::Rectangle { + w: 50.0, + h: 60.0, + radii: [10.0; 4], + kinds: [CornerKind::Chamfer; 4], + radii_relative: false, + xf: Affine::translate((10.0, 10.0)) * Affine::scale_non_uniform(2.0, 1.0), + }; + { + let d = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let NodeKind::Path { path, live: Some(live), .. } = &mut d.node_mut(id).unwrap().kind else { panic!("not live") }; + **live = stretched.clone(); + *path = live.to_path(); + } + let live = |s: &Session| node_path(s, id).1; + let steps = |s: &Session| s.doc().unwrap().history.undo.len(); + let undo = steps(&s); + run(&mut s, json!({"ids": [id.0], "kind": "chamfer"})); + assert_eq!(live(&s), Some(stretched.clone())); + assert_eq!(steps(&s), undo, "no step when nothing changes"); + run(&mut s, json!({"ids": [id.0, other.0], "kind": "chamfer"})); + assert_eq!(live(&s), Some(stretched)); + assert_eq!(corners(&s, other).1, [CornerKind::Chamfer; 4]); + assert_eq!(steps(&s), undo + 1); +} + +/// A radius is stored on a corner that stores a larger radius drawn at the new value, alone or +/// beside another rectangle; the radius every target already stores adds no undo step. +#[test] +fn a_radius_reaches_a_rectangle_that_already_draws_it() { + let (mut s, id) = session(); + let other = NodeId(s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 100, "height": 60})).unwrap()["id"].as_u64().unwrap()); + // 80 pt on every corner draws at 30 pt, half the 60 pt side. + run(&mut s, json!({"ids": [id.0], "radius": 80})); + assert_eq!(corners(&s, id).0, [80.0; 4]); + let (path, live) = node_path(&s, id); + let drawn = LiveCorners::new(&path, live.as_ref()).unwrap().drawn_radius(0); + assert!((drawn - 30.0).abs() < 1e-9, "draws at {drawn}"); + let steps = |s: &Session| s.doc().unwrap().history.undo.len(); + let undo = steps(&s); + run(&mut s, json!({"ids": [id.0], "corners": [1], "radius": 30})); + assert_eq!(corners(&s, id).0, [80.0, 30.0, 80.0, 80.0]); + assert_eq!(steps(&s), undo + 1); + run(&mut s, json!({"ids": [id.0, other.0], "corners": [0], "radius": 30})); + assert_eq!(corners(&s, id).0[0], 30.0); + assert_eq!(corners(&s, other).0[0], 30.0); + // The radius both already store adds no step. + run(&mut s, json!({"ids": [id.0, other.0], "corners": [0], "radius": 30})); + assert_eq!(steps(&s), undo + 2); +} + +/// `rectanglesOnly` sets the live rectangles among the selection and leaves a polygon as it is; an +/// action that records it holds no ids, so playing it sets the rectangles selected then. +#[test] +fn rectangles_only_sets_the_selected_rectangles_when_an_action_plays() { + let (mut s, id) = session(); + let polygon = NodeId(s.execute("shape.polygon", &json!({"cx": 300, "cy": 300, "radius": 40, "sides": 6})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [id.0, polygon.0]})).unwrap(); + let start = s.journal.len(); + run(&mut s, json!({"rectanglesOnly": true, "corners": [0], "kind": "chamfer"})); + assert_eq!(corners(&s, id).1[0], CornerKind::Chamfer); + let NodeKind::Path { live: Some(l), .. } = &s.doc().unwrap().doc.node(polygon).unwrap().kind else { panic!("not live") }; + let LiveShape::Polygon { kinds, .. } = &**l else { panic!("not a polygon") }; + assert!(kinds.iter().all(|k| *k == CornerKind::Round), "the polygon keeps its corners: {kinds:?}"); + let action = s.journal_for_action(start); + assert_eq!(action.len(), 1); + assert_eq!(action[0].1.get("ids"), None); + let other = NodeId(s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 40, "height": 40})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [other.0, polygon.0]})).unwrap(); + s.replay(&action[0].0, &action[0].1).unwrap(); + assert_eq!(corners(&s, other).1[0], CornerKind::Chamfer); +} + /// #938: `items` rounds several objects in one step, each its own corners (or all of them). #[test] fn items_round_several_objects_each_its_own_corners() { diff --git a/crates/engine/src/tests/params.rs b/crates/engine/src/tests/params.rs index ca72e66eec..38958ee4c8 100644 --- a/crates/engine/src/tests/params.rs +++ b/crates/engine/src/tests/params.rs @@ -707,12 +707,13 @@ fn an_effect_parameter_without_a_default_is_held_to_its_type() { use crate::cmd::params::undefaulted_type; use vectorcraft_render::effects::effect_catalog; // Read by checks of their own: a stored texture or a texture to load, an SVG filter and its axes, a Warp's - // map and the style of Crop Marks. + // map, the style of Crop Marks and a custom bevel's name and points. let own_check = |effect: &str, key: &str| match key { "textureImage" | "name" | "xml" => true, "axes" => effect == "svg.filter", "version" => effect.starts_with("warp."), "style" => effect == "cropMarks", + "bevelName" | "bevelProfile" => matches!(effect, "threeD.extrude" | "threeD.classicExtrude"), _ => false, }; let mut unlisted = vec![]; diff --git a/crates/engine/src/tests/pathops.rs b/crates/engine/src/tests/pathops.rs index dff77c1ce4..feb71e40ad 100644 --- a/crates/engine/src/tests/pathops.rs +++ b/crates/engine/src/tests/pathops.rs @@ -1907,6 +1907,166 @@ fn pathfinder_journal_entries_replay_with_the_options_they_used() { assert!(s.execute("object.pathfinder.divide", &json!({"precision": 20})).is_err()); } +/// The leaf objects of `n`, in paint order. +fn leaves_of(n: &vectorcraft_doc::Node, out: &mut Vec) { + match n.children() { + Some(children) => children.iter().for_each(|c| leaves_of(c, out)), + None => out.push(n.clone()), + } +} + +/// Apply the live Pathfinder effect `effect` with `params` to the selection, then expand its +/// appearance: the objects it draws. +fn live_pieces(s: &mut Session, effect: &str, params: Value) -> Vec { + let g = ids(&s.execute("effect.apply", &json!({"effect": effect, "params": params})).unwrap())[0]; + s.execute("effect.expandAppearance", &json!({"ids": [g.0]})).unwrap(); + let mut out = vec![]; + leaves_of(&node(s, g), &mut out); + out +} + +/// The parameters of the first effect of the selected object. +fn first_effect_params(s: &Session) -> Value { + let st = s.doc().unwrap(); + st.doc.node(st.selection.objects[0]).unwrap().appearance.effects[0].params.clone() +} + +/// A Pathfinder effect keeps the Pathfinder Options in force when it is applied, those its params +/// give aside, and its journal entry carries them. +#[test] +fn a_pathfinder_effect_keeps_the_options_in_force_when_applied() { + let mut s = session(); + let (a, b) = (rect(&mut s, 0.0, 0.0, 100.0, 100.0), rect(&mut s, 50.0, 50.0, 100.0, 100.0)); + s.execute("object.pathfinder.options", &json!({"precision": 1, "removeRedundantPoints": true, "removeUnpainted": true})).unwrap(); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("effect.apply", &json!({"effect": "pathfinder.divide"})).unwrap(); + let all = json!({"precision": 1.0, "removeRedundantPoints": true, "removeUnpainted": true}); + assert_eq!(first_effect_params(&s), all); + assert_eq!(s.journal.last().unwrap().1["params"], all, "the journal entry gives the options it used"); + s.execute("effect.apply", &json!({"effect": "pathfinder.softMix", "params": {"precision": 0.5}})).unwrap(); + let st = s.doc().unwrap(); + let mix = &st.doc.node(st.selection.objects[0]).unwrap().appearance.effects[1].params; + assert_eq!(mix, &json!({"mixingRate": 50.0, "precision": 0.5, "removeRedundantPoints": true, "removeUnpainted": true})); +} + +/// A live Pathfinder effect evaluates with its own options as the panel's operations do with +/// Pathfinder Options: a precision of 1 pt drops a 0.5 pt overlap, Divide leaves out an unfilled +/// object's pieces, and Remove Redundant Points drops an anchor that shapes nothing. +#[test] +fn a_pathfinder_effect_evaluates_with_its_own_options() { + for (precision, faces) in [(0.01, 3), (1.0, 2)] { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + let b = rect(&mut s, 0.0, 99.5, 100.0, 100.0); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + assert_eq!(live_pieces(&mut s, "pathfinder.divide", json!({"precision": precision})).len(), faces, "precision {precision}"); + } + for on in [false, true] { + let mut s = session(); + filled_and_unfilled(&mut s); + let divided = live_pieces(&mut s, "pathfinder.divide", json!({"removeUnpainted": on})); + let unfilled = divided.iter().filter(|n| n.appearance.fill_paint().is_none()).count(); + assert_eq!((unfilled, divided.len() - unfilled), (if on { 0 } else { 2 }, 1), "removeUnpainted {on}"); + } + for on in [false, true] { + let mut s = session(); + let pts = [(0.0, 0.0), (50.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)]; + let anchors: Vec = pts.iter().map(|(x, y)| json!({"x": x, "y": y})).collect(); + let a = NodeId(s.execute("path.create", &json!({"anchors": anchors, "closed": true})).unwrap()["id"].as_u64().unwrap()); + let b = rect(&mut s, 20.0, 20.0, 60.0, 60.0); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + let united = live_pieces(&mut s, "pathfinder.add", json!({"removeRedundantPoints": on})); + let count = united[0].path_data().unwrap().anchor_count(); + assert!(if on { count == 4 } else { count > 4 }, "removeRedundantPoints {on}: {count} anchors"); + } +} + +/// An effect saved before Pathfinder effects kept their own options draws as one given their +/// defaults, so older documents look as they did. +#[test] +fn a_pathfinder_effect_saved_without_options_draws_as_before() { + let draw = |params: Value| { + let mut s = session(); + filled_and_unfilled(&mut s); + let g = ids(&s.execute("effect.apply", &json!({"effect": "pathfinder.divide"})).unwrap())[0]; + s.edit("t", |d, _| { + d.node_mut(g).unwrap().appearance.effects[0].params = params; + Ok(()) + }) + .unwrap(); + s.execute("effect.expandAppearance", &json!({"ids": [g.0]})).unwrap(); + serde_json::to_value(node(&s, g)).unwrap() + }; + assert_eq!(draw(json!({})), draw(json!({"precision": 0.01, "removeRedundantPoints": false, "removeUnpainted": false}))); +} + +/// `effect.setParams` edits a Pathfinder effect's options as one undo step, records none for the +/// values it already evaluates with, and refuses values out of range or of the wrong type. +#[test] +fn pathfinder_effect_options_edit_as_one_step_and_refuse_bad_values() { + let mut s = session(); + let (a, b) = (rect(&mut s, 0.0, 0.0, 100.0, 100.0), rect(&mut s, 50.0, 50.0, 100.0, 100.0)); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("effect.apply", &json!({"effect": "pathfinder.add"})).unwrap(); + let steps = |s: &Session| s.doc().unwrap().history.undo.len(); + let doc = |s: &Session| serde_json::to_value(&*s.doc().unwrap().doc).unwrap(); + let before = steps(&s); + let same = s.execute("effect.setParams", &json!({"index": 0, "params": {"precision": 0.01, "removeUnpainted": false}})).unwrap(); + assert_eq!((same, steps(&s)), (json!({"ids": []}), before), "the values it has: no step"); + // An effect saved without options evaluates with the defaults: given them, it is unchanged. + let g = s.doc().unwrap().selection.objects[0]; + s.edit("t", |d, _| { + d.node_mut(g).unwrap().appearance.effects[0].params = json!({}); + Ok(()) + }) + .unwrap(); + let before = steps(&s); + let defaults = json!({"index": 0, "params": {"precision": 0.01, "removeRedundantPoints": false, "removeUnpainted": false}}); + assert_eq!(s.execute("effect.setParams", &defaults).unwrap(), json!({"ids": []})); + assert_eq!(steps(&s), before); + s.execute("effect.setParams", &json!({"index": 0, "params": {"precision": 2, "removeRedundantPoints": true}})).unwrap(); + assert_eq!(steps(&s), before + 1, "one step"); + assert_eq!(first_effect_params(&s), json!({"precision": 2, "removeRedundantPoints": true})); + let kept = doc(&s); + for bad in [ + json!({"precision": 0}), + json!({"precision": 11}), + json!({"precision": "1 pt"}), + json!({"precision": null}), + json!({"removeRedundantPoints": "yes"}), + json!({"removeUnpainted": 1}), + ] { + assert!(s.execute("effect.setParams", &json!({"index": 0, "params": bad})).is_err(), "setParams {bad}"); + assert!(s.execute("effect.apply", &json!({"effect": "pathfinder.trim", "params": bad})).is_err(), "apply {bad}"); + assert_eq!(doc(&s), kept, "{bad} changes nothing"); + } + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(first_effect_params(&s), json!({}), "undo restores the options"); +} + +/// A precision that Scale Strokes & Effects took past the range evaluates at its bound, and setting +/// the bound is still an edit: a later scale then starts from the value set. +#[test] +fn a_precision_set_after_a_scale_past_its_range_is_kept() { + let mut s = session(); + let (a, b) = (rect(&mut s, 0.0, 0.0, 100.0, 100.0), rect(&mut s, 50.0, 50.0, 100.0, 100.0)); + s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap(); + s.execute("effect.apply", &json!({"effect": "pathfinder.add", "params": {"precision": 8}})).unwrap(); + let precision = |s: &Session| first_effect_params(s)["precision"].as_f64(); + s.execute("object.scale", &json!({"sx": 200, "strokes": true})).unwrap(); + assert_eq!(precision(&s), Some(16.0)); + let steps = s.doc().unwrap().history.undo.len(); + let out = s.execute("effect.setParams", &json!({"index": 0, "params": {"precision": 10}})).unwrap(); + assert_ne!(out, json!({"ids": []}), "an edit"); + assert_eq!((precision(&s), s.doc().unwrap().history.undo.len()), (Some(10.0), steps + 1)); + s.execute("object.scale", &json!({"sx": 50, "strokes": true})).unwrap(); + assert_eq!(precision(&s), Some(5.0)); + // The value it stores is still no edit. + let steps = s.doc().unwrap().history.undo.len(); + assert_eq!(s.execute("effect.setParams", &json!({"index": 0, "params": {"precision": 5}})).unwrap(), json!({"ids": []})); + assert_eq!(s.doc().unwrap().history.undo.len(), steps); +} + /// A single group containing multiple overlapping paths is accepted by Crop. #[test] fn crop_operates_on_a_single_selected_group_of_paths() { diff --git a/crates/engine/src/tests/quickpen.rs b/crates/engine/src/tests/quickpen.rs index 66283183b9..f14be809b4 100644 --- a/crates/engine/src/tests/quickpen.rs +++ b/crates/engine/src/tests/quickpen.rs @@ -127,6 +127,25 @@ fn c_flips_and_brackets_size_the_last_sharp_arc() { assert!(!s.tool_claims_key(ToolKey::Letter('c'), view())); } +/// The drawing end (where the Quick Pen toolbar sits beside) is the path's last point with the +/// direction it arrives in: none before the first click, no direction for one point, and none +/// once Escape ends the path. +#[test] +fn the_drawing_end_is_the_last_point_and_its_direction() { + let mut s = session(); + quick_pen(&mut s); + assert_eq!(s.tool_drawing_end(view()), None); + click(&mut s, 100.0, 100.0); + assert_eq!(s.tool_drawing_end(view()), Some((pt(100.0, 100.0), None))); + click(&mut s, 100.0, 200.0); + let (p, dir) = s.tool_drawing_end(view()).unwrap(); + assert_eq!(p, pt(100.0, 200.0)); + let dir = dir.unwrap(); + assert!(dir.x.abs() < 1e-9 && dir.y > 0.99, "arrives heading down: {dir:?}"); + key(&mut s, ToolKey::Escape); + assert_eq!(s.tool_drawing_end(view()), None); +} + /// Alt tapped during a drag draws the piece with the next action: a continuous arc becomes a /// sharp-corner arc with a corner where it starts, and the path goes on drawing after it. #[test] @@ -183,6 +202,251 @@ fn escape_ends_the_path_and_a_drag_places_the_piece() { assert_eq!(paths(&s).len(), 2); } +/// The piece a press draws ends where the press is let go, past the last drag too, and a press let +/// go a drag's distance away with no drag in between places it there as well. +#[test] +fn the_piece_ends_where_the_press_is_let_go() { + let mut s = session(); + quick_pen(&mut s); + click(&mut s, 100.0, 100.0); + let v = view(); + s.pointer(&PointerEvent::new(PointerKind::Down, 150.0, 100.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 180.0, 120.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 250.0, 150.0), v).unwrap(); + assert_eq!(only_path(&s).anchors.last().unwrap().p, pt(250.0, 150.0)); + let undo = undo_steps(&s); + s.pointer(&PointerEvent::new(PointerKind::Down, 300.0, 100.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 340.0, 100.0), v).unwrap(); + assert_eq!(only_path(&s).anchors.last().unwrap().p, pt(340.0, 100.0)); + assert_eq!(undo_steps(&s), undo + 1); +} + +/// C and `[` `]` during a drag change the sharp-corner arc being dragged, within the press's one +/// undo step. +#[test] +fn c_and_brackets_during_a_drag_change_the_arc_being_dragged() { + let mut s = session(); + quick_pen(&mut s); + s.set_tool_option_cmd(&json!({"tool": "quickPen", "key": "action", "value": "sharpArc"})).unwrap(); + click(&mut s, 100.0, 300.0); + let undo = undo_steps(&s); + let v = view(); + s.pointer(&PointerEvent::new(PointerKind::Down, 280.0, 300.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 300.0, 300.0), v).unwrap(); + assert!(s.tool_claims_key(ToolKey::Letter('c'), view())); + key(&mut s, ToolKey::Letter('c')); + assert!(only_path(&s).anchors.get(1).unwrap().p.distance(pt(200.0, 400.0)) < 1e-9, "flipped while dragging"); + key(&mut s, ToolKey::BracketLeft); + assert_eq!(s.tool_options()["turn"], 165.0); + // A 165° arc is two segments, and its middle point lies the arc's sagitta below the chord + // (a 180° arc's lies 100 below). + let half = 82.5f64.to_radians(); + let mid_165 = pt(200.0, 300.0 + 100.0 / half.sin() * (1.0 - half.cos())); + assert_eq!(only_path(&s).anchors.len(), 3); + assert!(only_path(&s).anchors.get(1).unwrap().p.distance(mid_165) < 1e-6, "the dragged arc is 165°"); + s.pointer(&PointerEvent::new(PointerKind::Up, 300.0, 300.0), v).unwrap(); + let sp = only_path(&s); + assert_eq!(sp.anchors.len(), 3); + assert!(sp.anchors.get(1).unwrap().p.distance(mid_165) < 1e-6, "the flip and the size stay after the release"); + assert_eq!(undo_steps(&s), undo + 1); +} + +/// An edit made by another command during a drag ends the path: the next drag does not draw over +/// the edit, the piece stays as last shown, and the next click starts a new path. +#[test] +fn an_edit_during_a_drag_ends_the_path() { + let mut s = session(); + quick_pen(&mut s); + click(&mut s, 100.0, 100.0); + click(&mut s, 200.0, 100.0); + let id = paths(&s)[0].0; + let v = view(); + s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 180.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 200.0), v).unwrap(); + s.execute("path.moveAnchor", &json!({"id": id.0, "anchor": 0, "x": 90, "y": 90})).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 250.0, 250.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 260.0, 260.0), v).unwrap(); + let ends: Vec = only_path(&s).anchors.iter().map(|a| a.p).collect(); + assert_eq!(ends, [pt(90.0, 90.0), pt(200.0, 100.0), pt(200.0, 200.0)], "the edit and the piece as last shown"); + click(&mut s, 400.0, 400.0); + assert_eq!(paths(&s).len(), 2, "a new path"); +} + +/// With Real-time Drawing off, a sharp-corner arc let go past the last drag is placed where it was +/// let go, and C then flips that arc. +#[test] +fn a_deferred_arc_let_go_past_the_last_drag_flips() { + let mut s = session(); + s.execute("prefs.set", &json!({"key": "realTimeDrawing", "value": false})).unwrap(); + quick_pen(&mut s); + s.set_tool_option_cmd(&json!({"tool": "quickPen", "key": "action", "value": "sharpArc"})).unwrap(); + click(&mut s, 100.0, 300.0); + let v = view(); + s.pointer(&PointerEvent::new(PointerKind::Down, 250.0, 300.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 270.0, 300.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 300.0, 300.0), v).unwrap(); + let sp = only_path(&s); + assert_eq!(sp.anchors.len(), 3); + assert_eq!(sp.anchors.last().unwrap().p, pt(300.0, 300.0)); + let mid = sp.anchors.get(1).unwrap().p; + key(&mut s, ToolKey::Letter('c')); + let flipped = only_path(&s); + assert_eq!(flipped.anchors.len(), 3); + assert!(flipped.anchors.get(1).unwrap().p.distance(pt(200.0, 600.0 - mid.y)) < 1e-9, "flipped across the chord"); +} + +/// An edit made by another command to the path's look during a drag ends the path too. +#[test] +fn a_look_edit_during_a_drag_ends_the_path() { + let mut s = session(); + quick_pen(&mut s); + click(&mut s, 100.0, 100.0); + click(&mut s, 200.0, 100.0); + let id = paths(&s)[0].0; + let v = view(); + s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 180.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 200.0), v).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [id.0], "color": "#00ff00"})).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 260.0, 260.0), v).unwrap(); + let ends: Vec = only_path(&s).anchors.iter().map(|a| a.p).collect(); + assert_eq!(ends, [pt(100.0, 100.0), pt(200.0, 100.0), pt(200.0, 200.0)], "the piece as last shown"); + click(&mut s, 400.0, 400.0); + assert_eq!(paths(&s).len(), 2, "a new path"); +} + +/// An edit made by another command to another object during a drag stays and ends the path: the +/// press previews no more, its piece stays as last shown, and the next click starts a new path. +#[test] +fn an_edit_to_another_object_during_a_drag_stays() { + let mut s = session(); + s.execute("shape.rectangle", &json!({"x": 500, "y": 400, "width": 50, "height": 50})).unwrap(); + let rect = s.doc().unwrap().selection.objects[0]; + quick_pen(&mut s); + click(&mut s, 100.0, 100.0); + click(&mut s, 200.0, 100.0); + let v = view(); + s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 180.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 200.0), v).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [rect.0], "color": "#00ff00"})).unwrap(); + let edited = s.doc().unwrap().doc.node(rect).unwrap().clone(); + s.pointer(&PointerEvent::new(PointerKind::Up, 260.0, 260.0), v).unwrap(); + assert_eq!(*s.doc().unwrap().doc.node(rect).unwrap(), edited, "the other object's edit stays"); + let pen = paths(&s).into_iter().find(|(id, _)| *id != rect).unwrap().1; + let ends: Vec = pen.subpaths[0].anchors.iter().map(|a| a.p).collect(); + assert_eq!(ends, [pt(100.0, 100.0), pt(200.0, 100.0), pt(200.0, 200.0)], "the piece as last shown"); + click(&mut s, 400.0, 400.0); + assert_eq!(paths(&s).len(), 3, "a new path"); +} + +/// With Real-time Drawing off, a drag during which another command edits the path adds no piece, +/// and the edit stays. +#[test] +fn an_edit_during_a_deferred_drag_stays() { + let mut s = session(); + s.execute("prefs.set", &json!({"key": "realTimeDrawing", "value": false})).unwrap(); + quick_pen(&mut s); + click(&mut s, 100.0, 100.0); + click(&mut s, 200.0, 100.0); + let id = paths(&s)[0].0; + let v = view(); + s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 180.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 200.0), v).unwrap(); + s.execute("path.moveAnchor", &json!({"id": id.0, "anchor": 0, "x": 90, "y": 90})).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 250.0, 250.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 260.0, 260.0), v).unwrap(); + let ends: Vec = only_path(&s).anchors.iter().map(|a| a.p).collect(); + assert_eq!(ends, [pt(90.0, 90.0), pt(200.0, 100.0)], "the edit, and no piece"); +} + +/// An edit made by another command to another object during a click stays, and the path goes on: +/// a click previews its piece only when the press begins. +#[test] +fn an_edit_to_another_object_during_a_click_stays() { + let mut s = session(); + s.execute("shape.rectangle", &json!({"x": 500, "y": 400, "width": 50, "height": 50})).unwrap(); + let rect = s.doc().unwrap().selection.objects[0]; + quick_pen(&mut s); + click(&mut s, 100.0, 100.0); + click(&mut s, 200.0, 100.0); + let v = view(); + s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 200.0), v).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [rect.0], "color": "#00ff00"})).unwrap(); + let edited = s.doc().unwrap().doc.node(rect).unwrap().clone(); + s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, 200.0), v).unwrap(); + assert_eq!(*s.doc().unwrap().doc.node(rect).unwrap(), edited, "the other object's edit stays"); + click(&mut s, 300.0, 200.0); + let all = paths(&s); + assert_eq!(all.len(), 2, "no new path"); + let pen = all.into_iter().find(|(id, _)| *id != rect).unwrap().1; + let ends: Vec = pen.subpaths[0].anchors.iter().map(|a| a.p).collect(); + assert_eq!(ends, [pt(100.0, 100.0), pt(200.0, 100.0), pt(200.0, 200.0), pt(300.0, 200.0)]); +} + +/// An edit made by another command during a click (a press let go where it went down) ends the +/// path too: the next click starts a new path instead of drawing over the edit. +#[test] +fn an_edit_during_a_click_ends_the_path() { + let mut s = session(); + quick_pen(&mut s); + click(&mut s, 100.0, 100.0); + click(&mut s, 200.0, 100.0); + let id = paths(&s)[0].0; + let v = view(); + s.pointer(&PointerEvent::new(PointerKind::Down, 200.0, 180.0), v).unwrap(); + s.execute("path.moveAnchor", &json!({"id": id.0, "anchor": 0, "x": 90, "y": 90})).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 200.0, 180.0), v).unwrap(); + click(&mut s, 400.0, 400.0); + assert_eq!(paths(&s).len(), 2, "a new path"); + let ends: Vec = paths(&s)[0].1.subpaths[0].anchors.iter().map(|a| a.p).collect(); + assert_eq!(ends, [pt(90.0, 90.0), pt(200.0, 100.0), pt(200.0, 180.0)], "the edit stays"); +} + +/// With Align New Objects to Pixel Grid on, the path the tool draws is pixel-aligned: its points +/// move onto the grid, and the next click and drag still go on drawing the same path. +#[test] +fn a_pixel_aligned_path_goes_on_drawing() { + let mut s = session(); + s.execute("document.setup", &json!({"alignNewObjectsToPixelGrid": true})).unwrap(); + quick_pen(&mut s); + click(&mut s, 100.0, 100.0); + click(&mut s, 200.0, 100.0); + let ends = |s: &Session| only_path(s).anchors.iter().map(|a| a.p).collect::>(); + let two = ends(&s); + assert_eq!(two.len(), 2); + assert_eq!(two[0].y, two[1].y, "a level line"); + press(&mut s, &[(300.0, 150.0), (310.0, 170.0), (320.0, 200.0)]); + let three = ends(&s); + assert_eq!(three.len(), 3, "one path of three points"); + assert_eq!(three[..2], two[..], "the points before the piece stay as they were"); + assert!(three[2].distance(pt(320.0, 200.0)) <= 1.0, "the drag's piece ends near where it was let go: {:?}", three[2]); + click(&mut s, 400.0, 100.0); + let four = ends(&s); + assert_eq!(four.len(), 4); + assert_eq!(four[..3], three[..]); +} + +/// A dropped press takes back only its own piece, and with Real-time Drawing off a drag places its +/// piece on the release: in both cases the next click goes on drawing the same path. +#[test] +fn a_dropped_press_and_a_deferred_drag_keep_the_path() { + let mut s = session(); + quick_pen(&mut s); + click(&mut s, 100.0, 100.0); + click(&mut s, 200.0, 100.0); + let v = view(); + s.pointer(&PointerEvent::new(PointerKind::Down, 300.0, 100.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 320.0, 150.0), v).unwrap(); + s.drop_tool_press(v).unwrap(); + assert_eq!(only_path(&s).anchors.len(), 2, "the dropped piece is gone"); + click(&mut s, 300.0, 200.0); + assert_eq!(only_path(&s).anchors.len(), 3, "the path goes on"); + s.execute("prefs.set", &json!({"key": "realTimeDrawing", "value": false})).unwrap(); + press(&mut s, &[(400.0, 200.0), (420.0, 250.0), (450.0, 300.0)]); + assert_eq!(only_path(&s).anchors.last().unwrap().p, pt(450.0, 300.0)); + click(&mut s, 500.0, 100.0); + assert_eq!(only_path(&s).anchors.len(), 5, "the path goes on after the deferred piece"); +} + /// An anchor moved by another command ends the path being drawn: C does not flip the old arc back /// over the edit, and the next click starts a new path instead of rebuilding the old one. #[test] diff --git a/crates/engine/src/tests/recolor.rs b/crates/engine/src/tests/recolor.rs index b2664a9682..fe87c1f7a0 100644 --- a/crates/engine/src/tests/recolor.rs +++ b/crates/engine/src/tests/recolor.rs @@ -133,6 +133,174 @@ fn colors_with_nothing_selected_leave_out_what_select_all_leaves_out() { assert_eq!(hexes(&run(&mut s, "recolor.colors", json!({"ids": [hidden.0]}))), ["#0000ff"]); } +#[test] +fn used_colors_list_the_most_used_first_with_their_colors() { + let mut s = session(); + let reds: Vec = (0..3).map(|_| rect(&mut s, json!("#ff0000"))).collect(); + let blue = rect(&mut s, json!({"c": 100, "m": 100, "y": 0, "k": 0})); + run(&mut s, "select.set", json!({"ids": []})); + let r = run(&mut s, "color.used", json!({})); + assert_eq!(r["selection"], false, "{r}"); + let colors = r["colors"].as_array().unwrap(); + assert_eq!(colors.len(), 2, "{r}"); + assert_eq!((colors[0]["key"].as_str(), colors[0]["hex"].as_str(), colors[0]["count"].as_u64()), (Some("rgb 255 0 0"), Some("#ff0000"), Some(3))); + assert_eq!(colors[1]["count"], 1); + let first = run(&mut s, "color.used", json!({"limit": 1})); + assert_eq!(first["colors"], json!([colors[0]]), "`limit` keeps the most used"); + assert_eq!((r["uses"].clone(), first["uses"].clone()), (json!(4), json!(4)), "`uses` counts every color"); + // `color` is the color in its own model, which the paint commands take back. + assert_eq!(colors[1]["color"]["model"], "cmyk", "{r}"); + assert!(close(color_value(&colors[1]["color"]).unwrap(), fill(&s, blue))); + // The selection's colors while something is selected; `selection: false` reads all the art. + run(&mut s, "select.set", json!({"ids": [blue.0]})); + let r = run(&mut s, "color.used", json!({})); + assert_eq!((r["selection"].clone(), r["colors"].as_array().unwrap().len()), (json!(true), 1), "{r}"); + let all = run(&mut s, "color.used", json!({"selection": false})); + assert_eq!((all["selection"].clone(), all["colors"][0]["count"].clone()), (json!(false), json!(3)), "{all}"); + assert_eq!(s.doc().unwrap().selection.objects, [blue], "the selection is left as it was"); + // A hidden object's color is left out with nothing selected, as Select All leaves it out. + run(&mut s, "object.hide", json!({"ids": [reds[0].0]})); + assert_eq!(run(&mut s, "color.used", json!({"selection": false}))["colors"][0]["count"], 2); + let e = s.execute("color.used", &json!({"selection": "no"})).unwrap_err().to_string(); + assert!(e.contains("`selection` must be true or false"), "{e}"); + assert!(s.execute("color.used", &json!({"ids": [blue.0]})).is_err(), "an unknown key is refused"); +} + +#[test] +fn used_colors_name_the_swatch_and_tint_a_color_is_linked_to() { + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": {"c": 0, "m": 100, "y": 60, "k": 0}, "spot": true})); + let tinted = rect(&mut s, json!("#000000")); + run(&mut s, "paint.setFill", json!({"ids": [tinted.0], "swatch": "Ink", "tint": 40})); + run(&mut s, "select.set", json!({"ids": []})); + let r = run(&mut s, "color.used", json!({})); + let c = &r["colors"][0]; + assert_eq!(c["swatch"].as_str(), Some("Ink"), "{r}"); + assert!((c["tint"].as_f64().unwrap() - 40.0).abs() < 1e-4, "{r}"); + // recolor.colors keeps its own fields. + assert_eq!(run(&mut s, "recolor.colors", json!({}))["colors"][0].get("tint"), None); + // A swatch of paper white looks the same at every tint; the tint comes from the paint. + run(&mut s, "swatch.new", json!({"name": "Paper", "color": {"c": 0, "m": 0, "y": 0, "k": 0}, "spot": true})); + let paper = rect(&mut s, json!("#000000")); + run(&mut s, "paint.setFill", json!({"ids": [paper.0], "swatch": "Paper", "tint": 33.333})); + run(&mut s, "select.set", json!({"ids": [paper.0]})); + let c = run(&mut s, "color.used", json!({}))["colors"][0].clone(); + assert_eq!(c["swatch"].as_str(), Some("Paper"), "{c}"); + // The tint is the paint's own, unrounded. + let vectorcraft_color::Paint::Solid { tint, .. } = s.doc().unwrap().doc.node(paper).unwrap().appearance.fill_paint() else { + panic!("a solid fill") + }; + assert_eq!((c["tint"].as_f64().unwrap() / 100.0) as f32, tint, "{c}"); + assert!((tint - 0.33333).abs() < 1e-5); + // A pattern's tile keeps its tint as well. + run(&mut s, "select.set", json!({"ids": [paper.0]})); + run(&mut s, "object.pattern.make", json!({"name": "Sheet", "width": 20, "height": 20})); + run(&mut s, "object.pattern.done", json!({})); + let filled = rect(&mut s, json!("#000000")); + run(&mut s, "paint.setFill", json!({"ids": [filled.0], "swatch": "Sheet"})); + run(&mut s, "select.set", json!({"ids": [filled.0]})); + let c = run(&mut s, "color.used", json!({}))["colors"][0].clone(); + assert_eq!(c["swatch"].as_str(), Some("Paper"), "{c}"); + assert_eq!((c["tint"].as_f64().unwrap() / 100.0) as f32, tint, "{c}"); +} + +#[test] +fn used_colors_read_the_tiles_of_patterns_used_inside_pattern_tiles() { + let mut s = session(); + let red = rect(&mut s, json!("#ff0000")); + run(&mut s, "select.set", json!({"ids": [red.0]})); + run(&mut s, "object.pattern.make", json!({"name": "Inner", "width": 20, "height": 20})); + run(&mut s, "object.pattern.done", json!({})); + let middle = rect(&mut s, json!("#000000")); + run(&mut s, "paint.setFill", json!({"ids": [middle.0], "swatch": "Inner"})); + run(&mut s, "select.set", json!({"ids": [middle.0]})); + run(&mut s, "object.pattern.make", json!({"name": "Outer", "width": 20, "height": 20})); + run(&mut s, "object.pattern.done", json!({})); + let square = rect(&mut s, json!("#000000")); + run(&mut s, "paint.setFill", json!({"ids": [square.0], "swatch": "Outer"})); + // The inner tile's square is stroked with the outer pattern, so the two patterns use each other. + let outer = s.doc().unwrap().doc.node(square).unwrap().appearance.fill_paint().clone(); + let st = s.doc_mut().unwrap(); + let doc = std::sync::Arc::make_mut(&mut st.doc); + let tile = doc.pattern_mut("Inner").unwrap().art.first_mut().unwrap(); + std::sync::Arc::make_mut(tile).appearance.set_stroke(outer); + run(&mut s, "select.set", json!({"ids": [square.0]})); + let r = run(&mut s, "color.used", json!({})); + let colors = r["colors"].as_array().unwrap(); + assert_eq!(colors.iter().map(|c| (c["hex"].as_str(), c["count"].as_u64())).collect::>(), [(Some("#ff0000"), Some(1))], "{r}"); +} + +#[test] +fn used_colors_give_no_swatch_for_a_stop_that_mixes_its_ink_with_process_inks() { + use vectorcraft_color::{Gradient, GradientKind, GradientPaint, GradientStop, Paint}; + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": {"c": 0, "m": 100, "y": 60, "k": 0}, "spot": true})); + let shape = rect(&mut s, json!("#000000")); + let mixed = Color::Cmyk { c: 0.3, m: 0.5, y: 0.3, k: 0.0 }; + let stop = |color, plates| GradientStop { swatch: Some("Ink".into()), tint: 0.5, plates, ..GradientStop::new(0.0, color) }; + let mut end = stop(Color::Cmyk { c: 0.0, m: 0.5, y: 0.3, k: 0.0 }, None); + end.offset = 1.0; + let g = Gradient::new(GradientKind::Linear, vec![stop(mixed, Some([0.3, 0.0, 0.0, 0.0])), end]); + let st = s.doc_mut().unwrap(); + std::sync::Arc::make_mut(&mut st.doc).node_mut(shape).unwrap().appearance.set_fill(Paint::Gradient(Box::new(GradientPaint::new(g)))); + let r = run(&mut s, "color.used", json!({})); + let entry = |key: &str| r["colors"].as_array().unwrap().iter().find(|c| c["key"] == key).cloned().unwrap(); + let mix = entry("cmyk 30 50 30 0"); + assert_eq!((mix.get("swatch"), mix.get("tint")), (None, None), "{r}"); + assert_eq!(entry("cmyk 0 50 30 0")["swatch"], "Ink", "{r}"); + // recolor.colors keeps the swatch it lists. + let listed = run(&mut s, "recolor.colors", json!({})); + assert!(listed["colors"].as_array().unwrap().iter().all(|c| c["swatch"] == "Ink"), "{listed}"); +} + +#[test] +fn used_colors_take_the_swatch_of_a_plain_use_painted_after_a_mixed_stop_of_the_same_color() { + use vectorcraft_color::{Gradient, GradientKind, GradientPaint, GradientStop, Paint}; + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": {"c": 0, "m": 100, "y": 60, "k": 0}, "spot": true})); + let shape = rect(&mut s, json!("#000000")); + let plain = rect(&mut s, json!("#000000")); + run(&mut s, "paint.setFill", json!({"ids": [plain.0], "swatch": "Ink", "tint": 50})); + let ink = fill(&s, plain); + // The stop below the plain fill has the same color, and process plates that add nothing. + let stop = GradientStop { swatch: Some("Ink".into()), tint: 0.5, plates: Some([0.0; 4]), ..GradientStop::new(0.0, ink) }; + let mut end = stop.clone(); + end.offset = 1.0; + let g = Gradient::new(GradientKind::Linear, vec![stop, end]); + let st = s.doc_mut().unwrap(); + std::sync::Arc::make_mut(&mut st.doc).node_mut(shape).unwrap().appearance.set_fill(Paint::Gradient(Box::new(GradientPaint::new(g)))); + run(&mut s, "select.set", json!({"ids": []})); + let r = run(&mut s, "color.used", json!({})); + let c = r["colors"].as_array().unwrap().iter().find(|c| c["count"] == 3).cloned().unwrap(); + assert_eq!((c["swatch"].as_str(), c["tint"].as_f64()), (Some("Ink"), Some(50.0)), "{r}"); +} + +#[test] +fn recolor_colors_keeps_the_swatch_of_the_first_linked_use_when_a_mixed_stop_comes_first() { + use vectorcraft_color::{Gradient, GradientKind, GradientPaint, GradientStop, Paint}; + let mut s = session(); + run(&mut s, "swatch.new", json!({"name": "Ink", "color": {"c": 0, "m": 100, "y": 60, "k": 0}, "spot": true})); + run(&mut s, "swatch.new", json!({"name": "Other", "color": {"c": 0, "m": 100, "y": 60, "k": 0}, "spot": true})); + let shape = rect(&mut s, json!("#000000")); + let plain = rect(&mut s, json!("#000000")); + run(&mut s, "paint.setFill", json!({"ids": [plain.0], "swatch": "Other", "tint": 50})); + let ink = fill(&s, plain); + // The stop below the plain fill has the same color, linked to another swatch, with process + // plates that add nothing. + let stop = GradientStop { swatch: Some("Ink".into()), tint: 0.5, plates: Some([0.0; 4]), ..GradientStop::new(0.0, ink) }; + let mut end = stop.clone(); + end.offset = 1.0; + let g = Gradient::new(GradientKind::Linear, vec![stop, end]); + let st = s.doc_mut().unwrap(); + std::sync::Arc::make_mut(&mut st.doc).node_mut(shape).unwrap().appearance.set_fill(Paint::Gradient(Box::new(GradientPaint::new(g)))); + run(&mut s, "select.set", json!({"ids": []})); + let three = |r: &Value| r["colors"].as_array().unwrap().iter().find(|c| c["count"] == 3).cloned().unwrap(); + let used = run(&mut s, "color.used", json!({})); + assert_eq!(three(&used)["swatch"], "Other", "{used}"); + let listed = run(&mut s, "recolor.colors", json!({})); + assert_eq!(three(&listed)["swatch"], "Ink", "recolor.colors names the first linked use: {listed}"); +} + #[test] fn colors_with_nothing_selected_leave_out_hidden_and_locked_objects_in_groups() { let mut s = session(); @@ -1422,6 +1590,26 @@ fn theme_picker_marquee_takes_the_area_and_picks_add_up() { assert_eq!(got, ["rgb 0 255 0", "rgb 255 255 0"]); } +/// A distorted image is read where its pixels are drawn, between its corners. +#[test] +fn theme_picker_reads_a_distorted_image_where_it_is_drawn() { + let mut s = session(); + let (id, b) = halves_image(&mut s, 64, 32, [255, 0, 0, 255], [0, 0, 255, 255]); + let (x, y0, y1) = (b.x1 + 20.0, b.y0, b.y1); + run(&mut s, "select.set", json!({"ids": [id.0]})); + run(&mut s, "object.distort", json!({"corners": [[x + 40.0, y0], [x + 60.0, y0], [x + 100.0, y1], [x, y1]]})); + // The lower left of the trapezoid, outside the rectangle the image was placed in: red. + assert_eq!(pick_theme(&mut s, json!({"picks": [{"rect": [x + 2.0, y1 - 4.0, x + 20.0, y1 - 1.0]}]})), ["rgb 255 0 0"]); + // Where the image was: nothing. + assert!(pick_theme(&mut s, json!({"picks": [{"rect": [b.x0 + 1.0, b.y0 + 1.0, b.x1 - 1.0, b.y1 - 1.0]}]})).is_empty()); + // A marquee reaching past the horizon its sides meet at (a quarter of its height above its + // top) still reads every pixel it covers. + let h = y1 - y0; + let mut both = pick_theme(&mut s, json!({"picks": [{"rect": [x - 10.0, y0 - h, x + 110.0, y1 + 1.0]}]})); + both.sort(); + assert_eq!(both, ["rgb 0 0 255", "rgb 255 0 0"]); +} + /// Pixels less than half opaque are left out, and so is an image whose pixels can't be read. #[test] fn theme_picker_leaves_out_clear_pixels_and_unreadable_images() { diff --git a/crates/engine/src/tests/symbolism_options.rs b/crates/engine/src/tests/symbolism_options.rs index b8cb29f213..4a75c170c7 100644 --- a/crates/engine/src/tests/symbolism_options.rs +++ b/crates/engine/src/tests/symbolism_options.rs @@ -180,6 +180,48 @@ fn average_at_the_mean_adds_no_undo_step() { assert!(state(&s) == before); } +/// An instance the brush reaches but leaves as it is (the Symbol Screener with Alt on an opaque +/// instance, or without Alt on one at the lowest opacity it gives) is not counted, and a stroke +/// that changes no instance adds no undo step. +#[test] +fn an_instance_left_as_it_is_is_not_counted() { + let mut s = session(); + let (opaque, faint) = (dot(&mut s, 100.0, 150.0), dot(&mut s, 300.0, 150.0)); + s.execute("transparency.set", &json!({"ids": [faint.0], "opacity": 5})).unwrap(); + let before = state(&s); + let r = adjust(&mut s, json!({"tool": "screen", "points": [[100, 150]], "radius": 30, "intensity": 10, "alt": true})); + assert_eq!(r["count"], 0, "Alt on an opaque instance"); + let r = adjust(&mut s, json!({"tool": "screen", "points": [[300, 150]], "radius": 30, "intensity": 10})); + assert_eq!(r["count"], 0, "an instance at 5%"); + assert!(state(&s) == before, "a stroke that changes nothing changed the document or its history"); + // A stroke over both counts only the instance it changes. + let r = adjust(&mut s, json!({"tool": "screen", "points": [[200, 150]], "radius": 150, "intensity": 10})); + assert_eq!(r["count"], 1); + assert!(node(&s, opaque).opacity < 1.0 && node(&s, faint).opacity == 0.05); +} + +/// Average gives an opacity below 5% when that is the mean: the Symbol Sprayer's new instance and +/// the Symbol Screener's instances take the mean of the instances under the brush. +#[test] +fn average_keeps_a_mean_opacity_below_five_percent() { + let mut s = session(); + let set = NodeId(s.execute("symbol.spray", &json!({"name": "Dot", "points": [[200, 150]], "radius": 4})).unwrap()["id"].as_u64().unwrap()); + let first = members(&s, set)[0]; + s.execute("transparency.set", &json!({"ids": [first.0], "opacity": 2})).unwrap(); + s.select(|_, sel| sel.set([set])).unwrap(); + s.execute("symbol.spray", &json!({"name": "Dot", "points": [[215, 150]], "radius": 30})).unwrap(); + let sprayed = *members(&s, set).last().unwrap(); + assert!((node(&s, sprayed).opacity - 0.02).abs() < 1e-6, "{}", node(&s, sprayed).opacity); + // Two instances at 0% and 4%: Average brings both toward 2%, and neither goes past it. + let mut s = session(); + let (a, b) = (dot(&mut s, 200.0, 150.0), dot(&mut s, 220.0, 150.0)); + s.execute("transparency.set", &json!({"ids": [a.0], "opacity": 0})).unwrap(); + s.execute("transparency.set", &json!({"ids": [b.0], "opacity": 4})).unwrap(); + adjust(&mut s, json!({"tool": "screen", "points": [[210, 150]], "radius": 40, "intensity": 10, "method": "average"})); + let (pa, pb) = (node(&s, a).opacity, node(&s, b).opacity); + assert!(pa > 0.0 && pa <= 0.02 + 1e-6 && (0.02 - 1e-6..0.04).contains(&pb), "{pa} {pb}"); +} + /// Average evens out the Symbol Stainer's amount and the Symbol Scruncher's spacing. #[test] fn average_evens_out_the_stain_and_the_spacing() { @@ -279,6 +321,38 @@ fn an_unknown_method_is_refused() { assert_eq!(center(&s, a), Point::new(200.0, 150.0)); } +/// `tool.setOption` refuses a Symbolism Tools Options value of the wrong kind or name, and the +/// tool's options stay as they were. +#[test] +fn tool_set_option_refuses_bad_symbolism_options() { + let mut s = session(); + let before = s.tool_options_of("symbolSizer"); + for (key, bad, want) in [ + ("method", json!("smooth"), "`method` must be one of userDefined, average, random"), + ("sprayStain", json!("random"), "`sprayStain` must be one of average, userDefined"), + ("usePressure", json!("yes"), "`usePressure` must be true or false"), + ("diameter", json!("big"), "`diameter` must be a number from 2 to 2000"), + ("style", json!(3), "`style` must be a string or null"), + ("diameter", json!(1), "`diameter` must be a number from 2 to 2000"), + ] { + let r = s.set_tool_option_cmd(&json!({"tool": "symbolSizer", "values": {key: bad}})); + assert_eq!(r, Err(want.to_string()), "{key}"); + assert_eq!(s.tool_options_of("symbolSizer"), before, "{key}"); + } + let r = s.set_tool_option_cmd(&json!({"tool": "symbolSizer", "values": {"method": "random", "sprayStain": "userDefined"}})).unwrap(); + assert_eq!((r["method"].as_str(), r["sprayStain"].as_str()), (Some("random"), Some("userDefined"))); + // Every option the options dialog sends is taken, together. + let all = json!({ + "diameter": 100.0, "intensity": 6.0, "density": 4.0, "usePressure": true, "method": "average", "showBrush": false, + "sprayScrunch": "userDefined", "spraySize": "userDefined", "spraySpin": "userDefined", "sprayScreen": "userDefined", + "sprayStain": "average", "sprayStyle": "userDefined", "proportional": false, "affectsDensity": true, + }); + let r = s.set_tool_option_cmd(&json!({"tool": "symbolSizer", "values": all})).unwrap(); + for (key, v) in all.as_object().unwrap() { + assert_eq!(&r[key], v, "{key}"); + } +} + /// With `usePressure` each point's pen pressure is the intensity there; without it the pressure is /// not used. A pressure that isn't a number is an error. #[test] @@ -316,6 +390,13 @@ fn pen_pressure_is_the_intensity_with_use_pressure() { json!({"tool": tool, "points": [[200, 150, "hard"]], "usePressure": true}), "a point's pressure must be a number, not \"hard\"", ); + // Also on a point without coordinates, beside one that has them. + refused( + &mut s, + "symbol.adjust", + json!({"tool": tool, "points": [[200, 150], [null, 0, "bad"]], "usePressure": true}), + "a point's pressure must be a number, not \"bad\"", + ); } for key in ["usePressure", "proportional", "affectsDensity"] { let mut p = json!({"tool": "size", "points": [[200, 150]]}); @@ -644,6 +725,45 @@ fn set_density_starts_from_the_density_a_set_was_sprayed_at() { assert!((center(&s, a).x - (150.0 - 50.0 * 0.25 / 0.65)).abs() < 1e-9, "{:?}", center(&s, a)); } +/// A set duplicated packs from the density recorded for its source, and a pasted set from the +/// density its source had at Copy: after Cut, after the source is given another density, and in +/// another document. +#[test] +fn a_copied_set_packs_from_the_density_of_its_source() { + for copy in ["duplicate", "paste", "cut", "changed after copy", "other document"] { + let mut s = session(); + let row: Vec = (0..4).map(|i| json!([60.0 + 60.0 * f64::from(i), 150.0])).collect(); + let set = + NodeId(s.execute("symbol.spray", &json!({"name": "Dot", "points": row, "radius": 4, "density": 2})).unwrap()["id"].as_u64().unwrap()); + s.select(|_, sel| sel.set([set])).unwrap(); + let first = match copy { + "duplicate" => "edit.duplicate", + "cut" => "edit.cut", + _ => "edit.copy", + }; + s.execute(first, &json!({})).unwrap(); + if copy == "changed after copy" { + s.execute("symbol.setDensity", &json!({"from": 5, "to": 9, "ids": [set.0]})).unwrap(); + } + if copy == "other document" { + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + } + if copy != "duplicate" { + s.execute("edit.paste", &json!({})).unwrap(); + } + let copied = s.doc().unwrap().selection.objects.clone(); + assert!(copied.len() == 1 && (copy == "other document" || copied[0] != set), "{copy}: {copied:?}"); + let ids = members(&s, copied[0]); + let xs = |s: &Session| ids.iter().map(|id| center(s, *id).x).collect::>(); + let was = xs(&s); + let middle = was.iter().sum::() / 4.0; + s.execute("symbol.setDensity", &json!({"from": 5, "to": 9, "ids": [copied[0].0]})).unwrap(); + for (before, after) in was.iter().zip(xs(&s)) { + assert!((after - (middle + (before - middle) * 0.25 / 0.95)).abs() < 1e-9, "{copy}: {before} -> {after}"); + } + } +} + /// A set of one instance takes the new density without moving, as one undo step, so a later change /// packs it from that density; setting the density it already has adds no undo step. #[test] @@ -719,6 +839,102 @@ fn set_density_refuses_bad_densities_and_objects_without_a_set() { assert!(state(&s) == before); } +/// The Symbol Styler applies the style gradually, by the brush's strength at the instance: the pen +/// pressure with Use Pressure Pen, else the intensity, less toward the brush's edge. Random gives +/// each instance a share of that amount. +#[test] +fn the_styler_applies_the_style_by_the_brushs_strength() { + let styled = |extra: Value, x: f64| { + let mut s = session(); + let a = dot(&mut s, 100.0, 150.0); + let id = s.execute("shape.rectangle", &json!({"x": 300, "y": 250, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap(); + s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap(); + s.execute("graphicStyle.new", &json!({"name": "Blue", "id": id})).unwrap(); + s.select(|_, sel| sel.clear()).unwrap(); + let mut p = json!({"tool": "style", "points": [[x, 150]], "radius": 10, "style": "Blue"}); + p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); + adjust(&mut s, p); + node(&s, a).appearance.fill().map_or(0.0, |f| f.opacity) + }; + let near = |a: f32, b: f32| (a - b).abs() < 1e-6; + assert!(near(styled(json!({"intensity": 10}), 100.0), 1.0), "full strength at the center"); + assert!(near(styled(json!({"intensity": 5}), 100.0), 0.5)); + assert!(near(styled(json!({"intensity": 10}), 105.0), 0.5), "half way to the edge"); + assert!(near(styled(json!({"usePressure": true, "points": [[100, 150, 0.25]]}), 100.0), 0.25)); + assert!(near(styled(json!({"usePressure": true, "points": [[100, 150, 1.0]]}), 100.0), 1.0)); + assert_eq!(styled(json!({"usePressure": true, "points": [[100, 150, 0.0]]}), 100.0), 0.0, "no pressure, no style"); + // Random: instances the same distance from the point take different amounts, each from none to + // the User Defined amount there (0.25: pressure 0.5, half way to the brush's edge). + let mut s = session(); + let ring: Vec = (0..6) + .map(|i| { + let a = f64::from(i) * std::f64::consts::TAU / 6.0; + dot(&mut s, 100.0 + 5.0 * a.cos(), 150.0 + 5.0 * a.sin()) + }) + .collect(); + let id = s.execute("shape.rectangle", &json!({"x": 300, "y": 250, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap(); + s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap(); + s.execute("graphicStyle.new", &json!({"name": "Blue", "id": id})).unwrap(); + s.select(|_, sel| sel.clear()).unwrap(); + adjust(&mut s, json!({"tool": "style", "points": [[100, 150, 0.5]], "radius": 10, "usePressure": true, "method": "random", "style": "Blue"})); + let amounts: Vec = ring.iter().map(|a| node(&s, *a).appearance.fill().map_or(0.0, |f| f.opacity)).collect(); + assert!(amounts.iter().all(|a| *a <= 0.25 + 1e-6), "{amounts:?}"); + assert!(amounts.iter().any(|a| *a > 0.0), "{amounts:?}"); + assert!(amounts.iter().any(|a| (a - amounts[0]).abs() > 1e-6), "{amounts:?}"); +} + +/// A sprayed instance's Average stain is the stain of the nearest instance whose stain shows: one +/// at no opacity is passed over and counts as no stain in the mean amount. +#[test] +fn average_spray_passes_over_a_stain_at_no_opacity() { + use vectorcraft_color::{Color, Paint}; + let mut s = session(); + let set = + NodeId(s.execute("symbol.spray", &json!({"name": "Dot", "points": [[100, 150], [130, 150]], "radius": 4})).unwrap()["id"].as_u64().unwrap()); + let ids = members(&s, set); + assert_eq!(ids.len(), 2); + s.edit("Stains", |d, _| { + for (id, color, amount) in [(ids[0], Color::rgb(1.0, 0.0, 0.0), 0.0), (ids[1], Color::rgb(0.0, 0.0, 1.0), 1.0)] { + let n = d.node_mut(id).unwrap(); + n.appearance.items.retain(|i| !matches!(i, vectorcraft_doc::AppearanceItem::Fill(_))); + let mut f = vectorcraft_doc::FillLayer::new(Paint::solid(color)); + f.opacity = amount; + n.appearance.items.insert(0, vectorcraft_doc::AppearanceItem::Fill(f)); + } + Ok(()) + }) + .unwrap(); + s.execute("symbol.spray", &json!({"name": "Dot", "points": [[100, 150]], "radius": 40})).unwrap(); + let new: Vec = members(&s, set).into_iter().filter(|id| !ids.contains(id)).collect(); + assert_eq!(new.len(), 1); + let f = node(&s, new[0]).appearance.fill().cloned().unwrap(); + assert_eq!(f.paint, Paint::solid(Color::rgb(0.0, 0.0, 1.0))); + assert!((f.opacity - 0.5).abs() < 1e-6, "{}", f.opacity); +} + +/// The Symbol Shifter moves an instance whose transform flattens it (it has no size), as it moves +/// any other, and counts it. +#[test] +fn the_shifter_moves_an_instance_without_a_size() { + let mut s = session(); + let a = dot(&mut s, 200.0, 150.0); + s.edit("Flatten", |d, _| { + if let Some(NodeKind::SymbolInstance { xf, .. }) = d.node_mut(a).map(|n| &mut n.kind) { + *xf = Affine::new([0.0, 0.0, 0.0, 0.0, 200.0, 150.0]); + } + Ok(()) + }) + .unwrap(); + let r = adjust(&mut s, json!({"tool": "shift", "points": [[200, 150], [210, 150]], "radius": 40, "intensity": 10})); + assert_eq!(r["count"], 1); + assert!(center(&s, a).x > 200.0, "{:?}", center(&s, a)); + // Average has no mean of such instances to move toward: it leaves them as they are. + let (before, x) = (state(&s), center(&s, a).x); + let r = adjust(&mut s, json!({"tool": "screen", "method": "average", "points": [[x, 150]], "radius": 40, "intensity": 10})); + assert_eq!(r["count"], 0); + assert!(state(&s) == before); +} + /// An instance with no size is shifted and screened as before; only Average, which needs its size, /// leaves it as it is. #[test] @@ -759,6 +975,29 @@ fn an_instance_without_a_size_is_changed_by_every_method_but_average() { assert!(state(&s) == before); } +/// Average Stainer: an instance whose stain is at no opacity has no stain of its own, so it takes +/// the stain the mean picks, not its hidden paint. +#[test] +fn average_stain_replaces_a_stain_at_no_opacity() { + use vectorcraft_color::{Color, Paint}; + let mut s = session(); + let (a, b) = (dot(&mut s, 100.0, 150.0), dot(&mut s, 120.0, 150.0)); + s.edit("Stains", |d, _| { + for (id, color, amount) in [(a, Color::rgb(1.0, 0.0, 0.0), 0.0), (b, Color::rgb(0.0, 0.0, 1.0), 1.0)] { + let n = d.node_mut(id).unwrap(); + let mut f = vectorcraft_doc::FillLayer::new(Paint::solid(color)); + f.opacity = amount; + n.appearance.items.insert(0, vectorcraft_doc::AppearanceItem::Fill(f)); + } + Ok(()) + }) + .unwrap(); + adjust(&mut s, json!({"tool": "stain", "method": "average", "points": [[100, 150]], "radius": 40, "intensity": 10})); + let f = node(&s, a).appearance.fill().cloned().unwrap(); + assert_eq!(f.paint, Paint::solid(Color::rgb(0.0, 0.0, 1.0))); + assert!(f.opacity > 0.0, "{}", f.opacity); +} + /// A stroke that leaves every instance under the brush as it is (each already at full stain, or /// at the least opacity) counts none and adds no undo step. #[test] diff --git a/crates/engine/src/tests/symbolism_shift.rs b/crates/engine/src/tests/symbolism_shift.rs new file mode 100644 index 0000000000..ca08dc2069 --- /dev/null +++ b/crates/engine/src/tests/symbolism_shift.rs @@ -0,0 +1,272 @@ +//! The symbolism tools' Shift forms in `symbol.adjust {shift}`: the Symbol Shifter's stacking +//! order, the Symbol Sizer keeping the set's density, and the Symbol Stainer and Symbol Styler +//! keeping their amount while the color or style changes. + +use serde_json::{Value, json}; +use vectorcraft_doc::{Document, Node, NodeKind}; +use vectorcraft_geom::Point; + +use crate::*; + +/// A document with the 20 pt square symbol "Dot" and nothing selected. +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 20, "height": 20})).unwrap(); + s.execute("symbol.new", &json!({"name": "Dot"})).unwrap(); + s.select(|_, sel| sel.clear()).unwrap(); + s +} + +/// An instance of Dot centered on (`x`, `y`), not selected. +fn dot(s: &mut Session, x: f64, y: f64) -> NodeId { + let id = NodeId(s.execute("symbol.place", &json!({"name": "Dot", "x": x, "y": y})).unwrap()["id"].as_u64().unwrap()); + s.select(|_, sel| sel.clear()).unwrap(); + id +} + +fn node(s: &Session, id: NodeId) -> Node { + s.doc().unwrap().doc.node(id).cloned().unwrap() +} + +fn center(s: &Session, id: NodeId) -> Point { + match node(s, id).kind { + NodeKind::SymbolInstance { xf, .. } => xf * Point::ZERO, + other => panic!("not an instance: {other:?}"), + } +} + +fn width(s: &Session, id: NodeId) -> f64 { + node(s, id).geometric_bounds().unwrap().width() +} + +fn undo_len(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +fn state(s: &Session) -> (Document, usize) { + ((*s.doc().unwrap().doc).clone(), undo_len(s)) +} + +fn adjust(s: &mut Session, p: Value) -> Value { + s.execute("symbol.adjust", &p).unwrap() +} + +/// The children of symbol set `set`, in stacking order (the first is at the back). +fn members(s: &Session, set: NodeId) -> Vec { + node(s, set).children().unwrap().iter().map(|c| c.id).collect() +} + +/// The instance's fill: its color as RGB and its amount. +fn fill(s: &Session, id: NodeId) -> Option<([f32; 3], f32)> { + node(s, id).appearance.fill().map(|f| (f.paint.color().map_or([0.0; 3], |c| c.to_rgb()), f.opacity)) +} + +/// A symbol set of four instances in a row at x = 40, 120, 200 and 280, selected. +fn row(s: &mut Session) -> (NodeId, Vec) { + let pts: Vec = (0..4).map(|i| json!([40.0 + 80.0 * f64::from(i), 150.0])).collect(); + let set = NodeId(s.execute("symbol.spray", &json!({"name": "Dot", "points": pts, "radius": 4})).unwrap()["id"].as_u64().unwrap()); + let ids = members(s, set); + assert_eq!(ids.len(), 4); + (set, ids) +} + +/// Shift-click with the Symbol Shifter brings the instances under the brush one place forward in +/// the set, and Alt+Shift-click sends them one place backward, without moving them on the canvas. +#[test] +fn shift_click_with_the_shifter_changes_the_stacking_order() { + let mut s = session(); + let (set, ids) = row(&mut s); + let centers: Vec = ids.iter().map(|id| center(&s, *id)).collect(); + let click = |s: &mut Session, x: f64, alt: bool| { + adjust(s, json!({"tool": "shift", "points": [[x, 150]], "radius": 10, "intensity": 10, "shift": true, "alt": alt}))["count"].clone() + }; + let steps = undo_len(&s); + assert_eq!(click(&mut s, 120.0, false), 1); + assert_eq!(members(&s, set), [ids[0], ids[2], ids[1], ids[3]]); + assert_eq!(undo_len(&s), steps + 1, "one undo step"); + assert_eq!(ids.iter().map(|id| center(&s, *id)).collect::>(), centers, "nothing moves on the canvas"); + assert_eq!(click(&mut s, 120.0, false), 1); + assert_eq!(members(&s, set), [ids[0], ids[2], ids[3], ids[1]]); + // Already in front of the others: nothing changes and no undo step is added. + let before = state(&s); + assert_eq!(click(&mut s, 120.0, false), 0); + assert!(state(&s) == before); + // Alt sends it back one place at a time; at the back it stays. + assert_eq!(click(&mut s, 120.0, true), 1); + assert_eq!(members(&s, set), [ids[0], ids[2], ids[1], ids[3]]); + click(&mut s, 120.0, true); + click(&mut s, 120.0, true); + assert_eq!(members(&s, set), [ids[1], ids[0], ids[2], ids[3]]); + assert_eq!(click(&mut s, 120.0, true), 0); + // Two instances under the brush move together past the next one. + s.execute("edit.undo", &json!({})).unwrap(); + let both = adjust(&mut s, json!({"tool": "shift", "points": [[40, 150], [120, 150]], "radius": 10, "intensity": 10, "shift": true})); + assert_eq!(both["count"], 2); + assert_eq!(members(&s, set), [ids[2], ids[0], ids[1], ids[3]]); + // Without Shift a drag moves the instances, as before. + adjust(&mut s, json!({"tool": "shift", "points": [[280, 150], [290, 150]], "radius": 30, "intensity": 10})); + assert!(center(&s, ids[3]).x > centers[3].x); +} + +/// Shift with the Symbol Sizer resizes the instances and keeps their centers where they are, even +/// with Resizing Affects Density. +#[test] +fn shift_with_the_sizer_keeps_the_density() { + let at = |affects: bool, shift: bool| { + let mut s = session(); + let a = dot(&mut s, 220.0, 150.0); + adjust( + &mut s, + json!({"tool": "size", "points": [[200, 150], [200, 150]], "radius": 60, "intensity": 10, "affectsDensity": affects, "shift": shift}), + ); + (center(&s, a), width(&s, a)) + }; + let (moved, _) = at(true, false); + assert!(moved.x > 220.5, "{moved:?}"); + let (kept, grown) = at(true, true); + assert!((kept.x - 220.0).abs() < 1e-9 && (kept.y - 150.0).abs() < 1e-9 && grown > 20.5, "{kept:?} {grown}"); + // It resizes as the Sizer does with Resizing Affects Density off. + assert_eq!(at(false, false), (kept, grown)); + assert_eq!(at(false, true), (kept, grown)); +} + +/// Shift with the Symbol Stainer keeps the stain's amount and moves its color toward the fill +/// color; an instance without a stain is left as it is. +#[test] +fn shift_with_the_stainer_keeps_the_amount_and_changes_the_color() { + let mut s = session(); + let (a, b) = (dot(&mut s, 100.0, 150.0), dot(&mut s, 300.0, 150.0)); + adjust(&mut s, json!({"tool": "stain", "points": [[100, 150], [100, 150]], "radius": 5, "intensity": 10, "color": "#ff0000"})); + let (red, amount) = fill(&s, a).unwrap(); + assert!(amount > 0.2 && red[0] > 0.99 && red[2] < 0.01, "{red:?} {amount}"); + // A second fill below the stain, which Shift leaves as it is. + s.edit("Add fill", |d, _| { + let n = d.node_mut(a).unwrap(); + let lower = n.appearance.fill().unwrap().clone(); + n.appearance.items.insert(0, vectorcraft_doc::AppearanceItem::Fill(vectorcraft_doc::FillLayer { opacity: 0.5, ..lower })); + Ok(()) + }) + .unwrap(); + let lower = node(&s, a).appearance.items[0].clone(); + let stain = |s: &mut Session, x: f64| { + adjust(s, json!({"tool": "stain", "points": [[x, 150], [x, 150]], "radius": 5, "intensity": 10, "color": "#0000ff", "shift": true})) + }; + assert_eq!(stain(&mut s, 100.0)["count"], 1); + let (color, kept) = fill(&s, a).unwrap(); + assert_eq!(kept, amount, "the amount stays"); + assert!(color[0] < red[0] && color[2] > 0.01, "toward blue: {color:?}"); + assert_eq!((node(&s, a).appearance.items.len(), &node(&s, a).appearance.items[0]), (2, &lower), "the other fill stays"); + // More strokes go on toward blue, with the amount still the same. + for _ in 0..30 { + stain(&mut s, 100.0); + } + let (bluer, kept) = fill(&s, a).unwrap(); + assert_eq!(kept, amount); + assert!(bluer[2] > 0.9 && bluer[0] < 0.1, "{bluer:?}"); + // Alt has no effect with Shift. + let green = json!({"tool": "stain", "points": [[100, 150]], "radius": 5, "intensity": 10, "color": "#00ff00", "shift": true}); + adjust(&mut s, green.clone()); + let plain = fill(&s, a); + s.execute("edit.undo", &json!({})).unwrap(); + let mut with_alt = green; + with_alt["alt"] = json!(true); + adjust(&mut s, with_alt); + assert_eq!(fill(&s, a), plain); + // No stain on b: nothing changes and no undo step is added. + let before = state(&s); + assert_eq!(stain(&mut s, 300.0)["count"], 0); + assert!(state(&s) == before && fill(&s, b).is_none()); +} + +/// Shift with the Symbol Styler keeps the amount of the instance's stain or style and moves its +/// fill toward the selected style's fill. +#[test] +fn shift_with_the_styler_keeps_the_amount_and_changes_the_style() { + let mut s = session(); + let a = dot(&mut s, 100.0, 150.0); + let id = s.execute("shape.rectangle", &json!({"x": 300, "y": 250, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap(); + s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap(); + s.execute("graphicStyle.new", &json!({"name": "Blue", "id": id})).unwrap(); + s.select(|_, sel| sel.clear()).unwrap(); + // A red stain at part strength. + adjust(&mut s, json!({"tool": "stain", "points": [[100, 150]], "radius": 5, "intensity": 10, "color": "#ff0000"})); + let (red, amount) = fill(&s, a).unwrap(); + assert!(red[0] > 0.99 && amount > 0.0 && amount < 0.5, "{red:?} {amount}"); + // Half the brush's strength at a point 2.5 pt from the instance: half way to blue. + adjust(&mut s, json!({"tool": "style", "points": [[102.5, 150]], "radius": 5, "intensity": 10, "style": "Blue", "shift": true})); + let (mixed, kept) = fill(&s, a).unwrap(); + assert_eq!(kept, amount); + assert!(mixed[0] < 0.99 && mixed[2] > 0.01, "{mixed:?}"); + // At the brush's center with full intensity it takes the style's fill. + adjust(&mut s, json!({"tool": "style", "points": [[100, 150]], "radius": 5, "intensity": 10, "style": "Blue", "shift": true})); + let (blue, kept) = fill(&s, a).unwrap(); + assert_eq!(kept, amount); + assert!(blue[2] > 0.99 && blue[0] < 0.01, "{blue:?}"); +} + +/// A stain or style with no form between it and the new paint (a pattern and a solid color) takes +/// the new paint at once, at any strength, and keeps its amount. +#[test] +fn shift_changes_a_paint_that_has_no_form_in_between() { + use vectorcraft_color::Paint; + let mut s = session(); + let a = dot(&mut s, 100.0, 150.0); + s.edit("Pattern fill", |d, _| { + let mut f = vectorcraft_doc::FillLayer::new(Paint::Pattern { pattern: "Tile".into(), xf: Default::default() }); + f.opacity = 0.4; + d.node_mut(a).unwrap().appearance.items.insert(0, vectorcraft_doc::AppearanceItem::Fill(f)); + Ok(()) + }) + .unwrap(); + // Low intensity, near the brush's edge: far below half strength. + let r = adjust(&mut s, json!({"tool": "stain", "points": [[104, 150]], "radius": 5, "intensity": 1, "color": "#ff0000", "shift": true})); + assert_eq!(r["count"], 1); + let f = node(&s, a).appearance.fill().cloned().unwrap(); + assert_eq!(f.opacity, 0.4, "the amount stays"); + assert!(f.paint.color().is_some_and(|c| c.to_rgb()[0] > 0.99), "{:?}", f.paint); +} + +/// A style name the document has no style for (the Styler's style from another document, or one +/// since renamed or deleted) moves the fill toward the document's first style after the default +/// one, as no name does, and the stain's amount stays. +#[test] +fn the_styler_takes_the_first_style_for_a_name_the_document_lacks() { + use vectorcraft_color::{Color, Paint}; + let styled = |style: Option<&str>| { + let mut s = session(); + let a = dot(&mut s, 100.0, 150.0); + s.execute("paint.setFill", &json!({"color": "#00ff00"})).unwrap(); + s.select(|_, sel| sel.clear()).unwrap(); + adjust(&mut s, json!({"tool": "stain", "points": [[100, 150]], "radius": 5, "intensity": 10, "color": "#ff0000"})); + let mut p = json!({"tool": "style", "points": [[100, 150]], "radius": 5, "intensity": 10, "shift": true}); + if let Some(n) = style { + p["style"] = json!(n); + } + let stained = node(&s, a).appearance.fill().map(|f| f.opacity); + adjust(&mut s, p); + let f = node(&s, a).appearance.fill().cloned().unwrap(); + assert_eq!(Some(f.opacity), stained, "the amount stays"); + let first = s.doc().unwrap().doc.graphic_styles[1].appearance.fill_paint(); + (f.paint, first) + }; + let (missing, first) = styled(Some("No Such Style")); + let (none, _) = styled(None); + assert_eq!(missing, none); + // The paint is the first style's, not the active fill color. + assert_eq!(none, first); + assert_ne!(none, Paint::solid(Color::rgb(0.0, 1.0, 0.0))); +} + +/// A `shift` that is not true, false or null is refused and changes nothing. +#[test] +fn a_bad_shift_is_refused() { + let mut s = session(); + dot(&mut s, 100.0, 150.0); + for tool in ["shift", "size", "stain", "style"] { + let before = state(&s); + let r = s.execute("symbol.adjust", &json!({"tool": tool, "points": [[100, 150]], "shift": "yes"})); + assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if msg == "`shift` must be true or false"), "{tool}: {r:?}"); + assert!(state(&s) == before); + } +} diff --git a/crates/engine/src/tests/toolsettings.rs b/crates/engine/src/tests/toolsettings.rs index fbde9edca7..69d382f2dc 100644 --- a/crates/engine/src/tests/toolsettings.rs +++ b/crates/engine/src/tests/toolsettings.rs @@ -138,6 +138,86 @@ fn a_dropped_press_does_not_keep_what_its_drag_changed() { assert_eq!(s.prefs.tool_settings["polygon"]["sides"], json!(7), "and stores its sides"); } +/// An option set with `tool.setOption` while a press is held survives the dropped press, in the +/// tool and in the stored options, while what the drag itself changed is put back in both. +#[test] +fn an_option_set_during_a_dropped_press_is_kept() { + let mut s = session(); + select(&mut s, "rectangularGrid"); + let v = ViewInfo { smart_guides: false, ..Default::default() }; + s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 100.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 180.0), v).unwrap(); + s.tool_key(ToolKey::Up, Mods::default(), v).unwrap(); + s.tool_key(ToolKey::Right, Mods::default(), v).unwrap(); + assert_eq!((s.tool_options()["rows"].clone(), s.tool_options()["columns"].clone()), (json!(6), json!(6))); + s.set_tool_option_cmd(&json!({"key": "columns", "value": 9})).unwrap(); + s.drop_tool_press(v).unwrap(); + let o = s.tool_options(); + assert_eq!((o["rows"].clone(), o["columns"].clone()), (json!(5), json!(9)), "the drag's rows go back; the set columns stay"); + let saved = &s.prefs.tool_settings["rectangularGrid"]; + assert_eq!((saved["rows"].clone(), saved["columns"].clone()), (json!(5), json!(9)), "the drag's rows are not stored; the set columns are"); + select(&mut s, "selection"); + select(&mut s, "rectangularGrid"); + let o = s.tool_options(); + assert_eq!((o["rows"].clone(), o["columns"].clone()), (json!(5), json!(9)), "a tool switch keeps the set columns"); + // The same through the desktop app's setter. + s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 100.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 180.0), v).unwrap(); + s.tool_key(ToolKey::Up, Mods::default(), v).unwrap(); + s.set_tool_option("columns", &json!(3)); + s.drop_tool_press(v).unwrap(); + let o = s.tool_options(); + assert_eq!((o["rows"].clone(), o["columns"].clone()), (json!(5), json!(3))); + let saved = &s.prefs.tool_settings["rectangularGrid"]; + assert_eq!((saved["rows"].clone(), saved["columns"].clone()), (json!(5), json!(3))); +} + +/// A Corner Radius preference set while a Rounded Rectangle press is held survives the dropped +/// press, in the tool and in the preference. +#[test] +fn a_corner_radius_set_during_a_dropped_press_is_kept() { + let mut s = session(); + select(&mut s, "roundedRectangle"); + let v = ViewInfo { smart_guides: false, ..Default::default() }; + s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 100.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 180.0), v).unwrap(); + let mut p = s.prefs.clone(); + p.corner_radius = 30.0; + s.apply_prefs(p); + s.drop_tool_press(v).unwrap(); + assert_eq!(s.tool_options()["cornerRadius"].as_f64(), Some(30.0), "the tool keeps the new radius"); + assert_eq!(s.prefs.corner_radius, 30.0, "the preference keeps it"); +} + +/// An option set with `tool.setOption` on a tool that lent a selection tool for a Cmd-drag +/// survives the dropped press, in the tool and in the stored options. So does a Corner Radius +/// preference set while the Rounded Rectangle lends one. +#[test] +fn an_option_set_on_a_lending_tool_during_a_dropped_press_is_kept() { + let mut s = session(); + select(&mut s, "rectangularGrid"); + let v = ViewInfo { smart_guides: false, ..Default::default() }; + let cmd = Mods { cmd: true, ..Default::default() }; + s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 100.0).with_mods(cmd), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 180.0).with_mods(cmd), v).unwrap(); + assert_eq!(s.lender.as_ref().map(|t| t.id()), Some("rectangularGrid"), "the press lent a selection tool"); + s.set_tool_option_cmd(&json!({"tool": "rectangularGrid", "key": "columns", "value": 9})).unwrap(); + s.drop_tool_press(v).unwrap(); + assert_eq!(s.tool_id(), "rectangularGrid", "the lending tool is back"); + assert_eq!(s.tool_options()["columns"], json!(9), "the tool keeps the set columns"); + assert_eq!(s.prefs.tool_settings["rectangularGrid"]["columns"], json!(9), "and stores them"); + select(&mut s, "roundedRectangle"); + s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 100.0).with_mods(cmd), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 200.0, 180.0).with_mods(cmd), v).unwrap(); + assert_eq!(s.lender.as_ref().map(|t| t.id()), Some("roundedRectangle"), "the press lent a selection tool"); + let mut p = s.prefs.clone(); + p.corner_radius = 30.0; + s.apply_prefs(p); + s.drop_tool_press(v).unwrap(); + assert_eq!(s.tool_options()["cornerRadius"].as_f64(), Some(30.0), "the tool keeps the new radius"); + assert_eq!(s.prefs.corner_radius, 30.0, "the preference keeps it"); +} + /// A dropped Pen press drops only the anchor it was placing: the path being drawn goes on with /// the next click. #[test] diff --git a/crates/engine/src/tests/xform.rs b/crates/engine/src/tests/xform.rs index 3aea7f3041..89c3b28b13 100644 --- a/crates/engine/src/tests/xform.rs +++ b/crates/engine/src/tests/xform.rs @@ -754,6 +754,406 @@ fn distort_perspective_midpoint_is_projective() { assert!((c.y - 100.0 / 6.0).abs() < 1e-3, "{c:?}"); } +/// A 2 × 2 px image placed at (0, 0)–(100, 100), selected. +fn placed_image(s: &mut Session) -> NodeId { + s.edit("Place", |d, sel| { + d.images.insert("pic".into(), vectorcraft_doc::ImageBlob::png(vec![])); + let id = d.alloc_id(); + let im = vectorcraft_doc::ImageObject { + key: "pic".into(), + width: 2, + height: 2, + xf: vectorcraft_geom::Affine::scale(50.0), + link: None, + placement: Default::default(), + pixels: None, + }; + d.insert(d.default_layer(), 0, Node::new(id, vectorcraft_doc::NodeKind::Image(Box::new(im))))?; + sel.set([id]); + Ok(id) + }) + .unwrap() +} + +fn corners(s: &Session, id: NodeId) -> [Point; 4] { + s.doc().unwrap().doc.node(id).unwrap().image_corners().unwrap() +} + +fn assert_corners(got: [Point; 4], want: [(f64, f64); 4]) { + for (g, (x, y)) in got.iter().zip(want) { + assert!(g.distance(Point::new(x, y)) < 1e-9, "{got:?} against {want:?}"); + } +} + +/// Perspective Distort and Free Distort put an image's corners exactly on the handles, in one +/// undo step; the image is bounded and clicked by its corners, and a move takes them along. +#[test] +fn distort_puts_an_images_corners_on_the_handles() { + for want in [[(40.0, 0.0), (60.0, 0.0), (100.0, 100.0), (0.0, 100.0)], [(10.0, 5.0), (90.0, 0.0), (120.0, 110.0), (0.0, 100.0)]] { + let mut s = session(); + let img = placed_image(&mut s); + let undo = undo_len(&s); + let corners_json: Vec<[f64; 2]> = want.iter().map(|(x, y)| [*x, *y]).collect(); + s.execute("object.distort", &json!({ "corners": corners_json })).unwrap(); + assert_eq!(undo_len(&s), undo + 1); + assert_corners(corners(&s, img), want); + assert!(s.doc().unwrap().doc.node(img).unwrap().is_distorted_image()); + let b = bounds(&s, img); + let xs = want.map(|c| c.0); + let ys = want.map(|c| c.1); + let near = |a: f64, b: f64| (a - b).abs() < 1e-9; + assert!(near(b.x0, xs.iter().copied().fold(f64::MAX, f64::min)) && near(b.x1, xs.iter().copied().fold(f64::MIN, f64::max)), "{b:?}"); + assert!(near(b.y0, ys.iter().copied().fold(f64::MAX, f64::min)) && near(b.y1, ys.iter().copied().fold(f64::MIN, f64::max)), "{b:?}"); + s.execute("object.move", &json!({"dx": 10, "dy": 20})).unwrap(); + assert_corners(corners(&s, img), want.map(|(x, y)| (x + 10.0, y + 20.0))); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + assert_corners(corners(&s, img), [(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)]); + assert!(!s.doc().unwrap().doc.node(img).unwrap().is_distorted_image()); + } + // Clicks: inside the trapezoid hits the image; inside its old square but outside the + // trapezoid does not. + let mut s = session(); + let img = placed_image(&mut s); + s.execute("object.distort", &json!({ "corners": [[40, 0], [60, 0], [100, 100], [0, 100]] })).unwrap(); + let doc = &s.doc().unwrap().doc; + let opt = vectorcraft_doc::hit::HitOptions::default(); + assert_eq!(vectorcraft_doc::hit::hit_test(doc, Point::new(50.0, 50.0), opt).map(|h| h.leaf), Some(img)); + assert_eq!(vectorcraft_doc::hit::hit_test(doc, Point::new(5.0, 10.0), opt).map(|h| h.leaf), None); +} + +/// Distorted together with a path, the image's corners and the path's anchors follow one warp. +#[test] +fn distort_moves_an_image_and_a_path_as_one() { + let mut s = session(); + let img = placed_image(&mut s); + let path = rect(&mut s, 100.0, 0.0, 100.0, 100.0); + s.execute("select.set", &json!({"ids": [img.0, path.0]})).unwrap(); + s.execute("object.distort", &json!({"corners": [[0, 0], [200, 0], [200, 100], [50, 100]]})).unwrap(); + let d = &s.doc().unwrap().doc; + let anchors: Vec = d.node(path).unwrap().path_data().unwrap().anchors().map(|(_, _, a)| a.p).collect(); + let q = corners(&s, img); + // The image's right edge and the path's left edge were one line, and stay one where the warp + // moves it. + assert!(q[2].distance(Point::new(100.0, 100.0)) > 1.0, "{q:?}"); + for p in [q[1], q[2]] { + assert!(anchors.iter().any(|a| a.distance(p) < 1e-9), "{p:?} not in {anchors:?}"); + } +} + +/// Corners that would fold an image over are refused: nothing changes and no undo step is kept. +/// A distorted image keeps its distortion where commands that cannot keep it are asked to work. +#[test] +fn distort_refuses_a_folded_image_and_crop_and_trace_refuse_a_distorted_one() { + let mut s = session(); + let img = placed_image(&mut s); + let (before, undo) = (s.doc().unwrap().doc.clone(), undo_len(&s)); + let e = s.execute("object.distort", &json!({"corners": [[0, 0], [100, 0], [0, 100], [100, 100]]})).unwrap_err().to_string(); + assert!(e.contains("convex"), "{e}"); + assert_eq!(undo_len(&s), undo); + assert_eq!(s.doc().unwrap().doc, before); + // Three corners on one line give no perspective map at all. + let e = s.execute("object.distort", &json!({"corners": [[0, 0], [200, 0], [100, 50], [0, 100]]})).unwrap_err().to_string(); + assert!(e.contains("convex"), "{e}"); + assert_eq!(s.doc().unwrap().doc, before); + // A convex shape too small for a perspective map: the corners could not reach the handles. + let e = s.execute("object.distort", &json!({"corners": [[0, 0], [1e-7, 0], [8e-8, 1e-7], [0, 1e-7]]})).unwrap_err().to_string(); + assert!(e.contains("too close together"), "{e}"); + // The same shape far from the origin: its distance from it does not hide the missed corner. + let x = 1_000_000.0; + let e = s.execute("object.distort", &json!({"corners": [[x, 0], [x + 1e-7, 0], [x + 8e-8, 1e-7], [x, 1e-7]]})).unwrap_err().to_string(); + assert!(e.contains("too close together"), "{e}"); + // A long, thin shape with one side all but gone. + let e = s.execute("object.distort", &json!({"corners": [[0, 0], [1_000_000, 0], [1_000_000, 1e-19], [0, 1]]})).unwrap_err().to_string(); + assert!(e.contains("too close together"), "{e}"); + assert_eq!(s.doc().unwrap().doc, before); + assert_eq!(undo_len(&s), undo); + // A small shape near the edge of the canvas is still distorted. + let o = vectorcraft_doc::MAX_COORD - 2.0; + let far = [[o, o], [o + 1.0, o], [o + 0.2130712, o + 1.0], [o, o + 1.0]]; + s.execute("object.distort", &json!({ "from": [0, 0, 100, 100], "corners": far })).unwrap(); + assert!(s.doc().unwrap().doc.node(img).unwrap().is_distorted_image()); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(undo_len(&s), undo); + s.execute("object.distort", &json!({ "corners": [[40, 0], [60, 0], [100, 100], [0, 100]] })).unwrap(); + for (cmd, params) in [ + ("object.cropImage", json!({})), + ("imageTrace.make", json!({})), + ("links.relink", json!({"path": "/nowhere/pic.png"})), + // Refused before the folder is searched, so a file missing there does not hide it. + ("links.relink", json!({"folder": "/nowhere"})), + ("links.embed", json!({"ids": [img.0]})), + ("links.unembed", json!({})), + // Refused before any file is written. + ("links.unembed", json!({"folder": "/nowhere"})), + ("object.createObjectMosaic", json!({})), + ("object.mesh.create", json!({})), + ( + "file.place", + json!({"replace": true, "name": "b.png", "dataBase64": vectorcraft_format::base64_encode(&crate::tests_links::png(2, 2, [0, 0, 255]))}), + ), + ] { + let e = s.execute(cmd, ¶ms).unwrap_err().to_string(); + // Every command gives the one shared refusal, which the complete-message catalogs translate. + assert!(e.contains("is an image changed by Perspective Distort or Free Distort, which this command does not work on"), "{cmd}: {e}"); + } + assert!(s.doc().unwrap().doc.node(img).unwrap().is_distorted_image()); + assert_eq!(undo_len(&s), undo + 1); + // Type replaces a distorted image by its bounds, which the corners give: not refused. + let text = json!({"replace": true, "name": "note.txt", "dataBase64": vectorcraft_format::base64_encode(b"Hello")}); + let out = s.execute("file.place", &text).unwrap(); + let id = NodeId(out["ids"][0].as_u64().unwrap()); + assert!(matches!(s.doc().unwrap().doc.node(id).unwrap().kind, vectorcraft_doc::NodeKind::Text(_))); +} + +/// Create Gradient Mesh on a path and a distorted image converts the path and names the image it +/// left as it is, with the shared refusal. +#[test] +fn mesh_create_reports_the_distorted_image_it_skips() { + let mut s = session(); + let img = placed_image(&mut s); + s.execute("object.distort", &json!({ "corners": [[40, 0], [60, 0], [100, 100], [0, 100]] })).unwrap(); + let path = rect(&mut s, 200.0, 0.0, 100.0, 100.0); + s.execute("select.set", &json!({"ids": [img.0, path.0]})).unwrap(); + let out = s.execute("object.mesh.create", &json!({"rows": 1, "cols": 1})).unwrap(); + assert_eq!(out["ids"].as_array().map(Vec::len), Some(1), "{out}"); + let skipped = out["skipped"].as_array().expect("the skipped image"); + assert_eq!(skipped.len(), 1, "{out}"); + assert_eq!(skipped[0]["id"], json!(img.0)); + assert!(skipped[0]["reason"].as_str().unwrap().contains("Perspective Distort or Free Distort"), "{out}"); + assert!(s.doc().unwrap().doc.node(img).unwrap().is_distorted_image()); + // Without a distorted image, no `skipped`. + let other = rect(&mut s, 400.0, 0.0, 100.0, 100.0); + let out = s.execute("object.mesh.create", &json!({"ids": [other.0], "rows": 1, "cols": 1})).unwrap(); + assert!(out.get("skipped").is_none(), "{out}"); +} + +/// A blend takes the warp's affine approximation whole, so an image inside it does not stop a +/// distort whose corners an image could not follow. +#[test] +fn distort_of_a_blend_holding_an_image_is_not_refused() { + let mut s = session(); + let img = placed_image(&mut s); + let r = rect(&mut s, 200.0, 0.0, 100.0, 100.0); + let out = s.execute("object.blend.make", &json!({"ids": [img.0, r.0]})).unwrap(); + let blend = NodeId(out["id"].as_u64().unwrap()); + let undo = undo_len(&s); + s.execute("object.distort", &json!({"ids": [blend.0], "corners": [[0, 0], [300, 0], [100, 50], [0, 100]]})).unwrap(); + assert_eq!(undo_len(&s), undo + 1); + assert!(!s.doc().unwrap().doc.node(img).unwrap().is_distorted_image()); +} + +/// The Control bar's Mask clips a distorted image to the shape between its corners. +#[test] +fn mask_on_a_distorted_image_follows_its_corners() { + let mut s = session(); + let img = placed_image(&mut s); + let want = [(40.0, 0.0), (60.0, 0.0), (100.0, 100.0), (0.0, 100.0)]; + s.execute("object.distort", &json!({ "corners": [[40, 0], [60, 0], [100, 100], [0, 100]] })).unwrap(); + let out = s.execute("object.maskImage", &json!({})).unwrap(); + let path = NodeId(out["path"].as_u64().unwrap()); + let d = &s.doc().unwrap().doc; + let anchors: Vec = d.node(path).unwrap().path_data().unwrap().anchors().map(|(_, _, a)| a.p).collect(); + assert_eq!(anchors.len(), 4, "{anchors:?}"); + for (x, y) in want { + assert!(anchors.iter().any(|a| a.distance(Point::new(x, y)) < 1e-9), "{x},{y} not in {anchors:?}"); + } + assert!(d.node(img).unwrap().is_distorted_image()); +} + +/// A Transform effect moves a distorted image's corners with it: expanded, the image stands +/// where the effect drew it. +#[test] +fn a_transform_effect_moves_a_distorted_images_corners() { + let mut s = session(); + let img = placed_image(&mut s); + s.execute("object.distort", &json!({ "corners": [[40, 0], [60, 0], [100, 100], [0, 100]] })).unwrap(); + s.execute("effect.apply", &json!({"ids": [img.0], "effect": "distort.transform", "params": {"moveH": 200}})).unwrap(); + s.execute("select.set", &json!({"ids": [img.0]})).unwrap(); + s.execute("effect.expandAppearance", &json!({})).unwrap(); + let mut found = vec![]; + for layer in &s.doc().unwrap().doc.layers { + layer.walk(&mut |n| { + if let Some(q) = n.image_corners() { + found.push(q); + } + }); + } + let want = [(240.0, 0.0), (260.0, 0.0), (300.0, 100.0), (200.0, 100.0)]; + assert!(found.iter().any(|q| q.iter().zip(want).all(|(p, (x, y))| p.distance(Point::new(x, y)) < 1e-6)), "{found:?}"); +} + +/// A Transform effect after a Warp effect moves a distorted image's warped pixels once: the art +/// stands where the Warp alone draws it, moved by the Transform. +#[test] +fn a_transform_after_a_warp_moves_a_distorted_image_once() { + let expanded_bounds = |transform: bool| { + let mut s = session(); + let img = placed_image(&mut s); + s.execute("object.distort", &json!({ "corners": [[40, 0], [60, 0], [100, 100], [0, 100]] })).unwrap(); + s.execute("effect.apply", &json!({"ids": [img.0], "effect": "warp.bulge", "params": {"bend": 50}})).unwrap(); + if transform { + s.execute("effect.apply", &json!({"ids": [img.0], "effect": "distort.transform", "params": {"moveH": 200}})).unwrap(); + } + s.execute("select.set", &json!({"ids": [img.0]})).unwrap(); + s.execute("effect.expandAppearance", &json!({})).unwrap(); + let mut images = None; + for layer in &s.doc().unwrap().doc.layers { + layer.walk(&mut |n| { + if let vectorcraft_doc::NodeKind::Image(im) = &n.kind { + let r = im.xf.transform_rect_bbox(vectorcraft_geom::Rect::new(0.0, 0.0, f64::from(im.width), f64::from(im.height))); + images = Some(images.map_or(r, |b: vectorcraft_geom::Rect| b.union(r))); + } + }); + } + images.expect("the warped pieces") + }; + let (alone, moved) = (expanded_bounds(false), expanded_bounds(true)); + assert!((moved.x0 - alone.x0 - 200.0).abs() < 1e-6 && (moved.x1 - alone.x1 - 200.0).abs() < 1e-6, "{alone:?} {moved:?}"); + assert!((moved.y0 - alone.y0).abs() < 1e-6 && (moved.y1 - alone.y1).abs() < 1e-6, "{alone:?} {moved:?}"); +} + +/// A raster effect's baked pixels already show the distortion: the image that replaces a +/// distorted one is placed by its own transform. +#[test] +fn baked_raster_effect_pixels_replace_a_distortion() { + let mut s = session(); + let img = placed_image(&mut s); + s.execute("object.distort", &json!({ "corners": [[40, 0], [60, 0], [100, 100], [0, 100]] })).unwrap(); + let v = s.doc().unwrap().doc.node(img).unwrap().clone(); + let baked = Node::new(NodeId(99), v.kind.clone()); + let out = crate::cmd::rasterfx::replace_with_image(v, baked); + assert!(!out.is_distorted_image()); + assert!(out.extras().image_quad.is_none()); +} + +/// A distorted image is saved with its corners and reads back the same. +#[test] +fn a_distorted_image_saves_and_reads_back() { + let mut s = session(); + let img = placed_image(&mut s); + s.execute("object.distort", &json!({ "corners": [[40, 0], [60, 0], [100, 100], [0, 100]] })).unwrap(); + let doc = &s.doc().unwrap().doc; + let bytes = vectorcraft_format::save(doc, false); + let back = vectorcraft_format::load(&bytes).unwrap(); + assert_eq!(back.node(img).unwrap().image_corners(), doc.node(img).unwrap().image_corners()); + assert!(back.node(img).unwrap().is_distorted_image()); + assert!(String::from_utf8_lossy(&bytes).contains("image_quad")); + // An image without a distortion is saved without the field, and opens as it was. + let mut plain = session(); + let img = placed_image(&mut plain); + let doc = &plain.doc().unwrap().doc; + let bytes = vectorcraft_format::save(doc, false); + assert!(!String::from_utf8_lossy(&bytes).contains("image_quad")); + let back = vectorcraft_format::load(&bytes).unwrap(); + assert_eq!(back.node(img), doc.node(img)); + // Corners in a file that fold the image over leave it placed by its transform. + let mut bad = (**doc).clone(); + bad.node_mut(img).unwrap().extras_mut().image_quad = + Some(Box::new([(0.0, 0.0), (100.0, 0.0), (0.0, 100.0), (100.0, 100.0)].map(|(x, y)| Point::new(x, y)))); + let back = vectorcraft_format::load(&vectorcraft_format::save(&bad, false)).unwrap(); + assert!(!back.node(img).unwrap().is_distorted_image()); + assert_corners(back.node(img).unwrap().image_corners().unwrap(), [(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)]); +} + +/// A distort whose corners cross the warp's horizon at the image is refused with that reason, and +/// a distort that leaves a distorted image where it is records nothing. +#[test] +fn distort_names_the_horizon_and_an_unchanged_distort_of_a_distorted_image_records_nothing() { + let mut s = session(); + let img = placed_image(&mut s); + let (before, undo) = (s.doc().unwrap().doc.clone(), undo_len(&s)); + // The box (0, 0)-(10, 10) widens toward its bottom so fast that the warp's horizon lies at + // y = 15, inside the image. + let e = s.execute("object.distort", &json!({"from": [0, 0, 10, 10], "corners": [[0, 0], [10, 0], [20, 10], [-10, 10]]})).unwrap_err().to_string(); + assert!(e.contains("horizon"), "{e}"); + assert_eq!(s.doc().unwrap().doc, before); + assert_eq!(undo_len(&s), undo); + s.execute("object.distort", &json!({ "corners": [[40, 0], [60, 0], [100, 100], [0, 100]] })).unwrap(); + let (before, undo) = (s.doc().unwrap().doc.clone(), undo_len(&s)); + let b = bounds(&s, img); + let at = [[b.x0, b.y0], [b.x1, b.y0], [b.x1, b.y1], [b.x0, b.y1]]; + s.execute("object.distort", &json!({ "from": [b.x0, b.y0, b.x1, b.y1], "corners": at })).unwrap(); + assert_eq!(s.doc().unwrap().doc, before); + assert_eq!(undo_len(&s), undo); +} + +/// Image info gives a distorted image's resolution at its middle, not the resolution it had +/// before the distort. +#[test] +fn image_info_measures_a_distorted_image_at_its_middle() { + let mut s = session(); + placed_image(&mut s); + // 2 pixels across 100 pt: 1.44 ppi. + let ppi = |s: &mut Session| { + let out = s.execute("image.info", &json!({})).unwrap(); + [out["ppi"][0].as_f64().unwrap(), out["ppi"][1].as_f64().unwrap()] + }; + assert!((ppi(&mut s)[0] - 1.44).abs() < 1e-9); + // The top squeezed to half the width: the middle of the pixels spans less than 100 pt across, + // so the resolution across there is higher. + s.execute("object.distort", &json!({ "corners": [[25, 0], [75, 0], [100, 100], [0, 100]] })).unwrap(); + let [x, _] = ppi(&mut s); + assert!(x > 1.44 * 1.1, "{x}"); +} + +/// Rasterize draws a distorted image's pixels between its corners, and the image it makes is a +/// plain one. +#[test] +fn rasterize_draws_a_distorted_image_between_its_corners() { + let mut s = session(); + let img = placed_image(&mut s); + let mut png = std::io::Cursor::new(vec![]); + image::RgbaImage::from_pixel(2, 2, image::Rgba([255, 0, 0, 255])).write_to(&mut png, image::ImageFormat::Png).unwrap(); + s.edit("Pixels", |d, _| { + d.images.insert("pic".into(), vectorcraft_doc::ImageBlob::png(png.into_inner())); + Ok(()) + }) + .unwrap(); + s.execute("object.distort", &json!({ "corners": [[40, 0], [60, 0], [100, 100], [0, 100]] })).unwrap(); + s.execute("select.set", &json!({ "ids": [img.0] })).unwrap(); + let out = s.execute("object.rasterize", &json!({ "ppi": 72, "background": "transparent", "addAround": 0 })).unwrap(); + let d = &s.doc().unwrap().doc; + let id = NodeId(out["id"].as_u64().unwrap()); + let n = d.node(id).unwrap(); + assert!(!n.is_distorted_image()); + let vectorcraft_doc::NodeKind::Image(im) = &n.kind else { panic!("an image") }; + // The raster covers the corners' bounds. + let b = n.geometric_bounds().unwrap(); + assert!([b.x0, b.y0, b.x1 - 100.0, b.y1 - 100.0].iter().all(|v| v.abs() <= 1.0), "{b:?}"); + let px = craft_image_codecs::decode(&d.images[&im.key].bytes).unwrap(); + let (w, h) = px.dimensions(); + let rgba = px.to_rgba8(); + let alpha = |x: f64, y: f64| { + let p = im.xf.inverse() * Point::new(x, y); + assert!(p.x >= 0.0 && p.y >= 0.0 && p.x < f64::from(w) && p.y < f64::from(h), "({x}, {y}) is outside the raster: {p:?}"); + let (i, j) = (p.x as u32, p.y as u32); + rgba[((j * w + i) * 4 + 3) as usize] + }; + assert_eq!(alpha(50.0, 90.0), 255, "inside the corners"); + assert_eq!(alpha(10.0, 10.0), 0, "inside the old rectangle, outside the corners"); +} + +/// A Free Transform drag in Free Distort mode on an image puts the dragged corner where the drag +/// ends, in one undo step, also when a position on the way would have folded the image. +#[test] +fn free_transform_distort_drag_on_an_image_is_one_undo_step() { + let mut s = session(); + let img = placed_image(&mut s); + let undo = undo_len(&s); + let v = ViewInfo::default(); + s.select_tool("freeTransform", v).unwrap(); + s.set_tool_option("mode", &json!("distort")); + s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 100.0), v).unwrap(); + // Past the top left corner: the image would fold over. + s.pointer(&PointerEvent::new(PointerKind::Drag, -50.0, -50.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 130.0, 120.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 130.0, 120.0), v).unwrap(); + assert_corners(corners(&s, img), [(0.0, 0.0), (100.0, 0.0), (130.0, 120.0), (0.0, 100.0)]); + assert!(s.doc().unwrap().doc.node(img).unwrap().is_distorted_image()); + assert_eq!(undo_len(&s), undo + 1); +} + #[test] fn free_transform_distort_mode_via_pointer() { let mut s = session(); diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index 5f36c5a98e..7b1caffb7c 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -298,6 +298,10 @@ impl Session { let points = self.tool.options().get("meshPoints").cloned().unwrap_or_else(|| Value::Array(vec![])); lent.set_option("meshPoints", &points); } + // The Cmd/Ctrl held for the loan is not the Cmd/Ctrl that mirrors a dragged handle (#7842). + if id == "directSelection" { + lent.set_option("lentByCmd", &Value::Bool(true)); + } self.selection_at_lend = self.active().map(|d| (d.uid, d.selection.clone())); self.lender = Some(std::mem::replace(&mut self.tool, lent)); Ok((PointerEvent { mods: Mods { cmd: false, ..ev.mods }, ..*ev }, settled)) @@ -611,13 +615,18 @@ impl Session { /// Escape, as during a drag, for most tools), and a release returns the tool to rest. Of what /// the tool asks for along the way, only a cancel and a notify run, so a marquee selects /// nothing and a click opens no size dialog. The tool gets back the persistent options it had - /// when the press began, and none of the press's changes to them are stored. A dropped Type - /// press restores the prior selection. The freeform gradient point selected once the tool - /// took the press is selected again. A press held while the tool computes an edit on another - /// thread has not reached the tool: it is removed from the held input with the pointer events - /// and tool keys held after it, and the tool is left as it is. A perspective plane key held - /// after it stays held, since the plane it picks outlasts a dropped press. Pointer events held - /// after the last held release belong to the press the tool has, and are removed with it. + /// when the press began, and none of the press's changes to them are stored. An option set + /// during the press with [`Self::set_tool_option`] or [`Self::set_tool_options`], or a General › + /// Corner Radius change during a Rounded Rectangle press, keeps its new value, also when the + /// tool lent a selection tool for the press (a Cmd-drag). Setting an option stores all of the + /// tool's options, the press's changes included, so the dropped press then stores the options + /// it puts back. A dropped Type press restores the prior selection. The freeform gradient + /// point selected once the tool took the press is selected again. A press held while the tool + /// computes an edit on another thread has not reached the tool: it is removed from the held + /// input with the pointer events and tool keys held after it, and the tool is left as it is. + /// A perspective plane key held after it stays held, since the plane it picks outlasts a + /// dropped press. Pointer events held after the last held release belong to the press the tool + /// has, and are removed with it. pub fn drop_tool_press(&mut self, view: ViewInfo) -> Result<()> { let (from, held) = self.held_press(); let keep: Vec = (self.held_input.iter().enumerate()) @@ -635,6 +644,7 @@ impl Session { // Nothing to roll back without a document; the tool still drops the press and gets the release. let _ = self.cancel_interaction(); let before = self.press_options.take(); + let stored = std::mem::take(&mut self.press_options_stored); let type_selection = self.press_type_selection.take(); let point = self.press_point.take(); let mut acts = self.with_tool_cx(view, |t, cx| t.drop_press(cx)); @@ -669,6 +679,11 @@ impl Session { self.tool.set_option(k, v); } } + // An option set during the press stored every option the tool had then, the press's + // changes included: those stored values are put back too. + if stored { + self.keep_tool_settings(); + } } r.map(drop) } @@ -706,6 +721,7 @@ impl Session { match ev.kind { PointerKind::Down => { self.press_options = Some((self.tool.id().to_string(), Self::persistent_options(self.tool.as_ref()))); + self.press_options_stored = false; self.press_type_selection = if matches!(self.tool.id(), "type" | "areaType" | "typeOnPath" | "verticalType" | "verticalAreaType" | "verticalTypeOnPath") { self.active().map(|st| (st.selection.clone(), st.active_layer)) @@ -715,6 +731,7 @@ impl Session { } PointerKind::Up => { self.press_options = None; + self.press_options_stored = false; self.press_type_selection = None; } _ => {} @@ -839,6 +856,12 @@ impl Session { self.ruler_origin = None; } + /// A guide is being dragged out of a ruler ([`Session::ruler_guide`]): its first event came + /// and its release has not. + pub fn ruler_guide_dragging(&self) -> bool { + self.ruler_guide.is_some() + } + /// Time passed while the pointer button is held (`dt` seconds; see [`Tool::tick`]): the /// desktop app ticks every frame of a press, agents with `holdMs` on a pointer event. pub fn tool_tick(&mut self, dt: f64, view: ViewInfo) -> Result> { @@ -1239,6 +1262,12 @@ impl Session { self.with_tool_cx(view, |t, cx| t.ends_on_escape(cx)) } + /// The point a path the active tool is drawing goes on from, and the direction the path + /// arrives there in (see `Tool::drawing_end`). + pub fn tool_drawing_end(&mut self, view: ViewInfo) -> Option<(Point, Option)> { + self.with_tool_cx(view, |t, cx| t.drawing_end(cx)) + } + pub fn overlays(&mut self, view: ViewInfo) -> Vec { // The Blend tool's first pick is not marked after an edit that dropped it. self.tell_tool_history_moved(); @@ -1309,9 +1338,12 @@ impl Session { if key == "queue" && self.tool.id() == "place" { self.note_place_queue_roots(); } + let before_press = self.options_before_press_set(); + let sets_pressed = self.press_taken_by(self.tool.id()); self.tool.set_option(key, v); self.tool_set_since_reset = true; self.keep_tool_settings(); + self.keep_press_set(before_press, |k| sets_pressed && k == key, sets_pressed); } /// Keep the automation roots in force now as those the place cursor's queue, being loaded, @@ -1356,6 +1388,8 @@ impl Session { self.note_place_queue_roots(); } let active = id.is_none_or(|id| id == self.tool.id()); + let before_press = self.options_before_press_set(); + let sets_pressed = self.press_taken_by(id.unwrap_or(self.tool.id())); // The tool that lent a selection tool for a Cmd-drag is the tool chosen, and active again // when the drag ends. let lender = id.is_some_and(|id| self.lender.as_deref().is_some_and(|l| l.id() == id)); @@ -1393,9 +1427,46 @@ impl Session { let set = other.id(); Self::restore_stores(&self.prefs, self.tool.as_mut(), |store| settings::stores(set).any(|(s, _)| s == store)); } + self.keep_press_set(before_press, |k| sets_pressed && values.contains_key(k), sets_pressed); out } + /// The tool that took the press under way: the active tool, or the tool that lent a selection + /// tool for it (a Cmd-drag), which the dropped press gives its options back to. + fn pressed_tool(&self) -> Option<&dyn Tool> { + let (pressed, _) = self.press_options.as_ref()?; + std::iter::once(&self.tool).chain(self.lender.as_ref()).map(|t| t.as_ref()).find(|t| t.id() == pressed) + } + + /// Tool `id` took the press under way ([`Self::pressed_tool`]). + pub(crate) fn press_taken_by(&self, id: &str) -> bool { + self.pressed_tool().is_some_and(|t| t.id() == id) + } + + /// The persistent options of the tool that took the press under way ([`Self::pressed_tool`]) + /// before an option is set: a dropped press puts back the options it began with, except those + /// the set changes ([`Self::keep_press_set`]). + fn options_before_press_set(&self) -> Option> { + self.pressed_tool().map(Self::persistent_options) + } + + /// After an option is set during a held press, the press's saved options take the options of + /// the tool that took the press that the set changed from `before` or named (`named`), so a + /// dropped press keeps them. `stored`: the set stored that tool's options, the press's changes + /// included, so a dropped press stores the options it puts back. + fn keep_press_set(&mut self, before: Option>, named: impl Fn(&str) -> bool, stored: bool) { + let Some(before) = before else { return }; + let Some(now) = self.pressed_tool().map(Self::persistent_options) else { return }; + self.press_options_stored |= stored; + if let Some((_, saved)) = self.press_options.as_mut() { + for (k, v) in now { + if before.get(&k) != Some(&v) || named(&k) { + saved.insert(k, v); + } + } + } + } + /// `tool.setOption {tool?, key?, value?, values?}` (a command of the desktop app and of the /// headless host): set one option (`key`, `value`) or several (`values`) of `tool` (default: /// the tool active when the call arrives, named before the edit in progress is finished) → its @@ -1419,6 +1490,9 @@ impl Session { } // Every value is checked before any is set, so an invalid one changes nothing. vectorcraft_tools::builder::check_builder_options(id, &values)?; + if id == vectorcraft_tools::circle::ID { + vectorcraft_tools::circle::check_options(&values)?; + } vectorcraft_tools::symbolism::check_options(id, &values)?; if id == vectorcraft_tools::cropimage::ID { use vectorcraft_tools::cropimage as crop; @@ -1519,6 +1593,10 @@ impl Session { /// Apply tool actions. Errors from previews are reported but keep the interaction alive. pub fn apply_actions(&mut self, acts: Vec) -> Result> { let outer = std::mem::replace(&mut self.in_tool_actions, true); + let outer_bucket = self.back_to_bucket; + // The Eyedropper's sample into a stop of the Live Paint Bucket's gradient, which switches back to the bucket. + self.back_to_bucket |= + self.tool.id() == "eyedropper" && acts.iter().any(|a| matches!(a, Action::SwitchTool(t) if t == crate::cmd::LIVE_PAINT_BUCKET)); // A preview that settling applied (typing kept as its own step before a drag begins) shows // its warning in the status bar, as the tool's own commit shows its preview's. let r = if !outer && self.depth == 0 { @@ -1528,6 +1606,7 @@ impl Session { self.apply_tool_actions(acts) }; self.in_tool_actions = outer; + self.back_to_bucket = outer_bucket; if !outer && self.depth == 0 { self.trim_histories(); } diff --git a/crates/engine/tests/direct_handle_mirror.rs b/crates/engine/tests/direct_handle_mirror.rs new file mode 100644 index 0000000000..30326d8e74 --- /dev/null +++ b/crates/engine/tests/direct_handle_mirror.rs @@ -0,0 +1,630 @@ +//! Temporary Cmd/Control symmetry while Direct Selection drags an existing handle. +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use serde_json::{Value, json}; +use vectorcraft_doc::{Node, NodeId}; +use vectorcraft_engine::{Session, ViewInfo}; +use vectorcraft_geom::{Anchor, AnchorKind, Point}; +use vectorcraft_tools::{Mods, PointerEvent, PointerKind}; + +fn run(s: &mut Session, command: &str, params: Value) -> Value { + s.execute(command, ¶ms).unwrap() +} + +fn view() -> ViewInfo { + ViewInfo { + smart_guides: false, + guides: false, + snap_to_point: false, + snap_to_grid: false, + snap_to_pixel: false, + snap_to_glyph: false, + corner_widgets: false, + show_bbox: false, + ..ViewInfo::default() + } +} + +fn session() -> Session { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 900, "height": 700})); + for (key, value) in [("constrainAngle", json!(0)), ("showHandlesMultipleAnchors", json!(true)), ("realTimeDrawing", json!(true))] { + run(&mut s, "prefs.set", json!({"key": key, "value": value})); + } + s +} + +fn node(s: &Session, id: NodeId) -> Node { + s.doc().unwrap().doc.node(id).unwrap().clone() +} + +fn curve(s: &mut Session, incoming: Point) -> NodeId { + let id = run( + s, + "path.create", + json!({"anchors": [ + {"x": 20, "y": 220}, + {"x": 100, "y": 100, "in": [incoming.x, incoming.y], "out": [180, 100]}, + {"x": 320, "y": 220} + ]}), + ); + let id = NodeId(id["id"].as_u64().unwrap()); + s.select_tool("directSelection", view()).unwrap(); + id +} + +fn anchor(s: &Session, id: NodeId) -> Anchor { + node(s, id).path_data().unwrap().subpaths[0].anchors[1] +} + +fn pointer(s: &mut Session, kind: PointerKind, at: Point, mods: Mods) { + s.pointer(&PointerEvent::new(kind, at.x, at.y).with_mods(mods), view()).unwrap(); +} + +fn press_handle(s: &mut Session, at: Point) { + pointer(s, PointerKind::Down, at, Mods::default()); + assert_eq!(s.tool_id(), "directSelection"); + assert!(s.in_interaction(), "the visible handle press begins Reshape"); +} + +fn near(actual: Point, expected: Point) { + assert!(actual.distance(expected) < 1e-6, "point {actual:?}, expected {expected:?}"); +} + +fn handles(a: Anchor, incoming: Point, outgoing: Point, kind: AnchorKind) { + near(a.h_in, incoming); + near(a.h_out, outgoing); + assert_eq!(a.kind, kind); +} + +fn assert_other_geometry(s: &Session, id: NodeId, before: &Node) { + let after = node(s, id); + let (old, new) = (before.path_data().unwrap(), after.path_data().unwrap()); + assert_eq!(new.subpaths.len(), old.subpaths.len()); + assert_eq!(new.subpaths[0].closed, old.subpaths[0].closed); + assert_eq!(new.subpaths[0].anchors.len(), 3); + assert_eq!(new.subpaths[0].anchors[0], old.subpaths[0].anchors[0]); + assert_eq!(new.subpaths[0].anchors[2], old.subpaths[0].anchors[2]); + assert_eq!(new.subpaths[0].anchors[1].p, old.subpaths[0].anchors[1].p); + assert_eq!(after.appearance, before.appearance); +} + +#[test] +fn direct_handle_baseline_ordinary_smooth_keeps_the_opposite_length() { + let mut s = session(); + let id = curve(&mut s, Point::new(50.0, 100.0)); + let before = node(&s, id); + assert_eq!(anchor(&s, id).kind, AnchorKind::Smooth); + let selection = json!(s.doc().unwrap().selection); + let undo = s.doc().unwrap().history.undo.len(); + press_handle(&mut s, Point::new(180.0, 100.0)); + let q = Point::new(180.0, 160.0); + pointer(&mut s, PointerKind::Drag, q, Mods::default()); + handles(anchor(&s, id), Point::new(60.0, 70.0), q, AnchorKind::Smooth); + assert_other_geometry(&s, id, &before); + pointer(&mut s, PointerKind::Up, q, Mods::default()); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1); + assert_eq!(json!(s.doc().unwrap().selection), selection); +} + +#[test] +fn direct_handle_baseline_cmd_added_mid_drag_mirrors_the_opposite() { + let mut s = session(); + let id = curve(&mut s, Point::new(50.0, 100.0)); + let before = node(&s, id); + press_handle(&mut s, Point::new(180.0, 100.0)); + let q = Point::new(180.0, 160.0); + pointer(&mut s, PointerKind::Drag, q, Mods::default()); + handles(anchor(&s, id), Point::new(60.0, 70.0), q, AnchorKind::Smooth); + pointer(&mut s, PointerKind::Drag, q, Mods { cmd: true, ..Mods::default() }); + handles(anchor(&s, id), Point::new(20.0, 40.0), q, AnchorKind::Smooth); + assert_other_geometry(&s, id, &before); + pointer(&mut s, PointerKind::Up, q, Mods { cmd: true, ..Mods::default() }); +} + +#[test] +fn direct_handle_cmd_mirror_holds_through_a_space_translation() { + let mut s = session(); + let id = curve(&mut s, Point::new(50.0, 100.0)); + press_handle(&mut s, Point::new(180.0, 100.0)); + let q = Point::new(180.0, 160.0); + pointer(&mut s, PointerKind::Drag, q, cmd()); + handles(anchor(&s, id), Point::new(20.0, 40.0), q, AnchorKind::Smooth); + // Space moves the anchor and both handles; the opposite handle stays mirrored. + let moved = Point::new(200.0, 190.0); + pointer(&mut s, PointerKind::Drag, moved, Mods { space: true, ..cmd() }); + let a = anchor(&s, id); + near(a.p, Point::new(120.0, 130.0)); + handles(a, Point::new(40.0, 70.0), Point::new(200.0, 190.0), AnchorKind::Smooth); + // Releasing Space without moving keeps the translated, mirrored handles. + pointer(&mut s, PointerKind::Drag, moved, cmd()); + handles(anchor(&s, id), Point::new(40.0, 70.0), Point::new(200.0, 190.0), AnchorKind::Smooth); + let next = Point::new(220.0, 190.0); + pointer(&mut s, PointerKind::Drag, next, cmd()); + assert_mirrored(anchor(&s, id), next, AnchorKind::Smooth); + pointer(&mut s, PointerKind::Up, next, cmd()); +} + +#[test] +fn direct_handle_modifiers_changed_during_a_space_translation_apply_at_once() { + let mut s = session(); + let id = curve(&mut s, Point::new(50.0, 100.0)); + press_handle(&mut s, Point::new(180.0, 100.0)); + pointer(&mut s, PointerKind::Drag, Point::new(180.0, 160.0), cmd()); + let moved = Point::new(200.0, 190.0); + pointer(&mut s, PointerKind::Drag, moved, Mods { space: true, ..cmd() }); + handles(anchor(&s, id), Point::new(40.0, 70.0), moved, AnchorKind::Smooth); + // Releasing Cmd while Space is held gives the opposite handle its own length again. + pointer(&mut s, PointerKind::Drag, moved, Mods { space: true, ..Mods::default() }); + let a = anchor(&s, id); + near(a.p, Point::new(120.0, 130.0)); + handles(a, Point::new(80.0, 100.0), moved, AnchorKind::Smooth); + // Alt while Space is held leaves the opposite handle where the translation put it. + pointer(&mut s, PointerKind::Drag, moved, Mods { space: true, alt: true, ..cmd() }); + handles(anchor(&s, id), Point::new(70.0, 130.0), moved, AnchorKind::Corner); + pointer(&mut s, PointerKind::Up, moved, Mods { alt: true, ..cmd() }); +} + +#[derive(Debug, PartialEq)] +struct Snapshot { + document: Value, + selection: Value, + undo: usize, + redo: usize, +} + +fn snapshot(s: &Session) -> Snapshot { + let st = s.doc().unwrap(); + Snapshot { document: json!(st.doc), selection: json!(st.selection), undo: st.history.undo.len(), redo: st.history.redo.len() } +} + +fn assert_content(s: &Session, expected: &Snapshot) { + let got = snapshot(s); + assert_eq!(got.document, expected.document); + assert_eq!(got.selection, expected.selection); +} + +fn cmd() -> Mods { + Mods { cmd: true, ..Mods::default() } +} + +fn reflected(a: Point, q: Point) -> Point { + a - (q - a) +} + +fn constrained(a: Point, q: Point) -> Point { + a + vectorcraft_geom::constrain_angle_from(q - a, 45.0, 0.0) +} + +fn assert_mirrored(a: Anchor, q: Point, kind: AnchorKind) { + handles(a, reflected(a.p, q), q, kind); +} + +#[test] +fn direct_handle_stationary_cmd_release_repress_commit_and_next_gesture() { + let mut s = session(); + let id = curve(&mut s, Point::new(50.0, 100.0)); + let before = snapshot(&s); + press_handle(&mut s, Point::new(180.0, 100.0)); + let q = Point::new(180.0, 160.0); + for (mods, opposite) in [(cmd(), Point::new(20.0, 40.0)), (Mods::default(), Point::new(60.0, 70.0)), (cmd(), Point::new(20.0, 40.0))] { + pointer(&mut s, PointerKind::Drag, q, mods); + handles(anchor(&s, id), opposite, q, AnchorKind::Smooth); + assert_eq!(s.doc().unwrap().history.undo.len(), before.undo, "previews are not separate edits"); + } + pointer(&mut s, PointerKind::Up, q, cmd()); + let committed = snapshot(&s); + assert_eq!(committed.undo, before.undo + 1); + assert_eq!(committed.selection, before.selection); + run(&mut s, "edit.undo", json!({})); + assert_content(&s, &before); + run(&mut s, "edit.redo", json!({})); + assert_content(&s, &committed); + // Cmd did not install a persistent coupling mode: a later ordinary Smooth drag keeps + // the opposite handle's committed length, rather than matching the newly dragged length. + press_handle(&mut s, q); + let next = Point::new(180.0, 200.0); + pointer(&mut s, PointerKind::Drag, next, Mods::default()); + let a = anchor(&s, id); + near(a.h_out, next); + assert_eq!(a.kind, AnchorKind::Smooth); + assert!((a.h_in.distance(a.p) - 100.0).abs() < 1e-6); + assert!((a.h_in.distance(a.p) - a.h_out.distance(a.p)).abs() > 20.0); + assert!(((a.h_in - a.p).cross(a.h_out - a.p)).abs() < 1e-6); + pointer(&mut s, PointerKind::Up, next, Mods::default()); + assert_eq!(s.doc().unwrap().history.undo.len(), before.undo + 2); +} + +#[test] +fn direct_handle_shift_constrains_before_mirroring_and_alt_takes_priority() { + let mut s = session(); + let id = curve(&mut s, Point::new(50.0, 100.0)); + let p = anchor(&s, id).p; + press_handle(&mut s, Point::new(180.0, 100.0)); + let raw = Point::new(180.0, 150.0); + let q = constrained(p, raw); + let shifted = Mods { shift: true, ..cmd() }; + pointer(&mut s, PointerKind::Drag, raw, shifted); + assert_mirrored(anchor(&s, id), q, AnchorKind::Smooth); + pointer(&mut s, PointerKind::Drag, raw, Mods { alt: true, ..shifted }); + handles(anchor(&s, id), Point::new(50.0, 100.0), q, AnchorKind::Corner); + // Removing Alt rebuilds from the original Smooth anchor, not the Corner preview. + pointer(&mut s, PointerKind::Drag, raw, shifted); + assert_mirrored(anchor(&s, id), q, AnchorKind::Smooth); + pointer(&mut s, PointerKind::Drag, raw, Mods { alt: true, ..cmd() }); + handles(anchor(&s, id), Point::new(50.0, 100.0), raw, AnchorKind::Corner); + pointer(&mut s, PointerKind::Up, raw, Mods { alt: true, ..cmd() }); +} + +#[test] +fn direct_handle_corner_with_collapsed_partner_is_reversible_without_changing_kind() { + let mut s = session(); + let id = curve(&mut s, Point::new(100.0, 100.0)); + let before = snapshot(&s); + assert_eq!(anchor(&s, id).kind, AnchorKind::Corner); + press_handle(&mut s, Point::new(180.0, 100.0)); + let q = Point::new(180.0, 160.0); + pointer(&mut s, PointerKind::Drag, q, cmd()); + assert_mirrored(anchor(&s, id), q, AnchorKind::Corner); + pointer(&mut s, PointerKind::Drag, q, Mods::default()); + handles(anchor(&s, id), Point::new(100.0, 100.0), q, AnchorKind::Corner); + pointer(&mut s, PointerKind::Drag, q, cmd()); + assert_mirrored(anchor(&s, id), q, AnchorKind::Corner); + s.tool_key(vectorcraft_tools::ToolKey::Escape, Mods::default(), view()).unwrap(); + assert_eq!(snapshot(&s), before); +} + +#[test] +fn direct_handle_stationary_drag_still_mirrors_unequal_partner_but_equal_is_noop() { + for (incoming, changes) in [(Point::new(50.0, 100.0), true), (Point::new(20.0, 100.0), false)] { + let mut s = session(); + let id = curve(&mut s, incoming); + let before = snapshot(&s); + let q = Point::new(180.0, 100.0); + press_handle(&mut s, q); + pointer(&mut s, PointerKind::Drag, q, cmd()); + assert_mirrored(anchor(&s, id), q, AnchorKind::Smooth); + pointer(&mut s, PointerKind::Up, q, cmd()); + if changes { + assert_eq!(s.doc().unwrap().history.undo.len(), before.undo + 1); + run(&mut s, "edit.undo", json!({})); + assert_content(&s, &before); + } else { + assert_eq!(snapshot(&s), before, "an already reflected pair records no edit"); + } + } +} + +#[test] +fn direct_handle_escape_restores_document_selection_and_existing_redo() { + let mut s = session(); + let id = curve(&mut s, Point::new(50.0, 100.0)); + run(&mut s, "shape.rectangle", json!({"x": 500, "y": 400, "width": 25, "height": 30})); + let redo_document = snapshot(&s).document; + run(&mut s, "edit.undo", json!({})); + run(&mut s, "select.set", json!({"ids": [id.0]})); + let before = snapshot(&s); + assert_eq!(before.redo, 1, "a real existing Redo is the cancellation control"); + press_handle(&mut s, Point::new(180.0, 100.0)); + let q = Point::new(180.0, 160.0); + pointer(&mut s, PointerKind::Drag, q, cmd()); + assert_mirrored(anchor(&s, id), q, AnchorKind::Smooth); + s.tool_key(vectorcraft_tools::ToolKey::Escape, Mods::default(), view()).unwrap(); + assert!(!s.in_interaction()); + assert_eq!(snapshot(&s), before); + pointer(&mut s, PointerKind::Up, q, Mods::default()); + assert_eq!(snapshot(&s), before, "a later release does not commit the canceled preview"); + run(&mut s, "edit.redo", json!({})); + assert_eq!(snapshot(&s).document, redo_document, "the prior Redo still restores its actual content"); +} + +#[test] +fn direct_handle_cmd_before_press_still_lends_selection_and_returns_direct() { + let mut s = session(); + let id = curve(&mut s, Point::new(50.0, 100.0)); + let before = snapshot(&s); + let a = anchor(&s, id); + pointer(&mut s, PointerKind::Down, a.p, cmd()); + assert_eq!(s.tool_id(), "selection", "Cmd before Down keeps the existing Selection loan"); + pointer(&mut s, PointerKind::Up, a.p, cmd()); + assert_eq!(s.tool_id(), "directSelection"); + assert_eq!(anchor(&s, id), a); + assert_eq!(snapshot(&s).document, before.document); + assert_eq!(s.doc().unwrap().history.undo.len(), before.undo); +} + +#[test] +fn direct_handle_cmd_that_lends_direct_selection_from_the_pen_does_not_mirror() { + let mut s = session(); + let id = curve(&mut s, Point::new(50.0, 100.0)); + s.select_tool("pen", view()).unwrap(); + let before = node(&s, id); + let undo = s.doc().unwrap().history.undo.len(); + pointer(&mut s, PointerKind::Down, Point::new(180.0, 100.0), cmd()); + assert_eq!(s.tool_id(), "directSelection", "Cmd lends the Pen the last selection tool"); + let q = Point::new(180.0, 160.0); + pointer(&mut s, PointerKind::Drag, q, cmd()); + handles(anchor(&s, id), Point::new(60.0, 70.0), q, AnchorKind::Smooth); + // Cmd let go and pressed again during the drag mirrors, as it does in Direct Selection itself. + pointer(&mut s, PointerKind::Drag, q, Mods::default()); + handles(anchor(&s, id), Point::new(60.0, 70.0), q, AnchorKind::Smooth); + pointer(&mut s, PointerKind::Drag, q, cmd()); + handles(anchor(&s, id), Point::new(20.0, 40.0), q, AnchorKind::Smooth); + assert_other_geometry(&s, id, &before); + pointer(&mut s, PointerKind::Up, q, cmd()); + assert_eq!(s.tool_id(), "pen"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1); +} + +#[test] +fn direct_handle_cmd_held_through_a_pen_lent_drag_leaves_the_opposite_length() { + let mut s = session(); + let id = curve(&mut s, Point::new(50.0, 100.0)); + s.select_tool("pen", view()).unwrap(); + pointer(&mut s, PointerKind::Down, Point::new(180.0, 100.0), cmd()); + let q = Point::new(180.0, 160.0); + pointer(&mut s, PointerKind::Drag, q, cmd()); + pointer(&mut s, PointerKind::Up, q, cmd()); + assert_eq!(s.tool_id(), "pen"); + handles(anchor(&s, id), Point::new(60.0, 70.0), q, AnchorKind::Smooth); +} + +fn text_anchor(s: &Session, id: NodeId) -> Anchor { + let n = node(s, id); + let vectorcraft_doc::NodeKind::Text(t) = n.kind else { panic!("text on a path") }; + t.type_path().unwrap().subpaths[0].anchors[1] +} + +fn text_properties(s: &Session, id: NodeId) -> Value { + let n = node(s, id); + let vectorcraft_doc::NodeKind::Text(t) = n.kind else { panic!("text on a path") }; + let vectorcraft_doc::TextKind::OnPath { start, end, .. } = &t.kind else { panic!("path text") }; + json!({"runs": t.runs, "para": t.para, "paras": t.paras, "xf": t.xf, "start": start, "end": end, + "effect": t.path_effect, "align": t.path_align, "spacing": t.path_spacing, "appearance": n.appearance}) +} + +fn path_text(s: &mut Session) -> NodeId { + let path = curve(s, Point::new(50.0, 100.0)); + let made = run( + s, + "text.createInPath", + json!({"path": path.0, "mode": "onPath", "text": "Along the original curve", "font": "Source Sans 3", "size": 12}), + ); + let id = NodeId(made["id"].as_u64().unwrap()); + run(s, "type.pathOptions", json!({"id": id.0, "start": 0.15, "end": 0.85})); + run(s, "object.transform", json!({"ids": [id.0], "matrix": [1.5, 0.4, 0.25, 0.9, 250, 80]})); + s.select_tool("directSelection", view()).unwrap(); + id +} + +#[test] +fn direct_handle_affine_path_text_mirrors_in_drawn_space_and_keeps_brackets() { + let mut s = session(); + let id = path_text(&mut s); + let before = snapshot(&s); + let properties = text_properties(&s, id); + assert_eq!(properties["start"], json!(0.15)); + assert_eq!(properties["end"], json!(0.85)); + let a = text_anchor(&s, id); + assert_eq!(a.kind, AnchorKind::Smooth); + near(a.p, Point::new(425.0, 210.0)); + near(a.h_out, Point::new(545.0, 242.0)); + assert!((a.h_in.distance(a.p) - a.h_out.distance(a.p)).abs() > 40.0); + press_handle(&mut s, a.h_out); + let raw = a.p + vectorcraft_geom::Vec2::new(80.0, 60.0); + pointer(&mut s, PointerKind::Drag, raw, cmd()); + assert_mirrored(text_anchor(&s, id), raw, AnchorKind::Smooth); + assert_eq!(text_properties(&s, id), properties); + let shifted = Mods { shift: true, ..cmd() }; + pointer(&mut s, PointerKind::Drag, raw, shifted); + assert_mirrored(text_anchor(&s, id), constrained(a.p, raw), AnchorKind::Smooth); + assert_eq!(text_properties(&s, id), properties); + pointer(&mut s, PointerKind::Up, raw, shifted); + let after = snapshot(&s); + assert_eq!(after.undo, before.undo + 1); + run(&mut s, "edit.undo", json!({})); + assert_content(&s, &before); + run(&mut s, "edit.redo", json!({})); + assert_content(&s, &after); +} + +fn blend_state(s: &Session, id: NodeId) -> (Anchor, Value, Vec) { + let n = node(s, id); + let vectorcraft_doc::NodeKind::Blend { children, spec } = n.kind else { panic!("blend") }; + assert!(spec.spine.is_some(), "the fixture uses an already pinned spine"); + let path = vectorcraft_doc::live::blend_spine(&children, &spec).unwrap().0; + (path.subpaths[0].anchors[1], json!(children), spec.key_anchors.clone()) +} + +fn blend(s: &mut Session) -> NodeId { + let a = run(s, "shape.rectangle", json!({"x": 15, "y": 95, "width": 10, "height": 10}))["id"].as_u64().unwrap(); + let b = run(s, "shape.rectangle", json!({"x": 295, "y": 95, "width": 10, "height": 10}))["id"].as_u64().unwrap(); + let made = run(s, "object.blend.make", json!({"ids": [a, b], "steps": 2})); + let id = NodeId(made["id"].as_u64().unwrap()); + let added = run(s, "object.blend.spine.addAnchor", json!({"id": id.0, "x": 100, "y": 100})); + assert_eq!(added["anchor"], json!(1)); + run(s, "object.blend.spine.convertAnchor", json!({"id": id.0, "anchor": 1, "to": "smooth", "x": 180, "y": 100})); + run(s, "object.blend.spine.moveAnchor", json!({"id": id.0, "anchor": 1, "handle": "in", "x": 50, "y": 100})); + run(s, "select.set", json!({"ids": [id.0]})); + s.select_tool("directSelection", view()).unwrap(); + let (middle, _, keys) = blend_state(s, id); + near(middle.p, Point::new(100.0, 100.0)); + handles(middle, Point::new(50.0, 100.0), Point::new(180.0, 100.0), AnchorKind::Smooth); + assert_eq!(keys, [0, 2]); + // An actual spine-point click makes its handles visible to Direct Selection. + pointer(s, PointerKind::Down, middle.p, Mods::default()); + pointer(s, PointerKind::Up, middle.p, Mods::default()); + assert!(!s.in_interaction()); + id +} + +#[test] +fn direct_handle_pinned_blend_spine_cmd_shift_preserves_keys_and_mapping() { + let mut s = session(); + let id = blend(&mut s); + let before = snapshot(&s); + let (a, keys, mapping) = blend_state(&s, id); + press_handle(&mut s, a.h_out); + let q = Point::new(180.0, 160.0); + pointer(&mut s, PointerKind::Drag, q, cmd()); + assert_mirrored(blend_state(&s, id).0, q, AnchorKind::Smooth); + let raw = Point::new(180.0, 150.0); + let shifted = Mods { shift: true, ..cmd() }; + pointer(&mut s, PointerKind::Drag, raw, shifted); + assert_mirrored(blend_state(&s, id).0, constrained(a.p, raw), AnchorKind::Smooth); + // The existing spine Shift-only path is deliberately unconstrained; Cmd's new rule + // must not leak into that old branch after the modifier is released. + pointer(&mut s, PointerKind::Drag, raw, Mods { shift: true, ..Mods::default() }); + near(blend_state(&s, id).0.h_out, raw); + pointer(&mut s, PointerKind::Drag, raw, shifted); + let (after_anchor, after_keys, after_mapping) = blend_state(&s, id); + assert_mirrored(after_anchor, constrained(a.p, raw), AnchorKind::Smooth); + assert_eq!(after_keys, keys, "handle edits leave the actual key art unchanged"); + assert_eq!(after_mapping, mapping); + pointer(&mut s, PointerKind::Up, raw, shifted); + let after = snapshot(&s); + assert_eq!(after.undo, before.undo + 1); + assert_eq!(after.selection, before.selection); + run(&mut s, "edit.undo", json!({})); + assert_content(&s, &before); + run(&mut s, "edit.redo", json!({})); + assert_content(&s, &after); +} + +#[test] +fn direct_handle_incoming_drag_mirrors_outgoing_and_release_restores_ordinary_length() { + let mut s = session(); + let id = curve(&mut s, Point::new(50.0, 100.0)); + let before = snapshot(&s); + let original = node(&s, id); + press_handle(&mut s, Point::new(50.0, 100.0)); + let q = Point::new(40.0, 20.0); + pointer(&mut s, PointerKind::Drag, q, Mods::default()); + handles(anchor(&s, id), q, Point::new(148.0, 164.0), AnchorKind::Smooth); + pointer(&mut s, PointerKind::Drag, q, cmd()); + handles(anchor(&s, id), q, Point::new(160.0, 180.0), AnchorKind::Smooth); + pointer(&mut s, PointerKind::Drag, q, Mods::default()); + handles(anchor(&s, id), q, Point::new(148.0, 164.0), AnchorKind::Smooth); + pointer(&mut s, PointerKind::Drag, q, cmd()); + assert_other_geometry(&s, id, &original); + pointer(&mut s, PointerKind::Up, q, cmd()); + handles(anchor(&s, id), q, Point::new(160.0, 180.0), AnchorKind::Smooth); + assert_eq!(s.doc().unwrap().history.undo.len(), before.undo + 1); + assert_eq!(snapshot(&s).selection, before.selection); + run(&mut s, "edit.undo", json!({})); + assert_content(&s, &before); +} + +/// `command` with `params` is refused with an error containing `message`, and the document, +/// selection and undo history stay as they were. +fn refused(s: &mut Session, command: &str, params: Value, message: &str) { + let before = snapshot(s); + let err = s.execute(command, ¶ms).unwrap_err().to_string(); + assert!(err.contains(message), "{command} {params}: {err}"); + assert_eq!(snapshot(s), before); +} + +#[test] +fn path_set_handle_symmetric_mirrors_refuses_bad_values_and_records_no_step_when_in_place() { + let mut s = session(); + let id = curve(&mut s, Point::new(50.0, 100.0)); + let at = |x: f64, y: f64| json!({"id": id.0, "anchor": 1, "which": "out", "x": x, "y": y}); + for bad in [json!("yes"), json!(1)] { + let mut p = at(180.0, 160.0); + p["symmetric"] = bad; + refused(&mut s, "path.setHandle", p, "`symmetric` must be true or false"); + } + let mut both = at(180.0, 160.0); + both["symmetric"] = json!(true); + both["independent"] = json!(true); + refused(&mut s, "path.setHandle", both, "`independent` and `symmetric` cannot both be true"); + + let undo = s.doc().unwrap().history.undo.len(); + let mut mirror = at(180.0, 160.0); + mirror["symmetric"] = json!(true); + run(&mut s, "path.setHandle", mirror.clone()); + handles(anchor(&s, id), Point::new(20.0, 40.0), Point::new(180.0, 160.0), AnchorKind::Smooth); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1); + let placed = snapshot(&s); + run(&mut s, "path.setHandle", mirror); + assert_eq!(snapshot(&s), placed, "both handles already in place record no undo step"); +} + +#[test] +fn symmetric_leaves_the_other_handle_retracted_at_an_open_end() { + let mut s = session(); + let id = curve(&mut s, Point::new(50.0, 100.0)); + let first = |s: &Session| node(s, id).path_data().unwrap().subpaths[0].anchors[0]; + let p = first(&s).p; + run(&mut s, "path.setHandle", json!({"id": id.0, "anchor": 0, "which": "out", "x": 60, "y": 180, "symmetric": true})); + handles(first(&s), p, Point::new(60.0, 180.0), AnchorKind::Corner); + + let mut s = session(); + let blend_id = blend(&mut s); + let end = |s: &Session| { + let n = node(s, blend_id); + let vectorcraft_doc::NodeKind::Blend { children, spec } = n.kind else { panic!("blend") }; + vectorcraft_doc::live::blend_spine(&children, &spec).unwrap().0.subpaths[0].anchors[0] + }; + let start = end(&s); + run(&mut s, "object.blend.spine.moveAnchor", json!({"id": blend_id.0, "anchor": 0, "handle": "out", "x": 60, "y": 60, "symmetric": true})); + near(end(&s).h_out, Point::new(60.0, 60.0)); + near(end(&s).h_in, start.h_in); + near(end(&s).h_in, start.p); +} + +#[test] +fn spine_and_type_path_handles_refuse_bad_symmetric_values() { + let mut s = session(); + let id = blend(&mut s); + let spine = |extra: Value| { + let mut p = json!({"id": id.0, "anchor": 1, "handle": "out", "x": 180, "y": 160}); + p.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone()); + p + }; + refused(&mut s, "object.blend.spine.moveAnchor", spine(json!({"symmetric": "yes"})), "`symmetric` must be true or false"); + refused( + &mut s, + "object.blend.spine.moveAnchor", + spine(json!({"symmetric": true, "independent": true})), + "`independent` and `symmetric` cannot both be true", + ); + refused( + &mut s, + "object.blend.spine.moveAnchor", + json!({"id": id.0, "anchor": 1, "x": 180, "y": 160, "symmetric": true}), + "`symmetric` places a handle", + ); + + let text = path_text(&mut s); + let a = text_anchor(&s, text); + let at = json!({"id": text.0, "anchor": 1, "which": "out", "x": a.h_out.x, "y": a.h_out.y + 20.0}); + let mut bad = at.clone(); + bad["symmetric"] = json!(0); + refused(&mut s, "text.setPathHandle", bad, "`symmetric` must be true or false"); + let mut both = at; + both["symmetric"] = json!(true); + both["independent"] = json!(true); + refused(&mut s, "text.setPathHandle", both, "`independent` and `symmetric` cannot both be true"); +} + +#[test] +fn direct_handle_cmd_that_lends_direct_selection_from_the_pen_does_not_mirror_type_on_a_path() { + let mut s = session(); + let id = path_text(&mut s); + let a = text_anchor(&s, id); + let length = a.h_in.distance(a.p); + s.select_tool("pen", view()).unwrap(); + pointer(&mut s, PointerKind::Down, a.h_out, cmd()); + assert_eq!(s.tool_id(), "directSelection"); + let q = a.p + vectorcraft_geom::Vec2::new(80.0, 60.0); + pointer(&mut s, PointerKind::Drag, q, cmd()); + let held = text_anchor(&s, id); + near(held.h_out, q); + assert!((held.h_in.distance(held.p) - length).abs() < 1e-6, "the other handle keeps its length"); + pointer(&mut s, PointerKind::Drag, q, Mods::default()); + pointer(&mut s, PointerKind::Drag, q, cmd()); + assert_mirrored(text_anchor(&s, id), q, AnchorKind::Smooth); + pointer(&mut s, PointerKind::Up, q, cmd()); + assert_eq!(s.tool_id(), "pen"); +} diff --git a/crates/engine/tests/scissors_snap.rs b/crates/engine/tests/scissors_snap.rs index f44b0e6f66..6d12bd6457 100644 --- a/crates/engine/tests/scissors_snap.rs +++ b/crates/engine/tests/scissors_snap.rs @@ -154,3 +154,184 @@ fn scissors_cuts_after_a_command_settles_a_deferred_move() { assert_eq!(session.doc().unwrap().history.undo.len(), undo_before + 1); } } + +/// Real Session composition: the hovered feedback must be the endpoint the actual split creates, +/// while the selected crossing owner, history and Undo/Redo contracts remain intact. +#[test] +fn review_8655_scissors_session_feedback_is_the_committed_cut_endpoint() { + let mut observed = Vec::new(); + for pixel_preview in [true, false] { + let mut session = Session::new(); + session.execute("file.new", &json!({"width":800,"height":600})).unwrap(); + let rectangle = + NodeId(session.execute("shape.rectangle", &json!({"x":100,"y":100,"width":100,"height":100})).unwrap()["id"].as_u64().unwrap()); + let crossing = NodeId(session.execute("shape.line", &json!({"x1":145,"y1":90,"x2":165,"y2":130})).unwrap()["id"].as_u64().unwrap()); + session.execute("select.set", &json!({"ids":[rectangle.0]})).unwrap(); + let view = ViewInfo { pixel_preview, ..ViewInfo::default() }; + session.select_tool("scissors", view).unwrap(); + let original = path(&session, rectangle); + let other = path(&session, crossing); + let selection_before = session.doc().unwrap().selection.clone(); + let undo_before = session.doc().unwrap().history.undo.len(); + let raw = Point::new(152.0, 101.5); + session.pointer(&PointerEvent::new(PointerKind::Move, raw.x, raw.y), view).unwrap(); + let overlays = session.overlays(view); + let markers: Vec<_> = overlays + .iter() + .filter_map(|o| match o { + Overlay::Anchor { p, color, filled: false, size } if *color == vectorcraft_tools::draw2::FEEDBACK && *size == 7.0 => Some(*p), + _ => None, + }) + .collect(); + let intersection = overlays.iter().any(|o| matches!(o, Overlay::Label { text, .. } if text == "intersect")); + assert_eq!(intersection, !pixel_preview, "CONTROL: native view boundary retains Smart Guides policy"); + for kind in [PointerKind::Down, PointerKind::Up] { + session.pointer(&PointerEvent::new(kind, raw.x, raw.y), view).unwrap(); + } + let opened = path(&session, rectangle); + assert!(!opened.is_closed()); + let anchors = &opened.subpaths[0].anchors; + assert_eq!(anchors.len(), 6); + let cut = anchors[0].p; + assert_eq!(anchors.last().unwrap().p, cut); + let expected = Point::new(if pixel_preview { 152.0 } else { 150.0 }, 100.0); + assert!(cut.distance(expected) < 1e-6, "CONTROL: actual cut geometry respects view snapping"); + assert!(cut.distance(raw) > 1.0, "CONTROL: feedback is projected to the path, not raw input"); + let selection_after = session.doc().unwrap().selection.clone(); + assert_eq!(selection_after.objects, [rectangle]); + assert_eq!(selection_after.partial(rectangle).unwrap().iter().copied().collect::>(), [(0, 0)]); + assert!(selection_after.segments.is_empty()); + assert_eq!(path(&session, crossing), other); + assert_eq!(session.doc().unwrap().history.undo.len(), undo_before + 1); + assert!( + session.overlays(view).iter().all(|o| !matches!(o, Overlay::Anchor { color, filled:false, size, .. } + if *color == vectorcraft_tools::draw2::FEEDBACK && *size == 7.0)), + "CONTROL: Up clears cut feedback" + ); + session.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(path(&session, rectangle), original); + assert_eq!(path(&session, crossing), other); + assert_eq!(session.doc().unwrap().selection, selection_before); + assert_eq!(session.doc().unwrap().history.undo.len(), undo_before); + session.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(path(&session, rectangle), opened); + assert_eq!(path(&session, crossing), other); + assert_eq!(session.doc().unwrap().selection, selection_after); + assert_eq!(session.doc().unwrap().history.undo.len(), undo_before + 1); + observed.push((pixel_preview, markers, cut)); + } + let endpoint_controls = review_8655_session_endpoint_controls(); + for (pixel_preview, markers, cut) in observed { + assert_eq!(markers.len(), 1, "REGRESSION: Pixel Preview{pixel_preview} needs one hollow7px FEEDBACK anchor"); + assert!(markers[0].distance(cut) < 1e-6, "REGRESSION: preview{markers:?} must mark the actual committed endpoint{cut:?}"); + } + for (markers, cut) in endpoint_controls { + assert_eq!(markers.len(), 1, "a successful interior/canonicalized cut has one marker"); + assert!(markers[0].distance(cut) < 1e-6, "marker{markers:?} must equal the actual Engine cut{cut:?}"); + } +} + +fn review_8655_session_markers(overlays: &[Overlay]) -> Vec { + overlays + .iter() + .filter_map(|o| match o { + Overlay::Anchor { p, color, filled: false, size } if *color == vectorcraft_tools::draw2::FEEDBACK && *size == 7.0 => Some(*p), + _ => None, + }) + .collect() +} + +fn review_8655_session_endpoint_controls() -> Vec<(Vec, Point)> { + let mut session = Session::new(); + session.execute("file.new", &json!({"width":800,"height":600})).unwrap(); + let line = NodeId(session.execute("shape.line", &json!({"x1":100,"y1":300,"x2":200,"y2":300})).unwrap()["id"].as_u64().unwrap()); + session.execute("select.set", &json!({"ids":[line.0]})).unwrap(); + let view = ViewInfo { smart_guides: false, snap_to_point: false, snap_to_grid: false, snap_to_pixel: false, ..ViewInfo::default() }; + session.select_tool("scissors", view).unwrap(); + let original = path(&session, line); + let document = json!(session.doc().unwrap().doc.as_ref()); + let selection = session.doc().unwrap().selection.clone(); + let undo = session.doc().unwrap().history.undo.len(); + let redo = session.doc().unwrap().history.redo.len(); + assert!(!original.is_closed()); + assert_eq!(original.subpaths[0].anchors.len(), 2, "CONTROL: ordinary minimal drawable open line"); + for endpoint in [Point::new(100.0, 300.0), Point::new(200.0, 300.0)] { + session.pointer(&PointerEvent::new(PointerKind::Move, endpoint.x, endpoint.y), view).unwrap(); + let endpoint_markers = review_8655_session_markers(&session.overlays(view)); + let error = session.pointer(&PointerEvent::new(PointerKind::Down, endpoint.x, endpoint.y), view).unwrap_err(); + assert!(error.to_string().contains("cannot split an open path at its end point"), "CONTROL: preserve baseline endpoint error: {error}"); + assert_eq!(json!(session.doc().unwrap().doc.as_ref()), document, "a failed endpoint cut changes no document data"); + assert_eq!(session.doc().unwrap().selection, selection); + assert_eq!(session.doc().unwrap().history.undo.len(), undo); + assert_eq!(session.doc().unwrap().history.redo.len(), redo); + assert!(endpoint_markers.is_empty(), "an endpoint that Engine rejects has no successful-cut feedback"); + session.pointer(&PointerEvent::new(PointerKind::Up, endpoint.x, endpoint.y), view).unwrap(); + } + let interior = Point::new(150.0, 300.0); + session.pointer(&PointerEvent::new(PointerKind::Move, interior.x, interior.y), view).unwrap(); + let interior_markers = review_8655_session_markers(&session.overlays(view)); + for kind in [PointerKind::Down, PointerKind::Up] { + session.pointer(&PointerEvent::new(kind, interior.x, interior.y), view).unwrap(); + } + let right_id = session.doc().unwrap().selection.objects[0]; + assert_ne!(right_id, line); + let right = path(&session, right_id); + let left = path(&session, line); + let actual_interior = right.subpaths[0].anchors[0].p; + assert!(actual_interior.distance(interior) < 1e-6); + assert_eq!(left.subpaths[0].anchors.last().unwrap().p, actual_interior); + assert_eq!(session.doc().unwrap().history.undo.len(), undo + 1); + session.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(path(&session, line), original); + assert!(session.doc().unwrap().doc.node(right_id).is_none()); + assert_eq!(session.doc().unwrap().selection, selection); + + let (canonical_markers, canonical) = review_8655_session_canonical_control(session, view); + vec![(interior_markers, actual_interior), (canonical_markers, canonical)] +} + +fn review_8655_session_canonical_control(mut session: Session, view: ViewInfo) -> (Vec, Point) { + let closed = NodeId( + session + .execute( + "path.create", + &json!({"d":"M99.99995 100 C133.33328333333333 100 166.66661666666666 100 199.99995 100 L199.99995 200 L99.99995 200 Z"}), + ) + .unwrap()["id"] + .as_u64() + .unwrap(), + ); + let mut prefs = session.prefs.clone(); + prefs.gridline_every = 10.0; + prefs.grid_subdivisions = 1; + session.apply_prefs(prefs); + assert_eq!(session.doc().unwrap().doc.grid.spacing, 10.0); + assert_eq!(session.doc().unwrap().doc.grid.subdivisions, 1); + session.execute("select.set", &json!({"ids":[closed.0]})).unwrap(); + let grid = ViewInfo { snap_to_grid: true, ..view }; + let original_closed = path(&session, closed); + assert!(original_closed.is_closed()); + let canonical = original_closed.subpaths[0].anchors[0].p; + let (_, segment, t, projected, _) = original_closed.nearest(Point::new(100.0, 100.0)).unwrap(); + assert_eq!(segment, 0); + assert!(t > 0.0 && t <= 1e-6, "CONTROL: stored native cubic reaches actual canonicalization threshold: {t}"); + assert!(projected.distance(canonical) > 1e-5, "CONTROL: projected point differs from canonical stored anchor"); + let raw = Point::new(100.1, 100.2); + session.pointer(&PointerEvent::new(PointerKind::Move, raw.x, raw.y), grid).unwrap(); + let canonical_markers = review_8655_session_markers(&session.overlays(grid)); + let before = session.doc().unwrap().history.undo.len(); + for kind in [PointerKind::Down, PointerKind::Up] { + session.pointer(&PointerEvent::new(kind, raw.x, raw.y), grid).unwrap(); + } + let opened = path(&session, closed); + assert!(!opened.is_closed()); + let anchors = &opened.subpaths[0].anchors; + assert_eq!(anchors.first().unwrap().p, canonical, "Engine commits the original anchor rather than curve.eval(t)"); + assert_eq!(anchors.last().unwrap().p, canonical); + assert_eq!(session.doc().unwrap().history.undo.len(), before + 1); + session.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(path(&session, closed), original_closed); + session.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(path(&session, closed), opened); + (canonical_markers, canonical) +} diff --git a/crates/eps/src/ai_editing.rs b/crates/eps/src/ai_editing.rs index 17177671cf..88daf4d7a1 100644 --- a/crates/eps/src/ai_editing.rs +++ b/crates/eps/src/ai_editing.rs @@ -118,7 +118,12 @@ //! `%AI24_EndSymbolList`); each instance as `/SymbolInstance :`, `(name) /SymbolRef ,`, the //! matrix taking the art to art space as `a b c d tx ty /RTransformMatrix`, `;`, then its name //! and opacity mask and a state block as a group's with its opacity and blending mode (an -//! instance with isolation, knockout or knockout shape of its own is written as its art). The +//! instance with isolation, knockout or knockout shape of its own is written as its art). A +//! dynamic symbol's art dictionary also holds `VectorCraftDynamicSymbol` (`/Int`, 1), and the +//! dictionary of an instance with changes of its own (`symbol_overrides`) holds +//! `VectorCraftSymbolOverrides`, a `/String` of the changes as hex-coded JSON: the format's own +//! entries, as other apps' editing data is not documented, read back by this reader and left out by +//! others. The //! definitions are at most the reader's 4,096. In a symbol's art, an instance's matrix and //! a gradient's take the art to the canvas's space turned y up about art space's origin there, //! and a gradient mesh's corners are in that space; an envelope's contents in its dictionary are @@ -191,7 +196,7 @@ //! and instances of //! symbols past 4,096 as their art (symbol art past [`vectorcraft_doc::MAX_SYMBOL_NODES`] objects //! in all left out), instances of symbols the document doesn't have as empty groups, symbols' 9-slice -//! guides, export types and dynamic type left out, gradient meshes the reader wouldn't read back as +//! guides, export types left out, gradient meshes the reader wouldn't read back as //! they are, folded meshes, meshes in pattern tiles and in art cut to a clipping object and every mesh //! on a large canvas as their drawn look, blends the reader wouldn't read back live as //! their steps, other live objects (placed documents included) as their art, @@ -220,6 +225,7 @@ use vectorcraft_pdf::PrivateData; use crate::ps; mod writer; +pub(crate) use writer::{DYNAMIC_KEY, OVERRIDES_KEY, hex_decode}; use writer::Writer; diff --git a/crates/eps/src/ai_editing/tests.rs b/crates/eps/src/ai_editing/tests.rs index 22d3203e3b..3fc99847d6 100644 --- a/crates/eps/src/ai_editing/tests.rs +++ b/crates/eps/src/ai_editing/tests.rs @@ -2432,6 +2432,26 @@ fn an_unpainted_paths_transparency_after_a_compound_path_is_its_own() { assert_eq!((art[0].opacity, art[0].blend, art[1].opacity, art[1].blend), (1.0, BlendMode::Normal, 0.5, BlendMode::Multiply)); } +/// A distorted image as deep as the writer goes, in the art of 8 nested opacity masks, is written +/// as one image at the placement nearest its corners, with a warning, not left out. +#[test] +fn a_distorted_image_nested_as_deep_as_the_limit_is_written_as_its_nearest_placement() { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + let mut n = image_node(&mut doc, ImageBlob::png(rgb_png()), (3, 2), Affine::translate((10.0, 10.0)) * Affine::scale(10.0), None); + n.set_image_corners([(14.0, 10.0), (36.0, 10.0), (40.0, 30.0), (10.0, 30.0)].map(|(x, y)| vectorcraft_geom::Point::new(x, y))).unwrap(); + for _ in 0..8 { + let mut owner = square(&mut doc, Rect::new(10.0, 10.0, 40.0, 30.0), Color::gray(0.5)); + owner.extras_mut().mask = Some(Box::new(OpacityMask::new(n, true))); + n = owner; + } + doc.insert(Some(layer), usize::MAX, n).unwrap(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::DEEP_DISTORTED), "{:?}", out.warnings); + // The samples are binary: count the `XI` lines in the bytes. + assert_eq!(out.program.windows(4).filter(|w| w == b"XI\r\n").count(), 1, "the one image"); +} + /// Opacity masks in mask art nested past the limit are left out, not written empty. #[test] fn opacity_masks_nested_too_deep_are_left_out() { @@ -6394,7 +6414,8 @@ fn instances_the_data_cant_hold_are_written_as_their_art() { let layer = doc.layers[0].id; doc.insert(Some(layer), usize::MAX, changed).unwrap(); doc.insert(Some(layer), usize::MAX, plain).unwrap(); - assert_eq!(export_ai_editing(&doc, &opts()).unwrap().warnings, [writer::SYMBOL_ART, writer::SYMBOL_OPTIONS]); + doc.symbols[0].dynamic = false; + assert_eq!(export_ai_editing(&doc, &opts()).unwrap().warnings, [writer::SYMBOL_ART]); let back = read_back(&doc); assert_eq!(kinds(&back), ["art", "instance"]); let green = back.layers[0].children().unwrap()[0].clone(); @@ -6890,7 +6911,7 @@ fn symbol_options_and_linked_images_in_symbols_are_reported() { let layer = doc.layers[0].id; doc.insert(Some(layer), usize::MAX, one).unwrap(); let out = export_ai_editing(&doc, &opts()).unwrap(); - assert_eq!(out.warnings, [writer::SYMBOL_OPTIONS, writer::LINKS_EMBEDDED]); + assert_eq!(out.warnings, [writer::LINKS_EMBEDDED]); let p = program_shown(&doc); assert!(p.contains("%AI5_BeginRaster") && !p.contains("%AI5_BeginPlace"), "{p}"); let back = read_back(&doc); @@ -15982,3 +16003,56 @@ fn a_mesh_eight_levels_down_is_written_as_a_mesh() { assert_eq!(back.len(), 1, "{back:#?}"); assert_mesh_exact(mesh_of(&back[0]), &want, "eight levels down"); } + +fn dynamic_doc() -> Document { + let mut doc = Document::new(200.0, 100.0); + let art = square(&mut doc, Rect::new(0.0, 0.0, 10.0, 10.0), LEAF); + doc.symbols.push(Symbol { dynamic: true, name: "Leaf".into(), art: Arc::new(art) }); + let layer = doc.layers[0].id; + for (x, c) in [(10.0, Color::rgb(1.0, 0.0, 0.0)), (50.0, Color::rgb(0.0, 0.0, 1.0))] { + let mut i = instance(&mut doc, "Leaf", Affine::translate((x, 10.0))); + i.extras_mut().symbol_overrides = vec![vectorcraft_doc::SymbolOverride { fill: Some(solid(c)), opacity: Some(0.5), ..Default::default() }]; + doc.insert(Some(layer), usize::MAX, i).unwrap(); + } + let plain = instance(&mut doc, "Leaf", Affine::translate((90.0, 10.0))); + doc.insert(Some(layer), usize::MAX, plain).unwrap(); + doc +} + +#[test] +fn dynamic_symbols_and_their_instance_changes_survive_a_round_trip() { + let doc = dynamic_doc(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert_eq!(out.warnings, [writer::SYMBOL_CHANGES]); + let back = read_back(&doc); + assert!(back.symbols[0].dynamic); + let kids = back.layers[0].children().unwrap(); + assert!(kids.iter().all(|n| matches!(n.kind, NodeKind::SymbolInstance { .. }))); + let want: Vec<_> = doc.layers[0].children().unwrap().iter().map(|n| n.extras().symbol_overrides.clone()).collect(); + let got: Vec<_> = kids.iter().map(|n| n.extras().symbol_overrides.clone()).collect(); + assert_eq!(got, want); + assert_ne!(got[0], got[1]); + assert!(got[2].is_empty()); +} + +#[test] +fn static_symbols_write_no_dynamic_entries() { + let mut doc = dynamic_doc(); + doc.symbols[0].dynamic = false; + let layer = doc.layers[0].id; + for n in doc.layers[0].children().unwrap().to_vec() { + doc.remove(n.id).unwrap(); + } + for x in [10.0, 50.0] { + let i = instance(&mut doc, "Leaf", Affine::translate((x, 10.0))); + doc.insert(Some(layer), usize::MAX, i).unwrap(); + } + let p = program(&doc); + assert!(!p.contains("VectorCraftDynamicSymbol") && !p.contains("VectorCraftSymbolOverrides")); + assert!(export_ai_editing(&doc, &opts()).unwrap().warnings.is_empty()); + let back = read_back(&doc); + assert!(!back.symbols[0].dynamic); + let kids = back.layers[0].children().unwrap(); + assert_eq!(kids.len(), 2); + assert!(kids.iter().all(|n| matches!(n.kind, NodeKind::SymbolInstance { .. }) && n.extras().symbol_overrides.is_empty())); +} diff --git a/crates/eps/src/ai_editing/writer.rs b/crates/eps/src/ai_editing/writer.rs index 41254840cb..263353c675 100644 --- a/crates/eps/src/ai_editing/writer.rs +++ b/crates/eps/src/ai_editing/writer.rs @@ -48,8 +48,9 @@ pub(super) use paints::{ GRADIENT_COMPARISONS, GRADIENT_DITHER, GRADIENT_HUE, GRADIENT_PERCEPTUAL, GRADIENT_SHAPES, GRADIENTS, SCANNED_DEFINITIONS, STOP_LINKS, SWATCH_PLACEMENT, free_gradient_name, }; +pub(crate) use symbols::{DYNAMIC_KEY, OVERRIDES_KEY, hex_decode}; #[cfg(test)] -pub(super) use symbols::{MISSING_SYMBOL, SYMBOL_ART, SYMBOL_COUNT, SYMBOL_OPTIONS}; +pub(super) use symbols::{MISSING_SYMBOL, SYMBOL_ART, SYMBOL_CHANGES, SYMBOL_COUNT, SYMBOL_OPTIONS}; #[cfg(test)] pub(super) use texts::{FONT_RESOLVES, RESOLVE_EACH_RUN, TYPE_ATTRIBUTES}; #[cfg(test)] @@ -66,7 +67,9 @@ pub(super) const PATTERN_TILES: &str = "pattern fills with more tiles than a fil pub(super) const CLIPPING: &str = "clipping groups and clipping layers whose clipping object isn't a path, and the clipping groups inside them, are written as their art cut to that object in the editing data for other apps"; pub(super) const CLIP_PAINT: &str = "the fills and strokes of clipping paths that a plain fill and line can't draw are written as paths of their own inside the clipping (fills under the clipped art, strokes over it) in the editing data for other apps"; pub(super) const CLIP_PAINT_MASKS: &str = "the opacity masks of clipping paths whose fills and strokes are written as paths of their own stay on the clipping path, not on those paths, in the editing data for other apps"; -pub(super) const LIVE: &str = "repeats, placed documents and intertwines are written as their art in the editing data for other apps"; +pub(super) const LIVE: &str = + "repeats, placed documents, intertwines and distorted images are written as their art in the editing data for other apps"; +pub(super) const DEEP_DISTORTED: &str = "images changed by Perspective Distort or Free Distort more than 8 deep in opacity masks, symbols, live objects and pattern tiles are written as the nearest parallelogram in the editing data for other apps"; pub(super) const GRAPHS: &str = "graphs are written as their art, without their data or settings, in the editing data for other apps"; pub(super) const STROKES: &str = "strokes a plain line can't draw (inside or outside the path, variable width, dots, dashes fitted to corners, gradients, patterns, arrowheads) are written as filled outlines, and brushed strokes as their brush's art, in the editing data for other apps"; pub(super) const ITEM_TRANSPARENCY: &str = @@ -286,6 +289,7 @@ pub(super) struct Writer<'a> { symbol_scales: HashMap, /// The entries a symbol's dictionary adds to its art's dictionary, and the art's id. root_entries: Option<(vectorcraft_doc::NodeId, String)>, + instance_entries: Option<(vectorcraft_doc::NodeId, String)>, /// The objects that may be written with an art style, as they were before baking, by id /// ([`styles::styled_objects`]). pub(super) styled: HashMap>, @@ -405,6 +409,7 @@ impl<'a> Writer<'a> { inner_scale: 1.0, symbol_scales: HashMap::new(), root_entries: None, + instance_entries: None, styled: HashMap::new(), symbol_styled: HashMap::new(), pattern_styled: HashMap::new(), @@ -799,6 +804,7 @@ impl<'a> Writer<'a> { } NodeKind::Compound { rule, .. } => self.shape(n, &compound_path(n), *rule, xy), NodeKind::Text(_) => self.text(n, xy), + NodeKind::Image(im) if n.is_distorted_image() => self.distorted_image(n, im, xy), NodeKind::Image(im) => { // An opacity mask that clips shows the image within what its art paints only (its // effects and its symbol instances' art included, as the renderer measures it). @@ -818,7 +824,7 @@ impl<'a> Writer<'a> { mask_window = self.windowed.take(); } } - NodeKind::SymbolInstance { symbol, xf } if self.live_instance_in_room(n, symbol, *xf) => self.symbol_instance(symbol, *xf, xy), + NodeKind::SymbolInstance { symbol, xf } if self.live_instance_in_room(n, symbol, *xf) => self.symbol_instance(n, symbol, *xf, xy), NodeKind::SymbolInstance { symbol, xf } => { if !self.open_group("u") { return; @@ -944,6 +950,18 @@ impl<'a> Writer<'a> { self.warn(GRAPHS); } + /// Distorted image `n` (`im`), of transparency `xy`: the mesh of its pieces while the art may + /// nest further, else one image at the placement nearest its corners, with a warning. + fn distorted_image(&mut self, n: &Node, im: &vectorcraft_doc::ImageObject, xy: Xy) { + if self.nest < MAX_NEST { + return self.drawn_art(n, xy, Some(LIVE), true); + } + let Some(near) = vectorcraft_doc::image_quad::nearest_affine(n) else { return }; + self.warn(DEEP_DISTORTED); + self.windowed = None; + self.image(&vectorcraft_doc::ImageObject { xf: near, ..self.doc.shown_image(n, im).into_owned() }, xy); + } + /// Live object `n`, of transparency `xy`, as a group of its art, with `warning` when it is given. /// With `bounds`, `n`'s text wrap options go on the rectangle of its bounds, the group's first /// member ([`Self::wrap_on_bounds`]); without it, in the group's dictionary. @@ -1016,6 +1034,10 @@ impl<'a> Writer<'a> { Some((id, _)) if *id == n.id => self.root_entries.take().map(|(_, e)| e), _ => None, }; + let entries = match &self.instance_entries { + Some((id, _)) if *id == n.id => entries.or_else(|| self.instance_entries.take().map(|(_, e)| e)), + _ => entries, + }; let role = match &self.blend_role { Some((id, _)) if *id == n.id => self.blend_role.take().map(|(_, e)| e), _ => None, diff --git a/crates/eps/src/ai_editing/writer/symbols.rs b/crates/eps/src/ai_editing/writer/symbols.rs index 4d4bb2acba..a616d748d1 100644 --- a/crates/eps/src/ai_editing/writer/symbols.rs +++ b/crates/eps/src/ai_editing/writer/symbols.rs @@ -14,7 +14,27 @@ use crate::ps; pub(in crate::ai_editing) const SYMBOL_ART: &str = "symbol instances with a fill, appearance changes, isolation, knockout or knockout shape of their own, instances of symbols with 9-slice guides or pattern paint, instances in pattern tiles or in art cut to a clipping object, instances scaled almost flat, instances that turn, mirror or scale symbols holding type, live objects, instances written as their art, shapes with rounded live corners or strokes written as outlines or brush art, instances that scale their symbol more than 100 times, instances on the layers of a large canvas and instances of symbols past 4,096 are written as their art in the editing data for other apps"; pub(in crate::ai_editing) const SYMBOL_OPTIONS: &str = - "the 9-slice guides, export types and dynamic type of symbols are left out of the editing data for other apps"; + "the 9-slice guides and export types of symbols are left out of the editing data for other apps"; +pub(in crate::ai_editing) const SYMBOL_CHANGES: &str = + "the changes of dynamic symbol instances are kept in dictionary entries of their own, which other apps leave out"; +pub(crate) const DYNAMIC_KEY: &str = "VectorCraftDynamicSymbol"; +pub(crate) const OVERRIDES_KEY: &str = "VectorCraftSymbolOverrides"; +const MAX_OVERRIDES_BYTES: usize = 1 << 20; + +pub(crate) fn hex_decode(s: &str) -> Option> { + if !s.len().is_multiple_of(2) || s.len() / 2 > MAX_OVERRIDES_BYTES { + return None; + } + s.as_bytes().chunks(2).map(|c| u8::from_str_radix(std::str::from_utf8(c).ok()?, 16).ok()).collect() +} + +fn hex_encode(b: &[u8]) -> String { + b.iter().fold(String::with_capacity(b.len() * 2), |mut s, v| { + let _ = write!(s, "{v:02x}"); + s + }) +} + pub(in crate::ai_editing) const MISSING_SYMBOL: &str = "symbol instances of symbols the document doesn't have are written as empty groups in the editing data for other apps"; /// The most an instance may scale its symbol's art, nested instances' scales included: the art's @@ -55,7 +75,8 @@ impl Writer<'_> { /// that keeps the art's area as it is written and scales it as the definition allows /// ([`Self::keeps_scale`]). pub(super) fn live_instance(&mut self, n: &Node, symbol: &str, xf: Affine) -> bool { - let own = vectorcraft_brush::stain(n).is_some() || !n.extras().symbol_overrides.is_empty(); + let dynamic = self.symbol_doc.symbols.iter().any(|s| s.name == symbol && s.dynamic); + let own = vectorcraft_brush::stain(n).is_some() || (!dynamic && !n.extras().symbol_overrides.is_empty()); let group_state = n.isolate || n.knockout != Knockout::Neutral || n.knockout_shape; // The matrix as written (to ten decimals) must still keep the art's area. let m = Affine::new((self.instance_space * xf).as_coeffs().map(|v| (v * 1e10).round() / 1e10)); @@ -153,7 +174,16 @@ impl Writer<'_> { /// canvas's space turned y up about art space's origin there) as `a b c d tx ty /// /RTransformMatrix` (to ten decimals), `;`, then its state block as a group's: `Xy`, `0 0 Xd` /// and `6 () XW` when it has transparency, else `9 () XW`. Its dictionary goes between the two. - pub(super) fn symbol_instance(&mut self, symbol: &str, xf: Affine, xy: Xy) { + pub(super) fn symbol_instance(&mut self, n: &Node, symbol: &str, xf: Affine, xy: Xy) { + let o = &n.extras().symbol_overrides; + if !o.is_empty() + && let Ok(json) = serde_json::to_vec(o) + && json.len() <= MAX_OVERRIDES_BYTES + { + let e = format!("%_{} /String ({OVERRIDES_KEY}) ,\n", ps::bytes(hex_encode(&json).as_bytes())); + self.instance_entries = Some((n.id, e)); + self.warn(SYMBOL_CHANGES); + } let m = self.instance_space * xf; let _ = write!(self.body, "/SymbolInstance :\n{} /SymbolRef ,\n", ps::bytes(symbol.as_bytes())); for v in m.as_coeffs() { @@ -201,7 +231,7 @@ impl Writer<'_> { self.warn(SYMBOL_COUNT); return false; } - if sym.dynamic || doc.symbol_export_type(name) != SymbolExportType::default() || doc.symbol_nine_slice(name).is_some() { + if doc.symbol_export_type(name) != SymbolExportType::default() || doc.symbol_nine_slice(name).is_some() { self.warn(SYMBOL_OPTIONS); } // The art's effects are its own, not those of a drawn look that first places it, and its @@ -260,7 +290,10 @@ impl Writer<'_> { (self.to_art, self.grad_space, self.canvas, self.instance_space) = (Affine::IDENTITY, about_origin, Affine::IDENTITY, about_origin); self.block_end = usize::MAX; let registration = u16::from(doc.symbol_registration(name).0.min(8)) + 1; - let entries = format!("%_{registration} /Int (AI13PatternRegistrationType) ,\n"); + let mut entries = format!("%_{registration} /Int (AI13PatternRegistrationType) ,\n"); + if sym.dynamic { + let _ = writeln!(entries, "%_1 /Int ({DYNAMIC_KEY}) ,"); + } // The canvas draws a symbol's art even when its root is hidden, so the root is written shown. let shown; let root: &Node = if sym.art.visible { diff --git a/crates/eps/src/import/ai/read/directives.rs b/crates/eps/src/import/ai/read/directives.rs index 55adb56a7c..4c5b48c04d 100644 --- a/crates/eps/src/import/ai/read/directives.rs +++ b/crates/eps/src/import/ai/read/directives.rs @@ -627,7 +627,7 @@ impl<'a> Reader<'a> { || sub.mesh.is_some() || sub.gradient_def.is_some(); let head = sub.symbol.take().unwrap_or_default(); - let registration = head.registration; + let (registration, dynamic) = (head.registration, head.dynamic); let measured = read.is_ok() && !open && sub.unsupported.is_empty() && sub.unknown.is_empty() && sub.frames.len() == 1; let Some(frame) = sub.frames.pop().filter(|_| measured) else { return }; let mut kids = frame.children; @@ -669,7 +669,7 @@ impl<'a> Reader<'a> { } } let named = self.unique_symbol_name(if name.is_empty() { "Symbol" } else { &name }); - self.doc.symbols.push(Symbol { name: named.clone(), art: Arc::new(art), dynamic: false }); + self.doc.symbols.push(Symbol { name: named.clone(), art: Arc::new(art), dynamic }); if let Some(reg) = registration.and_then(symbol_registration) { self.doc.set_symbol_registration(&named, reg); } diff --git a/crates/eps/src/import/ai/read/document.rs b/crates/eps/src/import/ai/read/document.rs index 29463daa85..ae2772a3c9 100644 --- a/crates/eps/src/import/ai/read/document.rs +++ b/crates/eps/src/import/ai/read/document.rs @@ -783,6 +783,19 @@ impl<'a> Reader<'a> { { head.registration = Some(*r); } + if self.frames.len() == 1 + && let Some(head) = self.symbol.as_mut() + && o.nums(crate::ai_editing::DYNAMIC_KEY).first().is_some_and(|v| *v != 0.0) + { + head.dynamic = true; + } + if let Some(text) = o.text(crate::ai_editing::OVERRIDES_KEY) + && let Some(bytes) = crate::ai_editing::hex_decode(&text) + && let Ok(list) = serde_json::from_slice::>(&bytes) + && let Some(n) = self.last_object().filter(|n| matches!(n.kind, NodeKind::SymbolInstance { .. })) + { + n.extras_mut().symbol_overrides = list.into_iter().filter(|s| !s.is_empty()).collect(); + } self.constraint_art(o); self.placed_page(o); // A blend's key object or spine. diff --git a/crates/eps/src/import/ai/read/types.rs b/crates/eps/src/import/ai/read/types.rs index 02d4a3354a..a155d9f505 100644 --- a/crates/eps/src/import/ai/read/types.rs +++ b/crates/eps/src/import/ai/read/types.rs @@ -244,6 +244,7 @@ pub(super) struct PatternHead { pub(super) struct SymbolHead { /// `AI13PatternRegistrationType` in the dictionary after the art. pub(super) registration: Option, + pub(super) dynamic: bool, /// Art the reader left out (type, a placed file, non-native art, an image it can't read or /// place, a gradient it can't read): the symbol isn't kept, and its instances come in as the /// page draws them, within the box of the rest. diff --git a/crates/eps/src/legacy_ai.rs b/crates/eps/src/legacy_ai.rs index ea569c94a5..d1ae8ef9ab 100644 --- a/crates/eps/src/legacy_ai.rs +++ b/crates/eps/src/legacy_ai.rs @@ -128,7 +128,9 @@ const CONIC_WEDGES: usize = 360; const STROKES: &str = "strokes a plain line can't draw (inside or outside the path, variable width, gradients, brushes, arrowheads) are written as filled outlines"; const IMAGE_ALPHA: &str = "transparent image pixels are written over white"; -const LIVE: &str = "symbols, blends, envelopes, meshes, repeats, placed documents and intertwines are written as their art"; +const LIVE: &str = "symbols, blends, envelopes, meshes, repeats, placed documents, intertwines and distorted images are written as their art"; +const DEEP_DISTORTED: &str = + "images changed by Perspective Distort or Free Distort more than 8 deep in symbols and live objects are written as the nearest parallelogram"; const GRAPHS: &str = "graphs are written as their art, without their data or settings"; /// The warning for an image left out because it can't be decoded: the note raster exports give /// (`vectorcraft-engine`'s `rasterfx::undecoded_warning`). diff --git a/crates/eps/src/legacy_ai/tests.rs b/crates/eps/src/legacy_ai/tests.rs index 108c90c2fc..6018bc6920 100644 --- a/crates/eps/src/legacy_ai/tests.rs +++ b/crates/eps/src/legacy_ai/tests.rs @@ -703,6 +703,25 @@ fn picture(doc: &mut Document, r: Rect) -> Node { ) } +/// A distorted image as deep as the writer goes, the art of the innermost of 8 nested symbols, is +/// written as one image at the placement nearest its corners, with a warning, not left out. +#[test] +fn a_distorted_image_nested_as_deep_as_the_limit_is_written_as_its_nearest_placement() { + let mut doc = Document::new(200.0, 100.0); + let mut art = picture(&mut doc, Rect::new(10.0, 10.0, 90.0, 90.0)); + art.set_image_corners([(40.0, 10.0), (60.0, 10.0), (90.0, 90.0), (10.0, 90.0)].map(|(x, y)| vectorcraft_geom::Point::new(x, y))).unwrap(); + for i in 0..8 { + let name = format!("S{i}"); + doc.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: name.clone(), art: Arc::new(art) }); + art = Node::new(doc.alloc_id(), NodeKind::SymbolInstance { symbol: name, xf: Affine::IDENTITY }); + } + doc.insert(doc.default_layer(), usize::MAX, art).unwrap(); + let out = write(&doc); + assert!(out.warnings.iter().any(|w| w == DEEP_DISTORTED), "{:?}", out.warnings); + let text = String::from_utf8(out.bytes).unwrap(); + assert_eq!(text.lines().filter(|l| l.ends_with(" XI")).count(), 1, "the one image"); +} + /// A layer `Below` holding a clipping group (a circle clipping an image, as in #2692), a group /// holding an image and an image; a layer `Above` holding an orange square. Without `images`, /// `Below` is empty. diff --git a/crates/eps/src/legacy_ai/writer.rs b/crates/eps/src/legacy_ai/writer.rs index 2e5510d3d0..7e7dbfe4fc 100644 --- a/crates/eps/src/legacy_ai/writer.rs +++ b/crates/eps/src/legacy_ai/writer.rs @@ -9,7 +9,7 @@ use super::{ ROTATED_TYPE, Rect, STROKES, SUBLAYERS, Shape, StrokeLayer, SubPath, TITLE_AND_COLOR_NAMES, TRANSPARENCY, TYPE, TYPE_ATTRIBUTES, TextKind, TextObject, UNDECODED, Vec2, Write, ai_ops, latin, ps, stroke, }; -use super::{CONIC, CONIC_WEDGES, DIAMOND, GRAPHS, HUE_STOPS, PERCEPTUAL_STOPS, SPREAD, SPREAD_CAPPED}; +use super::{CONIC, CONIC_WEDGES, DEEP_DISTORTED, DIAMOND, GRAPHS, HUE_STOPS, PERCEPTUAL_STOPS, SPREAD, SPREAD_CAPPED}; #[cfg(test)] thread_local! { @@ -322,14 +322,23 @@ impl<'a> Writer<'a> { self.lock(locked); self.text(t); } - NodeKind::Image(im) => { + // A distorted image too deep for its pieces is written at the placement nearest its + // corners. + NodeKind::Image(im) if !n.is_distorted_image() || self.nest >= MAX_NEST => { self.lock(locked); let shown = self.doc.shown_image(n, im); let blob = self.doc.image_blob(&shown); // A colorize color the renderer draws the image in. let colorize = n.extras().colorize.as_deref().filter(|p| matches!(p, Paint::Solid { .. }) && blob.is_some_and(ImageBlob::takes_colorize)); - self.image(blob, im.width, im.height, im.xf, colorize); + let xf = match vectorcraft_doc::image_quad::nearest_affine(n) { + Some(near) => { + self.warn(DEEP_DISTORTED); + near + } + None => im.xf, + }; + self.image(blob, im.width, im.height, xf, colorize); } NodeKind::SymbolInstance { symbol, xf } => { self.warn(LIVE); @@ -348,7 +357,8 @@ impl<'a> Writer<'a> { | NodeKind::Mesh(_) | NodeKind::Repeat(_) | NodeKind::PlacedDocument(_) - | NodeKind::Intertwine { .. } => { + | NodeKind::Intertwine { .. } + | NodeKind::Image(_) => { self.warn(LIVE); if self.nest < MAX_NEST { let g = vectorcraft_effects::expand_live_deep(Some(self.doc), n); diff --git a/crates/eps/src/scene.rs b/crates/eps/src/scene.rs index c715d817ec..349bc2a16b 100644 --- a/crates/eps/src/scene.rs +++ b/crates/eps/src/scene.rs @@ -585,7 +585,7 @@ impl<'a> Scene<'a> { self.shape(n, &bp, *rule); } NodeKind::Text(t) => self.text(n, t), - NodeKind::Image(im) => { + NodeKind::Image(im) if !n.is_distorted_image() => { let shown = self.doc.shown_image(n, im); let im = &*shown; let blob = self.doc.image_blob(im); @@ -606,13 +606,15 @@ impl<'a> Scene<'a> { self.nest -= 1; } } - // Live blends, envelopes, meshes and repeats are written as their evaluated art. + // Live blends, envelopes, meshes and repeats (and distorted images) are written as + // their evaluated art. NodeKind::Blend { .. } | NodeKind::Envelope { .. } | NodeKind::Mesh(_) | NodeKind::Repeat(_) | NodeKind::PlacedDocument(_) - | NodeKind::Intertwine { .. } => { + | NodeKind::Intertwine { .. } + | NodeKind::Image(_) => { let g = vectorcraft_effects::expand_live_deep(Some(self.doc), n); for c in g.children().into_iter().flatten() { self.node(c, false); diff --git a/crates/eps/src/tests.rs b/crates/eps/src/tests.rs index 60b5832859..0b92c6f8a6 100644 --- a/crates/eps/src/tests.rs +++ b/crates/eps/src/tests.rs @@ -1255,6 +1255,50 @@ fn an_envelopes_image_pieces_draw_one_copy_of_its_samples() { } } +/// An image changed by Perspective Distort is written as the pieces of its mesh, placed so that +/// its pixel rectangle's corners land on its corners: read back, each corner of the quad is a +/// corner of one of the pieces' images. +#[test] +fn a_distorted_image_is_written_with_its_corners_on_its_quad() { + let mut d = png_doc(); + let id = d.layers[0].children().unwrap()[0].id; + let q = [(40.0, 10.0), (60.0, 10.0), (90.0, 90.0), (10.0, 90.0)].map(|(x, y)| Point::new(x, y)); + d.node_mut(id).unwrap().set_image_corners(q).unwrap(); + for level in Level::ALL { + let out = export(&d, &EpsOptions { level, ..opts(&d) }, None, None).unwrap(); + let back = import::import(&out.bytes).unwrap().document; + let (mut seen, mut pieces) = ([false; 4], 0); + back.walk(|n| { + if let NodeKind::Image(im) = &n.kind { + pieces += 1; + let (w, h) = (f64::from(im.width), f64::from(im.height)); + for p in [(0.0, 0.0), (w, 0.0), (w, h), (0.0, h)] { + let at = im.xf * Point::new(p.0, p.1); + for (i, c) in q.iter().enumerate() { + seen[i] |= at.distance(*c) < 0.01; + } + } + } + }); + assert!(pieces > 2, "{level:?}: {pieces}"); + assert_eq!(seen, [true; 4], "{level:?}"); + // The pieces are clipped by the quad: a clipping path with its bounds and its area. + let mut quad_clips = 0; + back.walk(|n| { + if let NodeKind::Group { children, clip: true } = &n.kind + && let Some(p) = children.first().and_then(|c| c.path_data()) + && let Some(b) = p.bounds() + { + let area: f64 = p.subpaths.iter().map(|s| s.area()).sum::().abs(); + if [b.x0 - 10.0, b.y0 - 10.0, b.x1 - 90.0, b.y1 - 90.0].iter().all(|v| v.abs() < 0.01) && (area - 4000.0).abs() < 1.0 { + quad_clips += 1; + } + } + }); + assert!(quad_clips >= 1, "{level:?}: no clipping path on the quad"); + } +} + #[test] fn each_ink_of_a_colorized_image_placed_twice_is_written_once() { let first = Paint::Solid { color: Color::rgb8(255, 0, 0), swatch: Some("Ink".into()), tint: 1.0 }; diff --git a/crates/geom/src/shapes.rs b/crates/geom/src/shapes.rs index 1cb52b4559..f3ab848e81 100644 --- a/crates/geom/src/shapes.rs +++ b/crates/geom/src/shapes.rs @@ -367,6 +367,61 @@ pub fn circle_through_points(points: &[Point]) -> Option<(Point, f64)> { circle.filter(|(c, r)| c.is_finite() && r.is_finite() && *r > 0.0) } +/// The circle at `center` with `radius` as a closed path whose anchors are `points` (points on the +/// circle, as [`circle_through_points`] gives it) plus as many more as split each arc between two +/// of them into equal parts of at most a quarter turn. The path starts at the first point and runs +/// as [`ellipse`] does (left, top, right on the page); each curve's handles are 4/3·tan(θ/4) of +/// the radius along the tangents at its ends (θ, its turn). Two points with `center` at their +/// midpoint give four anchors. A point given twice is one anchor; with no points it starts at the +/// left, as [`ellipse`] does. +pub fn circle_with_anchors_at(center: Point, radius: f64, points: &[Point]) -> PathData { + let quarter = PI / 2.0; + let angle = |p: Point| (p.y - center.y).atan2(p.x - center.x); + let start = points.first().map_or(PI, |p| angle(*p)); + // (turn from the first point, the point itself). + let mut placed: Vec<(f64, Point)> = points.iter().map(|p| ((angle(*p) - start).rem_euclid(TAU), *p)).collect(); + placed.sort_by(|a, b| a.0.total_cmp(&b.0)); + placed.dedup_by(|a, b| a.1 == b.1); + // Two points with the center at their midpoint are the ends of a diameter: the second is half a + // turn from the first, also where rounding moves the angle from the center off it. + if let [(_, a), (turn, b)] = placed.as_mut_slice() + && a.midpoint(*b) == center + { + *turn = PI; + } + if placed.is_empty() { + placed.push((0.0, Point::new(center.x - radius, center.y))); + } + let on_circle = |t: f64| Point::new(center.x + radius * (start + t).cos(), center.y + radius * (start + t).sin()); + // Every anchor: (turn, position), the given points where they are and the others on the circle. + let mut turns: Vec<(f64, Point)> = Vec::new(); + for (i, &(t, p)) in placed.iter().enumerate() { + turns.push((t, p)); + let next = placed.get(i + 1).map_or(TAU, |n| n.0); + let gap = next - t; + // At most 4 parts for the whole turn: a gap is never more than a full turn. + let parts = (gap / quarter - 1e-9).ceil().clamp(1.0, 4.0); + for k in 1..parts as u32 { + let tk = t + gap * f64::from(k) / parts; + turns.push((tk, on_circle(tk))); + } + } + let n = turns.len(); + let anchors = (0..n) + .filter_map(|i| { + let &(t, p) = turns.get(i)?; + let prev = if i == 0 { turns.last()?.0 - TAU } else { turns.get(i - 1)?.0 }; + let next = turns.get(i + 1).map_or(TAU, |n| n.0); + // The unit tangent along the run (y down: increasing angle). + let a = start + t; + let tangent = Vec2::new(-a.sin(), a.cos()); + let handle = |turn: f64| radius * 4.0 / 3.0 * (turn / 4.0).tan(); + Some(Anchor { p, h_in: p - tangent * handle(t - prev), h_out: p + tangent * handle(next - t), kind: AnchorKind::Smooth }) + }) + .collect(); + PathData::single(SubPath::new(anchors, true)) +} + /// Regular polygon with `sides` (≥ 3), first vertex straight up from the centre. pub fn polygon(center: Point, radius: f64, sides: u32, rotation_deg: f64) -> PathData { let n = sides.max(3); @@ -1146,6 +1201,53 @@ mod tests { } } + /// The anchors are the given points exactly, plus enough more that no curve turns more than a + /// quarter; every anchor and every curve's middle lies on the circle, and the path starts at + /// the first point. + #[test] + fn a_circle_with_its_anchors_at_given_points() { + use kurbo::ParamCurve; + let (a, b, c) = (Point::new(8.0, 0.0), Point::new(0.0, 6.0), Point::ORIGIN); + let center = Point::new(4.0, 3.0); + for (points, count) in [(&[a, b][..], 4), (&[a, b, c][..], 5), (&[b, a, c, b][..], 5), (&[][..], 4)] { + let path = circle_with_anchors_at(center, 5.0, points); + let sub = &path.subpaths[0]; + assert!(sub.closed, "{points:?}"); + assert_eq!(sub.anchors.len(), count, "{points:?}: {sub:?}"); + for p in points { + assert!(sub.anchors.iter().any(|q| q.p == *p), "{p:?} is an anchor: {sub:?}"); + } + if let Some(first) = points.first() { + assert_eq!(sub.anchors[0].p, *first); + } + for q in &sub.anchors { + assert!((q.p.distance(center) - 5.0).abs() < 1e-9, "{q:?}"); + } + for seg in path.to_bezpath().segments() { + let turn = { + let (p0, p1) = (seg.start() - center, seg.end() - center); + p0.cross(p1).atan2(p0.dot(p1)) + }; + assert!(turn > 0.0 && turn <= PI / 2.0 + 1e-9, "{turn} for {seg:?}"); + assert!((seg.eval(0.5).distance(center) - 5.0).abs() < 5.0 * 1e-3, "{seg:?}"); + } + } + } + + /// The two ends of a diameter give four anchors, also where the midpoint rounds off it: at + /// x = 10⁶, steps of 2⁻³³ put the second point more than half a turn from the first, seen from + /// the rounded center. + #[test] + fn a_diameter_gives_four_anchors_where_its_midpoint_rounds() { + let u = 2f64.powi(-33); + let (a, b) = (Point::new(1_000_000.0, 0.0), Point::new(1_000_000.0 + 9.0 * u, 8.0 * u)); + let (center, radius) = circle_through_points(&[a, b]).expect("a circle"); + let path = circle_with_anchors_at(center, radius, &[a, b]); + let sub = &path.subpaths[0]; + assert_eq!(sub.anchors.len(), 4, "{sub:?}"); + assert_eq!((sub.anchors[0].p, sub.anchors[2].p), (a, b)); + } + /// Nearly on one line: a point 10⁻⁴ off a chord 2000 long still gives the circle (its sagitta /// formula `r = (h² + (L/2)²) / 2h`), and its center sits on the chord's perpendicular /// bisector; a point 10⁻¹² off it does not. diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 3106120489..64c57a6798 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -687,6 +687,37 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "{pinned?: bool} keep the Contextual Task Bar where it is instead of following the selection (true), let it follow the selection again from where it is (false) or toggle (omitted), as the bar's More Options menu does; returns the new state", ), ("window.taskBar.reset", "Reset Bar Position", "", "{} unpin the Contextual Task Bar and put it back under the selection"), + ( + "window.taskBar.actions", + "Bar Actions", + "", + "{action: \"imageTrace\"|\"cropImage\"|\"removeBackground\"|\"removeAnchorPoints\"|\"join\"|\"cutPath\"|\"convertToCorner\"|\"convertToSmooth\"|\"group\"|\"makeClippingMask\"|\"unite\"|\"expand\"|\"editClippingPath\"|\"releaseClippingMask\"|\"ungroup\"|\"isolate\"|\"editPath\"|\"releaseCompoundPath\"|\"createOutlines\"|\"convertToPointType\"|\"convertToAreaType\"|\"typeOnPathOptions\"|\"centerOnTop\"|\"centerOnBottom\"|\"dynamicText\"|\"offsetPath\"|\"simplify\"|\"smooth\"|\"duplicate\"|\"drawPencil\"|\"placeImage\"|\"fidelity\"|\"smoothToolOptions\"|\"resizeArtboard\"|\"duplicateArtboards\"|\"rearrangeArtboards\"|\"exportArtboards\"|\"fill\"|\"stroke\"|\"recolor\"|\"lock\"|\"shapeProperties\", visible?: bool} show (true), hide (false) or toggle (omitted or null) one of the Contextual Task Bar's actions or chips, as the bar's More Options › Bar Actions does; an action that is off stays out of the bar and out of More Options, and turning one off changes only the bar; `join` is both Connect and Join; every action starts on; kept with the preferences and with the workspace; another action, or a `visible` that is not true, false or null, is an error and changes nothing; returns {action, visible}", + ), + ( + "window.taskBar.resetActions", + "Reset Bar Actions", + "", + "{} show every Contextual Task Bar action and chip that Bar Actions turned off, as the bar's More Options › Reset Bar Actions does; returns the ids shown again", + ), + ( + "window.quickPenToolbar", + "Quick Pen Toolbar", + "", + "{} show or hide the toolbar the Quick Pen tool shows on the canvas (toggles; returns whether it shows), as Window › Quick Pen Toolbar and the toolbar's More Options › Hide Toolbar do; selecting the Quick Pen tool shows it again", + ), + ( + "window.quickPenToolbar.pin", + "Pin Toolbar Position", + "", + "{pinned?: bool} keep the Quick Pen toolbar where it is in the canvas window instead of following the drawing (true), let it follow the drawing again from where it is (false) or toggle (omitted), as the toolbar's More Options menu does; returns the new state", + ), + ("window.quickPenToolbar.reset", "Reset Toolbar Position", "", "{} unpin the Quick Pen toolbar and put it back beside the drawing"), + ( + "tool.quickPen.flipArc", + "Flip Arc", + "", + "{} flip the last sharp-corner arc of the path the Quick Pen tool is drawing to the other side of its chord, as C and the toolbar's Flip Arc button do, as one undo step; first finishes any pending tool edit (which can change the document), then returns false, changing nothing more, when the Quick Pen tool is not active, no path is being drawn or the last piece is not a sharp-corner arc", + ), ( "window.dock", "Panels", @@ -1000,6 +1031,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ ("help.about", "About VectorCraft", "", "{}"), ("help.checkForUpdates", "Check for Updates…", "", "{}"), ("help.commandPalette", "Search Commands…", "Cmd+Shift+/", "{}"), + ( + "help.clearRecentCommands", + "Clear Recent Commands", + "", + "{} empty the recent picks of Help › Search Commands (the list an empty search shows and the Recent Commands list), the saved list and the pick counts that rank the results; a pick of it is not kept as a recent pick or counted. Not enabled while no picks or counts are saved", + ), ( "help.discover", "VectorCraft Help…", @@ -1138,7 +1175,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "tool.options", "Tool Options…", "", - "{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview; with flares selected, the fields show the first one's settings, `flares` lists them and OK runs shape.editFlare with the settings changed instead, leaving the tool's options), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront, filledLines and lineWidth held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool (the tool whose options show; the Tool row changes it), diameter (pt), intensity and density (1–10), usePressure, method: userDefined|average|random (not used by the Sprayer and the Shifter), showBrush, sprayScrunch, spraySize, spraySpin, sprayScreen, sprayStain and sprayStyle: average|userDefined (the Symbol Sprayer's), proportional and affectsDensity (the Symbol Sizer's), shared by the eight tools; OK runs tool.setOption {tool, values}, after symbol.setDensity from the density the dialog opened with to the new one when symbol sets are selected and it changed), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (px for pencil, paintbrush and smooth, the same at any zoom; pt for blobBrush), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is drawn, and the path's fill and stroke on release), size (pt), angle (°, −180–180; 0) and roundness (%, 1–100; 100) of the eraser's tip; OK runs tool.setOption {tool, values}), livePaintSelection → Live Paint Selection Tool Options (dialog `livePaintSelectionOptions`, fields selectFills and selectStrokes (both on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the highlight's width, 1–20 px; 4); OK runs tool.setOption {tool: \"livePaintSelection\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), livePaintBucket → Live Paint Bucket Options (dialog `livePaintBucketOptions`, fields paintFills (on) and paintStrokes (off), cursorSwatchPreview (on: the active fill or stroke shows above the pointer between the color swatches before and after it; Left and Right without modifiers step it through the color swatches whether it is on or off), highlight (on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the face highlight's width, 1–20 px; 4; an edge's highlight is half as wide); OK runs tool.setOption {tool: \"livePaintBucket\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), shapeBuilder → Shape Builder Tool Options (dialog `shapeBuilderOptions`, fields gapDetection (off), gapLength (pt, 0–72; 3), openFilledAsClosed (on), clickStrokeSplitsPath (off), pickColorFrom: artwork|swatches (artwork), cursorSwatchPreview (off), selection: freeform|straightLine (freeform), highlightFill (on), highlightStroke (on), highlightColor (#rrggbb or a layer color's name; #ff4f4f); OK runs tool.setOption {tool: \"shapeBuilder\", values}; a highlightColor with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), objectsOnPath → Objects on Path Tool Options (dialog `objectsOnPathOptions`, fields pivot (0–8, row by row from the top left; 4, the center) and rotate (°, −360–360; 0); Reset puts 4 and 0 back; Save runs tool.setOption {tool: \"objectsOnPath\", values}: the objects attached next use them, groups attached before keep theirs)", + "{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview; with flares selected, the fields show the first one's settings, `flares` lists them and OK runs shape.editFlare with the settings changed instead, leaving the tool's options), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), circle → Circle Tool Options (dialog `circleOptions`, fields center, radii, diameter (all on), color (red|blue|magenta|green|black|gray; blue), standardAnchors (on) and dragThird (on); OK runs tool.setOption {tool: \"circle\", values}), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront, filledLines and lineWidth held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool (the tool whose options show; the Tool row changes it), diameter (pt), intensity and density (1–10), usePressure, method: userDefined|average|random (not used by the Sprayer and the Shifter), showBrush, sprayScrunch, spraySize, spraySpin, sprayScreen, sprayStain and sprayStyle: average|userDefined (the Symbol Sprayer's), proportional and affectsDensity (the Symbol Sizer's), shared by the eight tools; OK runs tool.setOption {tool, values}, after symbol.setDensity from the density the dialog opened with to the new one when symbol sets are selected and it changed), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (px for pencil, paintbrush and smooth, the same at any zoom; pt for blobBrush), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is drawn, and the path's fill and stroke on release), size (pt), angle (°, −180–180; 0) and roundness (%, 1–100; 100) of the eraser's tip; OK runs tool.setOption {tool, values}), livePaintSelection → Live Paint Selection Tool Options (dialog `livePaintSelectionOptions`, fields selectFills and selectStrokes (both on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the highlight's width, 1–20 px; 4); OK runs tool.setOption {tool: \"livePaintSelection\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), livePaintBucket → Live Paint Bucket Options (dialog `livePaintBucketOptions`, fields paintFills (on) and paintStrokes (off), cursorSwatchPreview (on: the active fill or stroke shows above the pointer between the color swatches before and after it; Left and Right without modifiers step it through the color swatches whether it is on or off), highlight (on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the face highlight's width, 1–20 px; 4; an edge's highlight is half as wide); OK runs tool.setOption {tool: \"livePaintBucket\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), shapeBuilder → Shape Builder Tool Options (dialog `shapeBuilderOptions`, fields gapDetection (off), gapLength (pt, 0–72; 3), openFilledAsClosed (on), clickStrokeSplitsPath (off), pickColorFrom: artwork|swatches (artwork), cursorSwatchPreview (off), selection: freeform|straightLine (freeform), highlightFill (on), highlightStroke (on), highlightColor (#rrggbb or a layer color's name; #ff4f4f); OK runs tool.setOption {tool: \"shapeBuilder\", values}; a highlightColor with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), objectsOnPath → Objects on Path Tool Options (dialog `objectsOnPathOptions`, fields pivot (0–8, row by row from the top left; 4, the center) and rotate (°, −360–360; 0); Reset puts 4 and 0 back; Save runs tool.setOption {tool: \"objectsOnPath\", values}: the objects attached next use them, groups attached before keep theirs)", ), ( "ui.colorGuideOptions", @@ -1312,6 +1349,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{params?: tracing settings (default: the Default preset's), rename?: a saved preset's name} the Image Trace panel's Manage Presets: open Save as New Preset… for those settings, or with `rename`, Rename… for that saved preset (dialog `imageTracePreset`, field `name`: a new \"Tracing Preset N\" or the preset's name); OK runs imageTrace.presets.save with the name (as `newName` when renaming), and the panel shows the preset it made from its settings", ), + ( + "ui.tracingPresetsDialog", + "Tracing Presets…", + "", + "{selected?: preset name (default Default)} open Edit → Tracing Presets (dialog `tracingPresets`, field `selected`): the built-in presets (in brackets, read-only) and the saved ones, with the selected one's settings. New… (from the selected preset) and Edit… (a saved one) open the preset editor (dialog `tracingPreset`, fields `name` and `params`, the tracing settings): OK runs imageTrace.presets.save and returns to Tracing Presets, and a name of a built-in preset, Custom or another saved preset keeps the editor open; Cancel returns with nothing saved. Delete runs imageTrace.presets.delete; Import… runs imageTrace.presets.import, and when saved presets have names in the file, asks (dialog `tracingPresetsReplace`) whether to replace them (OK) or keep them (Cancel); Export… runs imageTrace.presets.export on every saved preset", + ), ( "ui.flattenerPreview", "Flattener Preview", @@ -1561,7 +1604,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.colorWheel", "Color Wheel Options", "", - "{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, harmony?: bool, harmonyRule?: complementary|splitComplementary|leftComplement|rightComplement|analogous|analogous2|triad|tetrad|tetrad2|tetrad3|compound|compound2|highContrast|highContrast3|pentagram, vision?: bool} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, and pick the box's channel, as Box Channel does: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); harmony shows a marker on the wheel's ring for each other color of harmonyRule (the Color Guide's rule of that id; a rule's label is taken too), as Show Harmony and Harmony Rule do, and a click on a marker applies its color; vision shows Show Color Vision Preview's row under the wheel or the box, four chips with the current color as simulated for protanopia, deuteranopia and tritanopia (the simulations of view.proofSetup's protanopia, deuteranopia and tritanopia targets) and for achromatopsia (the gray with the color's CIE L*), each named with its hex value in its tooltip and to screen readers, and taking the keyboard focus; a click or a key on a chip does not apply its color; keys left out or null keep their values ({} reads them), params that are not an object, another key or a value off the list are an error and change nothing, the settings are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel, harmony, harmonyRule, vision}", + "{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, sliders?: none|oklch|hsl, gamut?: bool, harmony?: bool, harmonyRule?: complementary|splitComplementary|leftComplement|rightComplement|analogous|analogous2|triad|tetrad|tetrad2|tetrad3|compound|compound2|highContrast|highContrast3|pentagram, vision?: bool, documentColors?: bool} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, pick the box's channel, as Box Channel does, and show no slider rows under the wheel or the box (none), OKLCH Sliders (oklch) or HSL Sliders (hsl), as the menu items of those names do: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); OKLCH Sliders edit lightness 0 to 100 %, chroma 0 to 100 % of 0.4 and hue 0 to 360°, CSS Color 4's OKLCH of the display sRGB, and a color outside sRGB keeps L and H and takes the largest chroma that fits; HSL Sliders edit hue 0 to 360°, saturation 0 to 100 % and lightness 0 to 100 %, CSS Color 4's HSL of the display sRGB; gamut true grays out the parts of the wheel's square and the box's field whose colors the CMYK space cannot print (the out-of-gamut warning's test, as color.gamutCheck answers it), as Show Out-of-Gamut Colors does, and false shows them again; the shading is approximate: each cell of a 16 by 16 grid over the square or the field is grayed out or not by the color at its center, so a grayed cell can hold printable colors and a clear cell can hold colors that cannot print; harmony shows a marker on the wheel's ring for each other color of harmonyRule (the Color Guide's rule of that id; a rule's label is taken too), as Show Harmony and Harmony Rule do, and a click on a marker applies its color; vision shows Show Color Vision Preview's row under the wheel or the box, four chips with the current color as simulated for protanopia, deuteranopia and tritanopia (the simulations of view.proofSetup's protanopia, deuteranopia and tritanopia targets) and for achromatopsia (the gray with the color's CIE L*), each named with its hex value in its tooltip and to screen readers, and taking the keyboard focus; a click or a key on a chip does not apply its color; documentColors shows or hides the row the panel menu's Show Document Colors adds under the wheel or the box: the colors color.used {} lists, headed Selection Colors when something is selected and Document Colors otherwise, most used first and as many as fit in one row (a chip's tooltip gives its hex value and how many times the art uses it; a click applies it to the active proxy or to the selected gradient stop, keeping its color model and its link to a global swatch, or to the selected freeform point, which takes the color alone, and Alt+click applies it to the other proxy; the row reads the colors again when the document or the selection changes, not during a drag, and in art with more than 5,000 color uses at most once every half second after an edit); keys left out or null keep their values ({} reads them), params that are not an object, another key or a value off the list are an error and change nothing, oklch is an error while the working RGB space is not sRGB, the settings are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel, sliders, gamut, harmony, harmonyRule, vision, documentColors}", ), ( "ui.savePdfDialog", @@ -1889,7 +1932,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.hpglOptionsDialog", "HP-GL Options Dialog", "", - "{path?, useArtboards?, range?, hpglVersion?, curveTolerance?, origin?, pens?, sortPaths?, insideFirst?} open HP-GL Options (dialog `hpglOptions`: fields = these document.export options over the ones used last; pens null is One Pen per Color); OK checks them, remembers them and writes path (else asks). Export As… → HP-GL opens it too", + "{path?, useArtboards?, range?, hpglVersion?, curveTolerance?, origin?, pens?, sortPaths?, insideFirst?} open HP-GL Options (dialog `hpglOptions`: fields = these document.export options over the ones used last; pens null is One Pen per Color); OK checks them, remembers them and writes path (else asks); OK after another document has become active closes the dialog and writes nothing. Export As… → HP-GL opens it too", ), ( "file.saveForWeb", diff --git a/crates/metafile/src/scene.rs b/crates/metafile/src/scene.rs index 3e7f2024d5..a6c98889f6 100644 --- a/crates/metafile/src/scene.rs +++ b/crates/metafile/src/scene.rs @@ -31,6 +31,7 @@ const BLENDING: &str = "blending modes are left out"; const MASKS: &str = "opacity masks are left out"; const RASTER_FX: &str = "raster effects (shadows, glows, blurs, feathering) are left out"; const CLIPPING: &str = "clipping masks are not applied: the art they clip is written whole"; +const DISTORTED_IMAGES: &str = "images changed by Perspective Distort or Free Distort are written as the nearest parallelogram"; const FLAT_GRADIENTS: &str = "gradients are written as one colour, the average of their stops"; const FLAT_PATTERNS: &str = "pattern fills are written as one colour"; const TOO_MANY_TILES: &str = "pattern fills past 250,000 tiles in all are written as one colour"; @@ -134,6 +135,9 @@ pub(crate) struct Scene<'a> { /// Pattern tiles being written that may be merged: their parts aren't left out off the page, /// so each tile draws the same parts (the fill's clip still trims them). whole_tiles: bool, + /// While the pieces of a distorted image are written: the box of the clips around the current + /// object (`Some(None)` before the first), to which each piece's image is cropped. + crop: Option>, } impl<'a> Scene<'a> { @@ -151,6 +155,7 @@ impl<'a> Scene<'a> { nest: 0, tiles_left: MAX_TILES, whole_tiles: false, + crop: None, } } @@ -213,7 +218,24 @@ impl<'a> Scene<'a> { self.node(&o, true); } } - NodeKind::Image(im) => self.image(&self.doc.shown_image(n, im)), + NodeKind::Image(im) => match vectorcraft_doc::image_quad::nearest_affine(n) { + // A format that clips writes a distorted image as the pieces of its mesh; one that + // doesn't, at the affine placement nearest its corners. + // Each piece stores only the pixels inside its clips. + Some(_) if self.clips => { + let g = vectorcraft_effects::expand_live_deep(Some(self.doc), n); + let outer = self.crop.replace(None); + for c in g.children().into_iter().flatten() { + self.node(c, false); + } + self.crop = outer; + } + Some(xf) => { + self.warn(DISTORTED_IMAGES); + self.image(&ImageObject { xf, ..self.doc.shown_image(n, im).into_owned() }); + } + None => self.image(&self.doc.shown_image(n, im)), + }, NodeKind::SymbolInstance { symbol, xf } => { if let Some(sym) = self.doc.symbols.iter().find(|s| &s.name == symbol) && self.nest < MAX_NEST @@ -261,13 +283,19 @@ impl<'a> Scene<'a> { None }; let clipped = outline.is_some(); + let outer_crop = self.crop; if let Some((path, rule)) = outline { + if let Some(c) = self.crop { + let b = path.bounding_box(); + self.crop = Some(Some(c.map_or(b, |c| c.intersect(b)))); + } self.ops.push(Op::Clip { path, rule }); } if let Some(f) = &paint.fill { self.node(f, false); } rest.iter().for_each(|c| self.node(c, false)); + self.crop = outer_crop; if clipped { self.ops.push(Op::Unclip); } @@ -478,6 +506,13 @@ impl<'a> Scene<'a> { let Some(img) = self.decoded(im) else { return }; let (dw, dh) = (f64::from(img.width), f64::from(img.height)); let xf = im.xf * Affine::scale_non_uniform(f64::from(im.width.max(1)) / dw, f64::from(im.height.max(1)) / dh); + let (img, xf) = match self.crop.flatten() { + Some(c) => match cropped(&img, xf, c) { + Some((part, x0, y0)) => (Arc::new(part), xf * Affine::translate((f64::from(x0), f64::from(y0)))), + None => return, + }, + None => (img, xf), + }; self.ops.push(Op::Image { image: img, xf, opacity: self.opacity.clamp(0.0, 1.0) }); } @@ -503,6 +538,37 @@ impl<'a> Scene<'a> { } } +/// The pixels of `img`, drawn by `xf`, that `clip` (a box in the document) shows, with one pixel +/// more on each side: the part and its top left pixel. The whole image when `xf` cannot be +/// inverted; `None` when `clip` shows none of it. +fn cropped(img: &Rgba, xf: Affine, clip: Rect) -> Option<(Rgba, u32, u32)> { + if xf.determinant().abs() < 1e-12 || !xf.determinant().is_finite() { + return Some((img.clone(), 0, 0)); + } + let inv = xf.inverse(); + let corners = + [Point::new(clip.x0, clip.y0), Point::new(clip.x1, clip.y0), Point::new(clip.x1, clip.y1), Point::new(clip.x0, clip.y1)].map(|p| inv * p); + let (w, h) = (f64::from(img.width), f64::from(img.height)); + let lo = |f: fn(&Point) -> f64| corners.iter().map(f).fold(f64::INFINITY, f64::min); + let hi = |f: fn(&Point) -> f64| corners.iter().map(f).fold(f64::NEG_INFINITY, f64::max); + let (x0, y0) = ((lo(|p| p.x).floor() - 1.0).max(0.0), (lo(|p| p.y).floor() - 1.0).max(0.0)); + let (x1, y1) = ((hi(|p| p.x).ceil() + 1.0).min(w), (hi(|p| p.y).ceil() + 1.0).min(h)); + if !(x0 < x1 && y0 < y1) { + return None; + } + let (x0, y0, x1, y1) = (x0 as u32, y0 as u32, x1 as u32, y1 as u32); + if (x0, y0, x1, y1) == (0, 0, img.width, img.height) { + return Some((img.clone(), 0, 0)); + } + let row = img.width as usize * 4; + let mut pixels = Vec::with_capacity((x1 - x0) as usize * (y1 - y0) as usize * 4); + for y in y0..y1 { + let start = y as usize * row + x0 as usize * 4; + pixels.extend_from_slice(img.pixels.get(start..start + (x1 - x0) as usize * 4)?); + } + Some((Rgba { width: x1 - x0, height: y1 - y0, pixels }, x0, y0)) +} + /// Do the instances of `def` stay apart? A grid or brick tiling places its tiles side by side, so /// art that stays in its tile never overlaps another instance's; hex tilings overlap their tiles. fn tiles_apart(def: &vectorcraft_doc::PatternDef) -> bool { diff --git a/crates/metafile/src/tests.rs b/crates/metafile/src/tests.rs index 658628f107..d5576ef4b5 100644 --- a/crates/metafile/src/tests.rs +++ b/crates/metafile/src/tests.rs @@ -288,6 +288,82 @@ fn emf_clips_gradients_and_images() { assert_eq!((count(&k, 35), count(&k, 36)), (3, 3)); } +/// An image changed by Perspective Distort is written as the clipped pieces of its mesh where +/// the format clips (EMF), and as one image at the placement nearest its corners, with a warning, +/// where it does not (WMF). +#[test] +fn a_distorted_image_is_its_mesh_with_clips_and_its_nearest_parallelogram_without() { + let mut d = doc_with(100.0, 100.0, vec![]); + let img = image_node(&mut d, png(4, 4, [10, 20, 30, 255]), 4, 4, Affine::scale(10.0)); + add(&mut d, img); + let id = d.layers[0].children().unwrap()[0].id; + let q = [(16.0, 0.0), (24.0, 0.0), (40.0, 40.0), (0.0, 40.0)].map(|(x, y)| Point::new(x, y)); + d.node_mut(id).unwrap().set_image_corners(q).unwrap(); + let images = |ops: &[crate::scene::Op]| ops.iter().filter(|o| matches!(o, crate::scene::Op::Image { .. })).count(); + let warned = |w: &[String]| w.iter().any(|w| w.contains("Perspective Distort or Free Distort")); + let (ops, warnings) = crate::scene::Scene::new(&d, d.artboards[0].rect, true).run(); + assert!(images(&ops) > 2 && !warned(&warnings), "{} images, {warnings:?}", images(&ops)); + let (ops, warnings) = crate::scene::Scene::new(&d, d.artboards[0].rect, false).run(); + assert!(images(&ops) == 1 && warned(&warnings), "{} images, {warnings:?}", images(&ops)); + // Without clips, the image is placed by the affine map nearest its corners. + let near = vectorcraft_doc::image_quad::nearest_affine(d.node(id).unwrap()).unwrap(); + let placed = ops.iter().find_map(|o| match o { + crate::scene::Op::Image { xf, .. } => Some(*xf), + _ => None, + }); + assert!(placed.unwrap().as_coeffs().iter().zip(near.as_coeffs()).all(|(a, b)| (a - b).abs() < 1e-9), "{placed:?} against {near:?}"); +} + +/// Each piece of a distorted image's mesh in EMF stores the pixels inside its clips, not the +/// whole image, placed where the uncropped piece puts them. +#[test] +fn the_pieces_of_a_distorted_image_store_only_the_pixels_they_show() { + let mut pixels = vec![]; + for y in 0..64u8 { + for x in 0..64u8 { + pixels.extend_from_slice(&[x * 4, y * 4, 0, 255]); + } + } + let img = + craft_image_codecs::Image::from_raw(64, 64, craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, pixels).unwrap(); + let bytes = craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap(); + let mut d = doc_with(100.0, 100.0, vec![]); + let n = image_node(&mut d, bytes, 64, 64, Affine::scale(1.5)); + add(&mut d, n); + let id = d.layers[0].children().unwrap()[0].id; + let q = [(30.0, 0.0), (66.0, 0.0), (96.0, 96.0), (0.0, 96.0)].map(|(x, y)| Point::new(x, y)); + d.node_mut(id).unwrap().set_image_corners(q).unwrap(); + let art = vectorcraft_doc::image_quad::distorted_art(d.node(id).unwrap()).unwrap(); + let whole: Vec = vectorcraft_doc::image_quad::distorted_pieces(&art) + .iter() + .filter_map(|p| match &p.children()?.get(1)?.kind { + NodeKind::Image(im) => Some(im.xf), + _ => None, + }) + .collect(); + let (ops, _) = crate::scene::Scene::new(&d, d.artboards[0].rect, true).run(); + let parts: Vec<(&crate::dib::Rgba, Affine)> = ops + .iter() + .filter_map(|o| match o { + crate::scene::Op::Image { image, xf, .. } => Some((&**image, *xf)), + _ => None, + }) + .collect(); + assert_eq!(parts.len(), whole.len()); + assert!(parts.len() > 8, "{}", parts.len()); + let stored: u64 = parts.iter().map(|(i, _)| u64::from(i.width) * u64::from(i.height)).sum(); + assert!(stored * 4 < 64 * 64 * parts.len() as u64, "{stored} pixels in {} pieces", parts.len()); + for ((part, xf), full) in parts.iter().zip(&whole) { + // The part's first pixel names where it starts in the image. + let (x0, y0) = (f64::from(part.pixels[0] / 4), f64::from(part.pixels[1] / 4)); + let want = *full * Affine::translate((x0, y0)); + assert!(xf.as_coeffs().iter().zip(want.as_coeffs()).all(|(a, b)| (a - b).abs() < 1e-6), "{xf:?} against {want:?}"); + // Each row runs on from that pixel. + let last = (part.width as usize - 1) * 4; + assert_eq!(f64::from(part.pixels[last] / 4), x0 + f64::from(part.width - 1)); + } +} + #[test] fn type_is_written_as_outlines() { let t = TextObject::point(Point::new(10.0, 50.0), "Hi", CharStyle { fill: red(), ..CharStyle::default() }); diff --git a/crates/pathops/src/lib.rs b/crates/pathops/src/lib.rs index d35050f70c..d500182401 100644 --- a/crates/pathops/src/lib.rs +++ b/crates/pathops/src/lib.rs @@ -28,7 +28,9 @@ pub use edit::{ }; pub use fit::{fit_cubics, fit_cubics_through}; pub use offset::{Cap, Join, MAX_OFFSET_SEGMENT_PAIRS, offset_path, outline_stroke, stroke_region, try_offset_path}; -pub use pathfinder::{FaceMerger, PathfinderOp, Region, Shape, merge_regions, pathfinder, pathfinder_with, region_at, regions, regions_within}; +pub use pathfinder::{ + FaceMerger, PathfinderOp, Region, Shape, merge_regions, pathfinder, pathfinder_with, region_at, regions, regions_with, regions_within, +}; 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, diff --git a/crates/pathops/src/pathfinder.rs b/crates/pathops/src/pathfinder.rs index 112f9620c3..af7bf90231 100644 --- a/crates/pathops/src/pathfinder.rs +++ b/crates/pathops/src/pathfinder.rs @@ -557,7 +557,7 @@ pub fn regions(shapes: &[Shape]) -> Vec { } /// [`regions`] refit to `precision`. -pub(crate) fn regions_with(shapes: &[Shape], precision: f64) -> Vec { +pub fn regions_with(shapes: &[Shape], precision: f64) -> Vec { arrangement(shapes, precision).map(|a| regions_of(&a)).unwrap_or_default() } diff --git a/crates/pdf/src/export.rs b/crates/pdf/src/export.rs index 1e7a3fc71a..094cdeb99d 100644 --- a/crates/pdf/src/export.rs +++ b/crates/pdf/src/export.rs @@ -60,6 +60,9 @@ pub(crate) struct Exporter<'a> { images: HashMap>, /// `Some` while opacity mask art is written: whether an image in it was left out. image_left_out: Option, + /// While the pieces of a distorted image whose opacity mask is its own pixel grid are written: + /// its image key and the image written with the mask as its alpha, which each piece draws. + piece_image: Option<(String, Image)>, /// While the pieces of a mesh-warped image are written: the size its pixels are resampled for /// ([`Exporter::warp_image_size`]). warp_size: Option, diff --git a/crates/pdf/src/export/exporter.rs b/crates/pdf/src/export/exporter.rs index 2d18888525..498c12ca04 100644 --- a/crates/pdf/src/export/exporter.rs +++ b/crates/pdf/src/export/exporter.rs @@ -35,6 +35,7 @@ impl<'a> Exporter<'a> { warnings: vec![], images: HashMap::new(), image_left_out: None, + piece_image: None, warp_size: None, brushes: None, knockout: doc.page_knockout, diff --git a/crates/pdf/src/export/nodes.rs b/crates/pdf/src/export/nodes.rs index 2a2ab1a884..94b1c819c5 100644 --- a/crates/pdf/src/export/nodes.rs +++ b/crates/pdf/src/export/nodes.rs @@ -374,7 +374,8 @@ impl Exporter<'_> { let (mut pushes, isolated_children) = transparency(s, n, page, container, knockout); let mask = n.extras().mask.as_deref().filter(|m| !m.disabled); let alpha = match (&n.kind, mask) { - (NodeKind::Image(im), Some(m)) => self.masked_image(im, m, !n.extras().pixelated), + // The mask's image shares the pixel grid only when it has the same corners (or none). + (NodeKind::Image(im), Some(m)) if n.image_quad() == m.art.image_quad() => self.masked_image(im, m, !n.extras().pixelated), _ => None, }; if let Some(m) = mask @@ -427,7 +428,7 @@ impl Exporter<'_> { self.shape(s, n, &bp, *rule, page); } NodeKind::Text(t) => self.text(s, n, t, page), - NodeKind::Image(im) => match (n.extras().colorize.as_deref(), self.doc.shown_image(n, im)) { + NodeKind::Image(im) if !n.is_distorted_image() => match (n.extras().colorize.as_deref(), self.doc.shown_image(n, im)) { (Some(p @ Paint::Solid { .. }), im) if self.doc.image_blob(&im).is_none_or(vectorcraft_doc::ImageBlob::takes_colorize) => { let im = &*im; if writable(s, im.xf, Rect::new(0.0, 0.0, im.width.max(1).into(), im.height.max(1).into())) { @@ -442,7 +443,11 @@ impl Exporter<'_> { self.warn(super::exporter::UNWRITABLE_IMAGE); } } - (_, im) => self.image(s, &im, alpha, n.extras().pixelated), + (_, im) => { + // A piece of a distorted image draws the image its mask was written into. + let alpha = alpha.or_else(|| self.piece_image.as_ref().filter(|(key, _)| *key == im.key).map(|(_, i)| i.clone())); + self.image(s, &im, alpha, n.extras().pixelated) + } }, NodeKind::SymbolInstance { symbol, xf } => { // Within the objects a frame may draw of symbol instances, as on screen: nested @@ -488,17 +493,28 @@ impl Exporter<'_> { } // A gradient mesh is a smooth patch shading where it can be written as one. NodeKind::Mesh(m) if self.mesh(s, m) => {} - // Live blends/envelopes/meshes export their evaluated (expanded) form. + // Live blends/envelopes/meshes (and distorted images) export their evaluated + // (expanded) form. NodeKind::Blend { .. } | NodeKind::Envelope { .. } | NodeKind::Mesh(_) | NodeKind::Repeat(_) | NodeKind::PlacedDocument(_) - | NodeKind::Intertwine { .. } => { + | NodeKind::Intertwine { .. } + | NodeKind::Image(_) => { let g = vectorcraft_effects::expand_live_deep(Some(self.doc), n); + // The pieces draw the image as it is shown, under its color mask's key. + let piece = match (&n.kind, &alpha) { + (NodeKind::Image(im), Some(img)) => Some((self.doc.shown_image(n, im).key.clone(), img.clone())), + _ => None, + }; + let outer = piece.map(|p| self.piece_image.replace(p)); for c in g.children().into_iter().flatten() { self.node(s, c, page, false); } + if let Some(outer) = outer { + self.piece_image = outer; + } } // Ruler guides draw on screen only. NodeKind::RulerGuide { .. } => {} diff --git a/crates/pdf/src/tests/cmykimages.rs b/crates/pdf/src/tests/cmykimages.rs index ec157a8182..b5f6185ea9 100644 --- a/crates/pdf/src/tests/cmykimages.rs +++ b/crates/pdf/src/tests/cmykimages.rs @@ -1173,6 +1173,43 @@ fn a_cmyk_image_masked_by_a_grey_image_of_its_grid_writes_it_as_its_smask() { assert!(String::from_utf8_lossy(&bytes).contains("/S/Luminosity"), "a luminosity soft mask"); } +/// A distorted CMYK image whose mask is a gray image distorted to the same corners keeps the +/// mask on its pixel grid: every piece of its mesh draws the image with the mask as its `/SMask`, +/// with a color mask on the image too. +#[test] +fn a_distorted_cmyk_image_and_its_grid_mask_with_the_same_corners_write_it_as_its_smask() { + for color_masked in [false, true] { + let mut d = masked_doc(png(image::GrayImage::from_raw(2, 2, vec![255, 128, 0, 64]).unwrap()), true, false); + let q = [(16.0, 0.0), (24.0, 0.0), (40.0, 40.0), (0.0, 40.0)].map(|(x, y)| Point::new(x, y)); + let id = d.layers[0].children().unwrap()[0].id; + let mut mask = d.node(id).unwrap().extras().mask.clone().unwrap(); + Arc::make_mut(&mut mask.art).set_image_corners(q).unwrap(); + if color_masked { + d.images.insert("shown".into(), ImageBlob::new("image/png", png(image::RgbaImage::from_pixel(2, 2, image::Rgba([0, 90, 200, 255]))))); + } + let n = d.node_mut(id).unwrap(); + n.extras_mut().mask = Some(mask); + if color_masked { + n.extras_mut().color_mask = Some(Box::new(vectorcraft_doc::color_mask::ColorMask { + key: "shown".into(), + from: "img".into(), + background: vectorcraft_doc::color_mask::MaskBackground::Colors, + colors: vec![[255, 255, 255]], + contiguous: false, + measure: vectorcraft_doc::color_mask::MaskMatch::Distance, + tolerance: 0.0, + softness: 0.0, + })); + } + n.set_image_corners(q).unwrap(); + let (bytes, smasks) = export_smasks(&d); + // The shown pixels of a color mask have alpha, so its pieces take their triangles as + // luminosity masks; the mask's alpha still goes to the image's own `/SMask`. + assert!(color_masked || !String::from_utf8_lossy(&bytes).contains("/S/Luminosity"), "no luminosity soft mask"); + assert!(!smasks.is_empty() && smasks.iter().all(|m| m.as_deref() == Some(&[255, 128, 0, 64][..])), "{color_masked}: {smasks:?}"); + } +} + /// A grey mask image with a color mask masks the CMYK image with the pixels it shows: its hidden /// pixels are clear in the image's `/SMask`. #[test] diff --git a/crates/pdf/src/tests/compression.rs b/crates/pdf/src/tests/compression.rs index 9f7c8560cf..86bbb69bcb 100644 --- a/crates/pdf/src/tests/compression.rs +++ b/crates/pdf/src/tests/compression.rs @@ -154,6 +154,48 @@ fn a_warped_image_is_written_once_for_all_its_pieces() { } } +/// An image changed by Perspective Distort is written as the pieces of its mesh, placed so that +/// its pixel rectangle's corners land on its corners: read back, each corner of the quad is a +/// corner of one of the pieces' images. +#[test] +fn a_distorted_image_is_written_with_its_corners_on_its_quad() { + let mut d = doc(encoded(colour(), ImageFormat::Png), "image/png"); + let id = d.layers[0].children().unwrap()[0].id; + let q = [(40.0, 10.0), (60.0, 10.0), (90.0, 90.0), (10.0, 90.0)].map(|(x, y)| Point::new(x, y)); + d.node_mut(id).unwrap().set_image_corners(q).unwrap(); + let bytes = export_with_report(&d, &PdfOptions::default()).unwrap().bytes; + let back = crate::import(&bytes).unwrap(); + let (mut seen, mut pieces) = ([false; 4], 0); + back.walk(|n| { + if let NodeKind::Image(im) = &n.kind { + pieces += 1; + let (w, h) = (f64::from(im.width), f64::from(im.height)); + for p in [(0.0, 0.0), (w, 0.0), (w, h), (0.0, h)] { + let at = im.xf * Point::new(p.0, p.1); + for (i, c) in q.iter().enumerate() { + seen[i] |= at.distance(*c) < 0.01; + } + } + } + }); + assert!(pieces > 2, "{pieces}"); + assert_eq!(seen, [true; 4]); + // The pieces are clipped by the quad: a clipping path with its bounds and its area. + let mut quad_clips = 0; + back.walk(|n| { + if let NodeKind::Group { children, clip: true } = &n.kind + && let Some(p) = children.first().and_then(|c| c.path_data()) + && let Some(b) = p.bounds() + { + let area: f64 = p.subpaths.iter().map(|s| s.area()).sum::().abs(); + if [b.x0 - 10.0, b.y0 - 10.0, b.x1 - 90.0, b.y1 - 90.0].iter().all(|v| v.abs() < 0.01) && (area - 4000.0).abs() < 1.0 { + quad_clips += 1; + } + } + }); + assert!(quad_clips >= 1, "no clipping path on the quad"); +} + #[test] fn jpeg_zip_and_automatic_compression() { let png = doc(encoded(colour(), ImageFormat::Png), "image/png"); diff --git a/crates/plugins/src/objects.rs b/crates/plugins/src/objects.rs index 08689b7235..19a90500ce 100644 --- a/crates/plugins/src/objects.rs +++ b/crates/plugins/src/objects.rs @@ -325,7 +325,11 @@ fn encode_read_only_within(doc: &Document, n: &Node, symbols: &SymbolBoxes, left o["truncated"] = json!(false); } NodeKind::Image(im) => { - o["transform"] = affine_json(im.xf); + // A distorted image: its corners, and the affine placement nearest them at its middle. + o["transform"] = affine_json(vectorcraft_doc::image_quad::nearest_affine(n).unwrap_or(im.xf)); + if let Some(q) = n.image_quad() { + o["corners"] = json!(q.map(|p| [p.x, p.y])); + } o["pixelSize"] = json!([im.width, im.height]); o["colorMode"] = json!(doc.image_blob(im).map_or("unknown", color_mode)); o["linked"] = json!(im.link.is_some()); diff --git a/crates/plugins/src/objects/tests.rs b/crates/plugins/src/objects/tests.rs index 99e3088840..58159c3370 100644 --- a/crates/plugins/src/objects/tests.rs +++ b/crates/plugins/src/objects/tests.rs @@ -608,6 +608,24 @@ fn declared_embedded_and_linked_images_have_distinct_metadata_and_pixel_omission } } +/// A distorted image comes with its corners, and with the transform that matches it at its middle +/// rather than the one it had before the distort. +#[test] +fn a_distorted_image_comes_with_its_corners() { + let (mut d, _, _, [_, embedded, linked, ..]) = mixed(); + let q = [(40.0, 60.0), (42.0, 60.0), (44.0, 62.0), (40.0, 62.0)].map(|(x, y)| Point::new(x, y)); + d.node_mut(embedded).unwrap().set_image_corners(q).unwrap(); + let e = encode_read_only(&d, d.node(embedded).unwrap()).unwrap(); + assert_eq!(e["corners"], json!([[40.0, 60.0], [42.0, 60.0], [44.0, 62.0], [40.0, 62.0]])); + assert_ne!(e["transform"], json!([2.0, 0.0, 0.0, 2.0, 40.0, 60.0])); + // The transform is the affine map nearest the corners, the one that matches them at the middle. + let near = vectorcraft_doc::image_quad::nearest_affine(d.node(embedded).unwrap()).unwrap().as_coeffs(); + let got: Vec = e["transform"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect(); + assert!(got.len() == 6 && got.iter().zip(near).all(|(a, b)| (a - b).abs() < 1e-9), "{got:?} against {near:?}"); + let plain = encode_read_only(&d, d.node(linked).unwrap()).unwrap(); + assert!(plain.get("corners").is_none()); +} + /// A CMYK image's pixels are its inks as the working CMYK profile shows them on the canvas: black /// ink alone is the profile's black, not RGB black. #[test] diff --git a/crates/render/src/live.rs b/crates/render/src/live.rs index dfa79a9ad5..cda46c8fc0 100644 --- a/crates/render/src/live.rs +++ b/crates/render/src/live.rs @@ -51,6 +51,8 @@ pub(crate) struct LiveCache { expanded: FrameCache, Expanded, Found)>, meshes: FrameCache<(usize, usize), MeshEntry>, walks: FrameCache, + /// A distorted image's art by node and scale step ([`Renderer::distorted_art`]). + distorted: FrameCache<(usize, usize), (Arc, Arc)>, /// How many live objects [`Renderer::live_expanded`] evaluated and how many meshes /// [`Renderer::mesh_quads`] tessellated. #[cfg(test)] @@ -66,6 +68,7 @@ impl Default for LiveCache { expanded: FrameCache::new(lru::LIVE_BUDGET, 256), meshes: FrameCache::new(lru::MESH_BUDGET, 256), walks: FrameCache::new(lru::WALK_BUDGET, 256), + distorted: FrameCache::new(lru::LIVE_BUDGET, 256), #[cfg(test)] evaluated: 0, #[cfg(test)] @@ -80,6 +83,7 @@ impl LiveCache { self.expanded.sweep(stamp); self.meshes.sweep(stamp); self.walks.sweep(stamp); + self.distorted.sweep(stamp); } /// A cache whose evaluations take at most `budget` bytes. @@ -522,6 +526,28 @@ impl Renderer { v } + /// Distorted image `a`'s art for drawing through `view` + /// ([`vectorcraft_doc::image_quad::distorted_art_at`] at the view's largest stretch, rounded to + /// a quarter of an octave), kept with `cache` while the node stays the same. `None` when `a` is + /// not a distorted image. + pub(crate) fn distorted_art(&mut self, a: &Arc, view: Affine, cache: bool) -> Option> { + let scale = vectorcraft_doc::image_quad::max_stretch(view); + let step = if scale.is_finite() && scale > 0.0 { (scale.log2() * 4.0).round().clamp(-256.0, 256.0) } else { 0.0 }; + let key = (Arc::as_ptr(a) as usize, (step + 256.0) as usize); + if cache + && let Some(e) = self.live.distorted.get(&key, self.stamp) + && Arc::ptr_eq(&e.0, a) + { + return Some(e.1.clone()); + } + let density = vectorcraft_doc::image_quad::Density::at_scale((step / 4.0).exp2()); + let art = Arc::new(vectorcraft_doc::image_quad::distorted_art_at(a, density)?); + if cache { + self.live.distorted.insert(key, (a.clone(), art.clone()), lru::node_bytes(&art), self.stamp); + } + Some(art) + } + /// The quads of mesh `a` (`m`) at subdivision `level`, kept while the node and the color /// settings that colored them ([`GradientMesh::color_at`]) stay the same. fn mesh_quads(&mut self, doc: &Document, a: &Arc, m: &GradientMesh, level: usize, cache: bool) -> Arc> { @@ -572,6 +598,15 @@ impl Renderer { match &a.kind { NodeKind::PlacedDocument(p) => self.draw_placed(ctx, f, p), NodeKind::Mesh(m) => self.draw_mesh(ctx, f, a, m, cache), + // Outline mode draws a distorted image's frame through its corners, not the pieces it + // is drawn with. + NodeKind::Image(_) if f.opts.outline => self.draw_distorted_frame(ctx, f, a, cache), + // A distorted image's mesh is cut for the view's scale. + NodeKind::Image(_) => { + if let Some(art) = self.distorted_art(a, f.view, cache) { + self.draw_arc(ctx, f, &art); + } + } NodeKind::Blend { .. } | NodeKind::Envelope { .. } | NodeKind::Repeat(_) diff --git a/crates/render/src/renderer/images.rs b/crates/render/src/renderer/images.rs index 76b3bf53f2..fd0817a95d 100644 --- a/crates/render/src/renderer/images.rs +++ b/crates/render/src/renderer/images.rs @@ -2,6 +2,8 @@ use super::{ Affine, Arc, BezPath, Document, FillRule, Frame, HashMap, Ink, Node, NodeKind, Pixmap, Rect, RenderContext, Renderer, Shape, blob_key, blob_pixmap, fill_rule, image_mip, ink, lookup, mip_level, peniko, proof, vello_cpu, }; +use vello_cpu::peniko::{BlendMode, Compose, Mix}; + use crate::images; /// The color image node `n` of `doc` is colorized with ([`vectorcraft_doc::NodeExtras::colorize`]), @@ -24,6 +26,47 @@ impl Renderer { self.draw_image_in(ctx, f, im, None, tint, false); } + /// Distorted image `n` in outline mode: with Document Setup's Show Images in Outline Mode its + /// pixels, each piece of its mesh at the view's scale ([`Self::distorted_art`]) painted into + /// its triangle inside its corners, then its frame through its corners as a hairline. The + /// pieces knock out as the mesh's knockout group does ([`Self::draw_knockout`]): each first + /// erases the pieces below it inside its triangle, so a partly transparent image paints once + /// where pieces overlap. + pub(crate) fn draw_distorted_frame(&mut self, ctx: &mut RenderContext, f: &Frame, n: &Arc, cache: bool) { + let frame = n.image_frame(); + if f.doc.setup.outline_images + && let Some(edge) = &frame + && let Some(art) = self.distorted_art(n, f.view, cache) + { + let layer = |ctx: &mut RenderContext, compose: Compose| { + ctx.set_transform(Affine::IDENTITY); + ctx.push_layer(None, Some(BlendMode::new(Mix::Normal, compose)), None, None, None); + }; + // The pieces along the edges reach past the corners: the corners clip them. + ctx.set_transform(f.view); + ctx.push_layer(Some(edge), Some(BlendMode::new(Mix::Normal, Compose::SrcOver)), None, None, None); + for piece in vectorcraft_doc::image_quad::distorted_pieces(&art) { + let Some([clip, image]) = piece.children().map(Vec::as_slice) else { continue }; + let (NodeKind::Path { path, .. }, NodeKind::Image(im)) = (&clip.kind, &image.kind) else { continue }; + let region = (path.to_bezpath(), FillRule::NonZero); + layer(ctx, Compose::DestOut); + ctx.set_transform(f.view); + ctx.set_paint(f.ink.fixed([255, 255, 255, 255])); + ctx.set_fill_rule(fill_rule(region.1)); + ctx.fill_path(®ion.0); + ctx.pop_layer(); + layer(ctx, Compose::Plus); + let shown = f.doc.shown_image(image.as_ref(), im.as_ref()); + self.draw_image_in(ctx, f, &shown, Some(®ion), None, image.extras().pixelated); + ctx.pop_layer(); + } + ctx.pop_layer(); + } + if let Some(bp) = &frame { + self.hairline(ctx, f, bp, [0, 0, 0, 255]); + } + } + /// Draw an image, or with `area` (a region in the document inside the image's frame, see /// [`plain_image`]) the image painted into that region; colorized with `tint` when given; with /// `pixelated` ([`vectorcraft_doc::NodeExtras::pixelated`]) without smoothing. @@ -136,7 +179,9 @@ impl Renderer { } else if !pending && !outline { self.image_left_out = self.image_left_out.map(|_| true); } - if outline { + // An image painted into a region in outline mode is a piece of a distorted image, whose + // frame its caller draws ([`Self::draw_distorted_frame`]). + if outline && area.is_none() { let mut p = rect.to_path(0.1); p.apply_affine(im.xf); self.hairline(ctx, f, &p, [0, 0, 0, 255]); diff --git a/crates/render/src/renderer/nodes.rs b/crates/render/src/renderer/nodes.rs index 2a876c1073..619d27bf99 100644 --- a/crates/render/src/renderer/nodes.rs +++ b/crates/render/src/renderer/nodes.rs @@ -251,6 +251,7 @@ impl Renderer { && !f.opts.outline && !self.is_shape(a) && let NodeKind::Image(im) = &a.kind + && !a.is_distorted_image() && white_shape_mask(m) && let Some(region) = self.clip_of(&m.art) && shape_masked_image(a, im, ®ion.0) @@ -370,7 +371,7 @@ impl Renderer { self.stats.drawn += 1; return; } - if vectorcraft_doc::live::is_live(a) || effects::has_pathfinder(a) { + if vectorcraft_doc::live::is_drawn_live(a) || effects::has_pathfinder(a) { // The isolated object itself (a repeat isolated to edit its source, #5054) draws its // art as usual, as an isolated group does in `draw_layer_node`. let settle = f.opts.isolated == Some(a.id) && f.doc.mask_edit.is_none(); @@ -525,6 +526,7 @@ impl Renderer { // a clip layer (envelopes cut distorted images into many such pieces). if let ([image], None, None) = (rest, &fill, &stroke) && let NodeKind::Image(im) = &image.kind + && !image.is_distorted_image() && plain_image(image, im, ®ion.0) { let im = f.doc.shown_image(image, im); @@ -578,7 +580,7 @@ impl Renderer { } } NodeKind::Text(t) => self.draw_text(ctx, f, n, t), - NodeKind::Image(im) => { + NodeKind::Image(im) if !n.is_distorted_image() => { self.draw_image_in(ctx, f, &f.doc.shown_image(n, im), None, images::image_tint(f.doc, n, f.ink), n.extras().pixelated) } NodeKind::SymbolInstance { symbol, xf } => { @@ -604,7 +606,8 @@ impl Renderer { | NodeKind::Mesh(_) | NodeKind::Repeat(_) | NodeKind::PlacedDocument(_) - | NodeKind::Intertwine { .. } => match self.live_root.clone().filter(|a| std::ptr::eq(&**a, n)) { + | NodeKind::Intertwine { .. } + | NodeKind::Image(_) => match self.live_root.clone().filter(|a| std::ptr::eq(&**a, n)) { Some(a) => self.draw_live_body(ctx, f, &a, true), None => self.draw_live_node(ctx, f, n), }, @@ -629,7 +632,7 @@ impl Renderer { /// same from frame to frame while the art does. When `a` is a live object, /// [`Self::draw_content`] draws its evaluation from the live cache ([`Self::live_root`]). pub(crate) fn draw_kept_node(&mut self, ctx: &mut RenderContext, f: &Frame, a: &Arc) { - let live = vectorcraft_doc::live::is_live(a).then(|| a.clone()); + let live = vectorcraft_doc::live::is_drawn_live(a).then(|| a.clone()); let outer = std::mem::replace(&mut self.live_root, live); self.draw_forced_arc(ctx, f, a); self.live_root = outer; diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index d63f9e91b4..06cada26f4 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -605,6 +605,35 @@ fn outline_mode_no_fill() { assert!(r.pixel(10, 50)[0] < 200); } +/// Outline view draws a distorted image's frame through its corners: a slanted side, and nothing +/// inside or along the rectangle it was placed in. +#[test] +fn outline_mode_draws_a_distorted_images_frame_through_its_corners() { + let mut d = Document::new(100.0, 100.0); + let id = d.alloc_id(); + let im = vectorcraft_doc::ImageObject { + key: "k".into(), + width: 10, + height: 10, + xf: Affine::scale(10.0), + link: None, + placement: Default::default(), + pixels: None, + }; + let mut n = Node::new(id, NodeKind::Image(Box::new(im))); + let q = [(40.0, 0.0), (60.0, 0.0), (100.0, 100.0), (0.0, 100.0)].map(|(x, y)| vectorcraft_geom::Point::new(x, y)); + n.set_image_corners(q).unwrap(); + let l = d.layers[0].id; + d.insert(Some(l), 0, n).unwrap(); + let r = + Renderer::new().render(&d, 100, 100, Affine::IDENTITY, &RenderOptions { outline: true, background: Some([255; 4]), ..Default::default() }); + // On the left side, halfway down: from (40, 0) to (0, 100). + assert!(r.pixel(20, 50)[0] < 200, "the slanted side"); + // The old rectangle's left edge and the inside of the quad stay blank. + assert_eq!(r.pixel(1, 30), [255; 4]); + assert_eq!(r.pixel(50, 50), [255; 4]); +} + /// A 100 × 100 document with each kind of path Outline view draws, and the ids of its objects by /// name: a stroked square, a compound path with a hole, a path and a compound path with a live /// effect, a guide, a clip group, an Image Trace object showing its outlines, and a path in a layer diff --git a/crates/render/src/tests/meshwarp.rs b/crates/render/src/tests/meshwarp.rs index 3316ba70bb..5f9aec38f0 100644 --- a/crates/render/src/tests/meshwarp.rs +++ b/crates/render/src/tests/meshwarp.rs @@ -136,3 +136,64 @@ fn other_clip_groups_in_a_knockout_group_knock_out_by_their_alpha() { let a = r.pixel(120, 80)[3]; assert!(a > 160, "{a}"); } + +/// Show Images in Outline Mode paints a half transparent distorted image's pixels once, where the +/// pieces of its mesh overlap too: inside the image, its alpha is the preview's. +#[test] +fn outline_mode_paints_a_distorted_images_pixels_once_where_its_pieces_overlap() { + let mut d = Document::new(100.0, 100.0); + d.images.insert("pic".into(), ImageBlob::png(png(128))); + d.setup.outline_images = true; + let im = ImageObject { + key: "pic".into(), + width: 4, + height: 4, + xf: Affine::translate((10.0, 10.0)) * Affine::scale(20.0), + link: None, + placement: Default::default(), + pixels: None, + }; + let mut n = Node::new(d.alloc_id(), NodeKind::Image(Box::new(im))); + n.set_image_corners([(20.0, 10.0), (80.0, 10.0), (90.0, 90.0), (10.0, 90.0)].map(|(x, y)| Point::new(x, y))).unwrap(); + let pieces = vectorcraft_doc::image_quad::distorted_pieces(&vectorcraft_doc::image_quad::distorted_art(&n).unwrap()).len(); + assert!(pieces > 2, "{pieces}"); + d.insert(Some(d.layers[0].id), 0, n).unwrap(); + let r = Renderer::new().render(&d, 400, 400, Affine::scale(4.0), &RenderOptions { outline: true, background: None, ..Default::default() }); + let preview = drawn(&d); + let a = preview.pixel(200, 200)[3]; + assert!(a.abs_diff(128) <= 4, "the image's own alpha inside it: {a}"); + let mut off = vec![]; + for y in 80..320 { + for x in 100..300 { + let (a, b) = (r.pixel(x, y)[3], preview.pixel(x, y)[3]); + if a.abs_diff(b) > 2 && off.len() < 8 { + off.push((x, y, a, b)); + } + } + } + assert_eq!(off, vec![], "outline alpha against preview alpha"); +} + +/// The canvas cuts a distorted image's mesh for the view's scale: more pieces zoomed in, fewer +/// zoomed out, than the mesh files and print take. +#[test] +fn the_canvas_cuts_a_distorted_images_mesh_for_the_zoom() { + let im = + ImageObject { key: "pic".into(), width: 400, height: 400, xf: Affine::IDENTITY, link: None, placement: Default::default(), pixels: None }; + let mut n = Node::new(vectorcraft_doc::NodeId(1), NodeKind::Image(Box::new(im))); + n.set_image_corners([(40.0, 0.0), (360.0, 0.0), (400.0, 400.0), (0.0, 400.0)].map(|(x, y)| Point::new(x, y))).unwrap(); + let page = vectorcraft_doc::image_quad::distorted_pieces(&vectorcraft_doc::image_quad::distorted_art(&n).unwrap()).len(); + let n = std::sync::Arc::new(n); + let mut r = Renderer::new(); + let mut pieces = |scale: f64| vectorcraft_doc::image_quad::distorted_pieces(&r.distorted_art(&n, Affine::scale(scale), false).unwrap()).len(); + let (small, large) = (pieces(1.0 / 25.0), pieces(8.0)); + assert!(small < page && page < large, "{small} {page} {large}"); + // A view that stretches one way and squeezes the other as much keeps its area, and still + // takes a finer mesh than an unscaled one. + let (plain, stretched) = (pieces(1.0), r_pieces(&n, Affine::scale_non_uniform(16.0, 1.0 / 16.0))); + assert!(stretched > plain, "{stretched} {plain}"); +} + +fn r_pieces(n: &std::sync::Arc, view: Affine) -> usize { + vectorcraft_doc::image_quad::distorted_pieces(&Renderer::new().distorted_art(n, view, false).unwrap()).len() +} diff --git a/crates/render/src/tests/objectfx.rs b/crates/render/src/tests/objectfx.rs index 5a4fb97b44..2c92758f49 100644 --- a/crates/render/src/tests/objectfx.rs +++ b/crates/render/src/tests/objectfx.rs @@ -611,6 +611,65 @@ fn a_shadow_on_an_image_paints_offset_pixels() { assert!(worst <= 4, "max channel difference {worst}"); } +/// A distorted opaque image is drawn opaque between its corners, where the pieces of its mesh +/// meet too; its drop shadow is the shape between its corners moved, and nothing paints where its +/// rectangle was. +#[test] +fn a_distorted_image_is_opaque_between_its_corners_and_its_shadow_follows_them() { + let mut d = image_doc(vec![fx("stylize.dropShadow", json!({"x": 10, "y": 10, "blur": 0, "opacity": 100, "mode": "normal"}))]); + let id = d.layers[0].children().unwrap()[0].id; + d.node_mut(id).unwrap().set_image_corners([(35.0, 20.0), (45.0, 20.0), (50.0, 50.0), (20.0, 50.0)].map(|(x, y)| Point::new(x, y))).unwrap(); + let img = render(&d); + let mut faded = vec![]; + for y in 30..42 { + for x in 30..40 { + let p = img.pixel(x, y); + // A seam shows the white page (green) or the shadow below (darker red) through. + if p[0] < 200 || p[1] > 48 { + faded.push((x, y, p)); + } + } + } + assert_eq!(faded, vec![], "the image's red, also where its pieces meet"); + assert!(lum(img.pixel(40, 55)) < 100, "the shadow below the quad: {:?}", img.pixel(40, 55)); + assert_eq!(lum(img.pixel(24, 28)), WHITE, "outside the quad, inside the old rectangle"); + // The rectangle's shadow would reach (58, 36); the quad's shadow ends at x = 56 there. + assert_eq!(lum(img.pixel(58, 36)), WHITE, "outside the quad's shadow, inside the rectangle's"); +} + +/// A distorted opaque image draws opaque inside its corners at any zoom, where the pieces of its +/// mesh meet too, and nothing of it draws outside its corners. +#[test] +fn a_distorted_image_is_opaque_inside_its_corners_at_every_zoom() { + let mut d = image_doc(vec![]); + let id = d.layers[0].children().unwrap()[0].id; + let q = [(35.0, 20.0), (45.0, 20.0), (50.0, 50.0), (20.0, 50.0)].map(|(x, y)| Point::new(x, y)); + d.node_mut(id).unwrap().set_image_corners(q).unwrap(); + for scale in [0.5, 1.0, 3.0] { + let size = (100.0 * scale) as u32; + let opts = RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() }; + let img = Renderer::new().render(&d, size, size, Affine::scale(scale), &opts); + let at = |x: f64, y: f64| img.pixel((x * scale) as u32, (y * scale) as u32); + let mut faded = vec![]; + // Points at least 2.5 pt inside the corners: the left side runs from (35, 20) to (20, 50) + // and the right side from (45, 20) to (50, 50). + for y in [24.0, 30.0, 36.0, 42.0, 47.0] { + let t = (y - 20.0) / 30.0; + let (left, right) = (35.0 - 15.0 * t + 2.5, 45.0 + 5.0 * t - 2.5); + let mid = (left + right) / 2.0; + for x in [left, (left + mid) / 2.0, mid, (mid + right) / 2.0, right] { + let p = at(x, y); + if p[1] > 12 || p[2] > 12 { + faded.push((x, y, p)); + } + } + } + assert_eq!(faded, vec![], "the image's red at {scale}x"); + assert_eq!(lum(at(24.0, 28.0)), WHITE, "outside the corners at {scale}x"); + assert_eq!(lum(at(36.0, 17.0)), WHITE, "above the top edge at {scale}x"); + } +} + #[test] fn blur_on_a_symbol_instance_softens_its_edges() { let plain = render(&symbol_doc(vec![])); diff --git a/crates/svg/src/export/nodes.rs b/crates/svg/src/export/nodes.rs index 6427d048bd..b92e888b57 100644 --- a/crates/svg/src/export/nodes.rs +++ b/crates/svg/src/export/nodes.rs @@ -90,6 +90,7 @@ impl Reuse { | NodeKind::Repeat(_) | NodeKind::PlacedDocument(_) | NodeKind::Intertwine { .. } => (self.turns, self.scales) = (false, false), + NodeKind::Image(_) if n.is_distorted_image() => (self.turns, self.scales) = (false, false), NodeKind::SymbolInstance { symbol, .. } => { // A scale reaching an instance of a symbol with 9-slice guides changes how its // cells are sized. @@ -988,7 +989,7 @@ impl Writer<'_> { self.shape(n, &d.join(" "), None, &paths, *rule, export_shape_bounds(n)); } NodeKind::Text(t) => self.text_node(n, t), - NodeKind::Image(im) => { + NodeKind::Image(im) if !n.is_distorted_image() => { let shown = self.doc.shown_image(n, im); let im = &*shown; if let Some(Paint::Solid { color, .. }) = n.extras().colorize.as_deref() @@ -1090,14 +1091,28 @@ impl Writer<'_> { self.line(""); (self.xf, self.instance_xf) = saved; } - // Live blends/envelopes/meshes export their evaluated (expanded) form. + // Live blends/envelopes/meshes (and distorted images) export their evaluated + // (expanded) form. NodeKind::Blend { .. } | NodeKind::Envelope { .. } | NodeKind::Mesh(_) | NodeKind::Repeat(_) | NodeKind::PlacedDocument(_) - | NodeKind::Intertwine { .. } => { - let g = vectorcraft_effects::expand_live_deep(Some(self.doc), n); + | NodeKind::Intertwine { .. } + | NodeKind::Image(_) => { + let mut g = vectorcraft_effects::expand_live_deep(Some(self.doc), n); + // A distorted image inside instances that scale it is cut as finely on the page as + // one placed directly. + let stretch = vectorcraft_doc::image_quad::max_stretch(self.instance_xf); + if n.is_distorted_image() + && (stretch - 1.0).abs() > 1e-9 + && let Some(art) = vectorcraft_doc::image_quad::distorted_art_at(n, vectorcraft_doc::image_quad::Density::page_at(stretch)) + && let NodeKind::Group { children, .. } = &mut g.kind + && let [only] = &mut children[..] + && only.id == n.id + { + *only = std::sync::Arc::new(art); + } self.share_images(&g); self.node_body(&g); } diff --git a/crates/svg/tests/it/warp_pieces.rs b/crates/svg/tests/it/warp_pieces.rs index 437bab8a65..d2493dabf3 100644 --- a/crates/svg/tests/it/warp_pieces.rs +++ b/crates/svg/tests/it/warp_pieces.rs @@ -167,6 +167,80 @@ fn hidden_warp_pieces_share_no_image() { } } +/// An image whose corners Perspective Distort moved is written with its pixels between those +/// corners: opaque just inside each corner of the quad, and clear where its rectangle was but the +/// quad is not. +#[test] +fn a_distorted_image_is_written_between_its_corners() { + let q = [(40.0, 10.0), (60.0, 10.0), (90.0, 90.0), (10.0, 90.0)].map(|(x, y)| Point::new(x, y)); + let mut d = Document::new(100.0, 100.0); + let n = distorted_image(&mut d, q, 4); + d.insert(d.default_layer(), 0, n).unwrap(); + let svg = export_full(&d, &ExportOptions::default(), None).svg; + let tree = resvg::usvg::Tree::from_str(&svg, &resvg::usvg::Options::default()).unwrap(); + let mut pixmap = resvg::tiny_skia::Pixmap::new(400, 400).unwrap(); + resvg::render(&tree, resvg::tiny_skia::Transform::from_scale(4.0, 4.0), &mut pixmap.as_mut()); + let alpha = |x: f64, y: f64| pixmap.pixel((x * 4.0) as u32, (y * 4.0) as u32).unwrap().alpha(); + // A point (in points) 2 pt inside each corner, toward the quad's middle. + let mid = Point::new(50.0, 50.0); + for c in q { + let inside = c + (mid - c).normalize() * 2.0; + assert!(alpha(inside.x, inside.y) > 200, "{c:?}: {}", alpha(inside.x, inside.y)); + } + // The rectangle's top corners lie outside the quad. + assert_eq!(alpha(14.0, 14.0), 0); + assert_eq!(alpha(86.0, 14.0), 0); +} + +/// A plain opaque red `px` × `px` image over (10, 10)–(90, 90), its corners moved to `q`. +fn distorted_image(d: &mut Document, q: [Point; 4], px: u32) -> Node { + let img = craft_image_codecs::Image::from_raw( + px, + px, + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U8, + [255, 0, 0, 255].repeat((px * px) as usize), + ) + .unwrap(); + let png = craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap(); + d.images.insert("pic".into(), ImageBlob::png(png)); + let im = ImageObject { + key: "pic".into(), + width: px, + height: px, + xf: Affine::translate((10.0, 10.0)) * Affine::scale(80.0 / f64::from(px)), + link: None, + placement: Default::default(), + pixels: None, + }; + let mut n = Node::new(d.alloc_id(), NodeKind::Image(Box::new(im))); + n.set_image_corners(q).unwrap(); + n +} + +/// A distorted image in a symbol instance that scales it is cut into as many pieces as the same +/// image placed directly at that size. +#[test] +fn a_distorted_image_in_a_scaled_instance_is_cut_as_finely_as_one_placed_directly() { + let q = [(40.0, 10.0), (60.0, 10.0), (90.0, 90.0), (10.0, 90.0)].map(|(x, y)| Point::new(x, y)); + let pieces = |d: &Document| export_full(d, &ExportOptions::default(), None).svg.matches(" unscaled, "{scaled} {unscaled}"); + assert!(scaled.abs_diff(want) * 10 <= want, "{scaled} against {want}"); +} + /// Pieces of an opaque image are drawn one over another without knockout masks; a colorize paint /// draws a gray image's light pixels partly transparent, so its pieces take them. #[test] diff --git a/crates/three-d/src/lib.rs b/crates/three-d/src/lib.rs index c99a437efd..56a49aadf7 100644 --- a/crates/three-d/src/lib.rs +++ b/crates/three-d/src/lib.rs @@ -12,9 +12,9 @@ pub mod fold; mod solid; mod visibility; pub use solid::{ - Bevel, BevelShape, DepthPlane, Extrude, FaceMap, Facet, Inflate, MapCell, MeshFace, PlanarFace, SolidSurface, SurfaceKind, TOO_COMPLEX_SOLID, - View, extrude, extrude_face_map, extrude_mesh_face, extrude_side_size, extrude_surfaces, inflate, inflate_each, inflate_together, plane, - plane_face_map, plane_mesh_face, + Bevel, BevelProfile, BevelShape, DepthPlane, Extrude, FaceMap, Facet, Inflate, MapCell, MeshFace, PlanarFace, SolidSurface, SurfaceKind, + TOO_COMPLEX_SOLID, View, extrude, extrude_face_map, extrude_mesh_face, extrude_side_size, extrude_surfaces, inflate, inflate_each, + inflate_together, plane, plane_face_map, plane_mesh_face, }; pub use visibility::{VisibleFace, visible_faces}; mod shading; diff --git a/crates/three-d/src/solid.rs b/crates/three-d/src/solid.rs index be13429151..71f039724f 100644 --- a/crates/three-d/src/solid.rs +++ b/crates/three-d/src/solid.rs @@ -113,6 +113,8 @@ impl View { } /// The shape of a bevel's cross-section, from the cap's edge (0) to the side wall (1). +// A custom profile takes 258 bytes; an extrusion copies its bevel a few times. +#[allow(clippy::large_enum_variant)] #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub enum BevelShape { /// A straight 45° chamfer when width and height are equal. @@ -126,11 +128,73 @@ pub enum BevelShape { Step, /// A convex then concave S curve. Ogee, + /// A cross-section of the user's own, drawn as an open path ([`BevelProfile`]). + Custom(BevelProfile), +} + +/// A custom bevel's cross-section: points from the cap's edge, (0, 0), to the side wall, (1, 1), +/// each a (share of the width, share of the height) pair in 0..1, joined by straight lines. The +/// shares are kept to 1/32,768 in a fixed array, so the profile is `Copy` like the built-in shapes. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct BevelProfile { + points: [(u16, u16); BevelProfile::MAX_POINTS], + len: u8, +} + +impl BevelProfile { + /// The most points a profile holds. + pub const MAX_POINTS: usize = 64; + + /// A profile of `points`, or `None` unless there are 2 to [`Self::MAX_POINTS`] of them, every + /// share is a number in 0..1, and they start at (0, 0) and end at (1, 1). + pub fn new(points: &[(f64, f64)]) -> Option { + const END: f64 = 1e-6; + if !(2..=Self::MAX_POINTS).contains(&points.len()) || points.iter().any(|&(x, y)| !(0.0..=1.0).contains(&x) || !(0.0..=1.0).contains(&y)) { + return None; + } + let (first, last) = (points[0], points[points.len() - 1]); + if first.0 > END || first.1 > END || last.0 < 1.0 - END || last.1 < 1.0 - END { + return None; + } + let mut out = Self { points: [(0, 0); Self::MAX_POINTS], len: points.len() as u8 }; + let share = |v: f64| (v * f64::from(Self::ONE)).round() as u16; + for (slot, &(x, y)) in out.points.iter_mut().zip(points) { + *slot = (share(x), share(y)); + } + out.points[0] = (0, 0); + out.points[points.len() - 1] = (Self::ONE, Self::ONE); + Some(out) + } + + /// A whole share in the stored points: shares are kept to 1/32,768, so halves and quarters + /// stay exact. + const ONE: u16 = 1 << 15; + + /// The points, as (share of the width, share of the height). + pub fn points(&self) -> impl Iterator + '_ { + let share = |v: u16| f64::from(v) / f64::from(Self::ONE); + self.points[..usize::from(self.len)].iter().map(move |&(x, y)| (share(x), share(y))) + } + + /// The point at `s` (0..1), the points spread evenly along `s` and joined by straight lines. + fn at(&self, s: f64) -> (f64, f64) { + // A profile holds at least two points (`new`). + let len = usize::from(self.len).max(2); + let share = |v: u16| f64::from(v) / f64::from(Self::ONE); + let k = s * (len - 1) as f64; + let i = (k.floor() as usize).min(len - 2); + let f = k - i as f64; + let (a, b) = (self.points[i], self.points[i + 1]); + let (ax, ay, bx, by) = (share(a.0), share(a.1), share(b.0), share(b.1)); + (ax + (bx - ax) * f, ay + (by - ay) * f) + } } impl BevelShape { + /// The built-in shapes. pub const ALL: [BevelShape; 5] = [Self::Classic, Self::Rounded, Self::Cove, Self::Step, Self::Ogee]; + /// The shape's parameter value; `custom` for a [`BevelShape::Custom`] one. pub fn id(self) -> &'static str { match self { Self::Classic => "classic", @@ -138,9 +202,11 @@ impl BevelShape { Self::Cove => "cove", Self::Step => "step", Self::Ogee => "ogee", + Self::Custom(_) => "custom", } } + /// The built-in shape named `s`. pub fn parse(s: &str) -> Option { Self::ALL.into_iter().find(|b| b.id() == s) } @@ -150,6 +216,7 @@ impl BevelShape { let s = s.clamp(0.0, 1.0); let q = s * std::f64::consts::FRAC_PI_2; match self { + Self::Custom(profile) => profile.at(s), Self::Classic => (s, s), Self::Rounded => (1.0 - q.cos(), q.sin()), Self::Cove => (q.sin(), 1.0 - q.cos()), @@ -177,6 +244,11 @@ impl BevelShape { match self { Self::Classic => vec![0.0, 1.0], Self::Step => vec![0.0, 0.25, 0.5, 0.75, 1.0], + // Each of its points, where the straight lines between them turn. + Self::Custom(profile) => { + let last = (usize::from(profile.len) - 1) as f64; + (0..usize::from(profile.len)).map(|i| i as f64 / last).collect() + } _ => (0..=8).map(|i| f64::from(i) / 8.0).collect(), } } diff --git a/crates/three-d/src/solid/tests.rs b/crates/three-d/src/solid/tests.rs index 2caed84391..d4b86d7b10 100644 --- a/crates/three-d/src/solid/tests.rs +++ b/crates/three-d/src/solid/tests.rs @@ -354,6 +354,40 @@ fn bevel_shapes_repeats_and_both_sides_change_the_surface() { } } +/// A custom bevel's points are its cross-section, joined by straight lines: two points make the +/// classic chamfer, and the step shape's points make the step shape's solid. Other points change +/// the surface. A profile must run from (0, 0) to (1, 1) with every share in 0..1. +#[test] +fn custom_bevel_profiles_shape_the_bevel() { + let (p, b) = shape(&square(0.0, 0.0, 100.0)); + let v = View { rotation_x: -20.0, rotation_y: 30.0, ..front() }; + let solid = |shape: BevelShape| { + let bevel = Bevel { shape, width: 12.0, height: 12.0, repeat: 2, space: 0.2, both_sides: true, ..Bevel::default() }; + extrude(&p, FillRule::EvenOdd, b, Extrude { bevel: Some(bevel), ..Extrude::default() }, v).unwrap() + }; + let custom = |pts: &[(f64, f64)]| BevelShape::Custom(BevelProfile::new(pts).unwrap()); + assert_eq!(solid(custom(&[(0.0, 0.0), (1.0, 1.0)])), solid(BevelShape::Classic)); + let step = [(0.0, 0.0), (0.0, 0.5), (0.5, 0.5), (0.5, 1.0), (1.0, 1.0)]; + assert_eq!(solid(custom(&step)), solid(BevelShape::Step)); + let notch = custom(&[(0.0, 0.0), (0.2, 0.6), (0.7, 0.4), (1.0, 1.0)]); + assert_ne!(solid(notch), solid(BevelShape::Classic)); + assert_eq!(notch.id(), "custom"); + assert_eq!(BevelShape::parse("custom"), None); + assert_eq!(notch.at(0.0), (0.0, 0.0)); + assert_eq!(notch.at(1.0), (1.0, 1.0)); + // The point a third of the way along is the second point, kept to 1/32,768. + let (x, y) = notch.at(1.0 / 3.0); + assert!(close(x, 0.2, 1e-4) && close(y, 0.6, 1e-4), "{x}, {y}"); + // Inside, the bevel carves the shape with the same points. + let inside = Bevel { shape: notch, width: 12.0, height: 12.0, inside: true, ..Bevel::default() }; + assert!(extrude(&p, FillRule::EvenOdd, b, Extrude { bevel: Some(inside), ..Extrude::default() }, v).is_ok()); + let too_many = vec![(0.5, 0.5); BevelProfile::MAX_POINTS + 1]; + for bad in [&[(0.0, 0.0)][..], &[(0.1, 0.0), (1.0, 1.0)], &[(0.0, 0.0), (1.0, 0.9)], &[(0.0, 0.0), (1.2, 0.5), (1.0, 1.0)], &too_many] { + assert_eq!(BevelProfile::new(bad), None, "{bad:?}"); + } + assert!(BevelProfile::new(&[(0.0, 0.0), (f64::NAN, 0.5), (1.0, 1.0)]).is_none()); +} + #[test] fn holes_stay_holes_in_the_caps_and_get_walls_of_their_own() { let mut b = square(0.0, 0.0, 100.0); diff --git a/crates/tools/src/circle.rs b/crates/tools/src/circle.rs index 40f52290f4..e50e595e26 100644 --- a/crates/tools/src/circle.rs +++ b/crates/tools/src/circle.rs @@ -16,8 +16,17 @@ //! circle passes through the points (two are the same, three lie on one line) or the circle would //! reach past the canvas, the tool shows none and the release draws nothing; for three different //! points on one line, or a circle past the canvas, the pointer shows "Circle too large". +//! +//! The tool's options (Circle Tool Options, `tool.setOption`; kept with the preferences): +//! `center`, `radii` and `diameter` show or hide the center cross, the radius lines and the +//! diameter label; `color` is the color of the cross and the lines (one of [`COLORS`]); +//! `standardAnchors` off puts the circle's anchors at the points it was drawn through instead of +//! at 0°, 90°, 180° and 270° (`anchors: "points"`); `dragThird` off places the second point with +//! a click and draws the circle through three points with a third click, and a click on the second +//! point again (as a double-click there does) draws the circle on the two points. Every option is +//! on by default, and `color` is blue. -use serde_json::{Value, json}; +use serde_json::{Map, Value, json}; use vectorcraft_doc::MAX_COORD; use vectorcraft_geom::{Point, Rect, Vec2, shapes}; @@ -35,6 +44,71 @@ const REACH_PX: f64 = 3.0; /// The longest outline (screen points) the preview draws dashed, about 7,000 dashes. const DASHED_PX: f64 = 50_000.0; +/// The colors the center cross and the radius lines can be drawn in, by option value. Blue is the +/// feedback color the other drawing tools use. +pub const COLORS: &[(&str, [u8; 3])] = &[ + ("red", [0xe5, 0x2d, 0x27]), + ("blue", crate::draw2::FEEDBACK), + ("magenta", [0xd6, 0x2c, 0xd6]), + ("green", [0x1f, 0xb4, 0x4b]), + ("black", [0x00, 0x00, 0x00]), + ("gray", [0x80, 0x80, 0x80]), +]; + +/// The option keys that are true or false. +const SWITCHES: &[&str] = &["center", "radii", "diameter", "standardAnchors", "dragThird"]; + +/// The tool's options (see the module comment). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct Options { + center: bool, + radii: bool, + diameter: bool, + /// An entry of [`COLORS`]. + color: usize, + standard_anchors: bool, + drag_third: bool, +} + +impl Default for Options { + fn default() -> Self { + Options { center: true, radii: true, diameter: true, color: 1, standard_anchors: true, drag_third: true } + } +} + +impl Options { + fn switch(&mut self, key: &str) -> Option<&mut bool> { + Some(match key { + "center" => &mut self.center, + "radii" => &mut self.radii, + "diameter" => &mut self.diameter, + "standardAnchors" => &mut self.standard_anchors, + "dragThird" => &mut self.drag_third, + _ => return None, + }) + } +} + +/// Is every value in `values` one the tool takes? `tool.setOption` checks them all before setting +/// any; [`Tool::set_option`] skips a value it cannot read. +pub fn check_options(values: &Map) -> Result<(), String> { + for (key, v) in values { + if SWITCHES.contains(&key.as_str()) { + if !v.is_boolean() { + return Err(format!("`{key}` must be true or false")); + } + } else if key == "color" { + if !v.as_str().is_some_and(|s| COLORS.iter().any(|(name, _)| *name == s)) { + let names: Vec<&str> = COLORS.iter().map(|(name, _)| *name).collect(); + return Err(format!("`{key}` must be one of {}", names.join(", "))); + } + } else { + return Err(format!("unknown Circle tool option `{key}`")); + } + } + Ok(()) +} + /// The press in progress. #[derive(Clone, Copy, Debug, PartialEq)] enum Press { @@ -47,23 +121,36 @@ enum Press { /// places the third point and the circle passes through `snapped`. A press within /// [`REACH_PX`] of the first point, or one that snaps to it (`on_first`), is a press on it: let /// go there it places nothing, and dragged out it draws the circle on the diameter it drags out. + /// With `dragThird` off, a drag moves the second point and the release places it. Second { at: Point, snapped: Point, from: Point, on_first: bool, dragged: bool }, + /// With `dragThird` off, the press after the second point was placed, at `at` (snapped). Let go + /// on the second point (`on_second`), it draws the circle on the two points; let go on the + /// first point it places nothing; otherwise it draws the circle through the three points. + Third { at: Point, from: Point, on_first: bool, on_second: bool, dragged: bool }, } #[derive(Default)] pub struct CircleTool { snap: DrawSnap, + options: Options, /// The first point, placed by a click (or by the press of a drag in progress). first: Option, + /// With `dragThird` off, the second point, placed by a click where it is shown (snapped, with + /// Alt's rounding of the diameter when Alt was held), and where the click let go: a press near + /// either is a press on the second point, so the second click of a double-click finds it even + /// where Alt's rounding moved it away from the pointer. + second: Option<(Point, Point)>, press: Option, /// Where the pointer is, snapped: the point the next press or release places. pointer: Option, } -/// The command the tool runs for `points`. -fn command(points: &[Point]) -> (String, Value) { +/// The command the tool runs for `points`; with `standard_anchors` off, the circle's anchors are +/// at the points. +fn command(points: &[Point], standard_anchors: bool) -> (String, Value) { let pairs: Vec = points.iter().map(|p| json!([p.x, p.y])).collect(); - ("shape.circleThroughPoints".into(), json!({ "points": pairs })) + let params = if standard_anchors { json!({ "points": pairs }) } else { json!({ "points": pairs, "anchors": "points" }) }; + ("shape.circleThroughPoints".into(), params) } /// The circle through two points (the ends of a diameter) or three, as `shape.circleThroughPoints` @@ -73,6 +160,17 @@ pub fn circle_of(points: &[Point]) -> Option<(Point, f64)> { shapes::circle_through_points(points).filter(on_canvas) } +/// [`circle_of`], as the tool draws it: with `standard_anchors` off, also none where the path with +/// an anchor at each point ([`shapes::circle_with_anchors_at`]) reaches past the canvas, since its +/// curves can reach slightly outside the circle. +fn drawn_circle(points: &[Point], standard_anchors: bool) -> Option<(Point, f64)> { + let fits = |(c, r): &(Point, f64)| { + let b = vectorcraft_geom::Shape::bounding_box(&shapes::circle_with_anchors_at(*c, *r, points).to_bezpath()); + [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite() && v.abs() <= MAX_COORD) + }; + circle_of(points).filter(|c| standard_anchors || fits(c)) +} + /// With Alt, `p` moved along the line from `first` so that their distance (the diameter) is on /// the nearest ruler tick at the current zoom, in the General unit; `p` itself without Alt, and /// when that rounding leaves no distance. @@ -84,43 +182,65 @@ fn round_diameter(cx: &ToolContext, first: Point, p: Point, mods: Mods) -> Point /// Are the points two or more different points through which no circle is drawn: three on one /// line, or a circle that would reach past the canvas? -fn too_large(points: &[Point]) -> bool { +fn too_large(points: &[Point], standard_anchors: bool) -> bool { let distinct = points.iter().enumerate().all(|(i, p)| !points.iter().take(i).any(|q| q == p)); - points.len() >= 2 && distinct && circle_of(points).is_none() + points.len() >= 2 && distinct && drawn_circle(points, standard_anchors).is_none() } impl CircleTool { fn clear(&mut self) { self.first = None; + self.second = None; self.press = None; self.pointer = None; self.snap.clear(); } - /// How the second point keeps to the first: Shift's 45° steps and the construction guides. + /// How the second point keeps to the first: Shift's 45° steps and the construction guides. A + /// third point keeps to neither. fn leave(&self, cx: &ToolContext, mods: Mods) -> Option { - self.first.map(|a| Leave::segment(cx, a, mods.shift)) + self.first.filter(|_| self.second.is_none()).map(|a| Leave::segment(cx, a, mods.shift)) } /// The points the circle passes through as the tool shows it now. fn points(&self) -> Vec { let mut out: Vec = self.first.into_iter().collect(); + if let Some((b, _)) = self.second { + match self.press { + // Let go where it was pressed, a press on the first point draws nothing and one on + // the second point draws the circle on the two. + Some(Press::Third { on_first: true, dragged: false, .. }) => {} + Some(Press::Third { on_second: true, dragged: false, .. }) => out.push(b), + _ => { + out.push(b); + out.extend(self.pointer); + } + } + return out; + } match self.press { Some(Press::First { .. }) | None => out.extend(self.pointer.filter(|_| self.first.is_some())), // A press on the first point adds no point: a drag from it drags out a diameter. Some(Press::Second { on_first: true, dragged, .. }) => out.extend(self.pointer.filter(|_| dragged)), Some(Press::Second { at, dragged: false, .. }) => out.push(at), + // With `dragThird` off, a drag moves the second point. + Some(Press::Second { at, .. }) if !self.options.drag_third => out.push(at), Some(Press::Second { snapped, dragged: true, .. }) => { out.push(snapped); out.extend(self.pointer); } + Some(Press::Third { .. }) => {} } out } /// The second point as the tool shows it: none for a press on the first point. fn second(&self) -> Option { + if let Some((b, _)) = self.second { + return Some(b); + } match self.press { + Some(Press::Second { on_first: false, at, .. }) if !self.options.drag_third => Some(at), Some(Press::Second { on_first: false, dragged: false, at, .. }) => Some(at), Some(Press::Second { on_first: false, dragged: true, snapped, .. }) => Some(snapped), _ => None, @@ -131,18 +251,34 @@ impl CircleTool { /// (the tool showed none), it only starts afresh. fn draw(&mut self, points: &[Point]) -> Vec { self.clear(); - if circle_of(points).is_none() { + if drawn_circle(points, self.options.standard_anchors).is_none() { return vec![]; } - let (c, v) = command(points); + let (c, v) = command(points, self.options.standard_anchors); vec![Action::Exec(c, v)] } + /// With `dragThird` off, the release of a press after the second point was placed: on the + /// second point it draws the circle on the two points, on the first it places nothing, and + /// elsewhere it draws the circle through the three, or keeps the points where none passes + /// through them. + fn third_up(&mut self, at: Point, on_first: bool, on_second: bool, dragged: bool) -> Vec { + let (Some(a), Some((b, _))) = (self.first, self.second) else { return vec![] }; + if on_second && !dragged { + return self.draw(&[a, b]); + } + if (on_first && !dragged) || drawn_circle(&[a, b, at], self.options.standard_anchors).is_none() { + self.snap.clear(); + return vec![]; + } + self.draw(&[a, b, at]) + } + /// Is the press let go at `ev` a drag: is `ev` [`DRAG_PX`] or more from the press? A release /// nearer the press is a click, also after a drag that came back to it. fn drags(&self, cx: &ToolContext, ev: &PointerEvent) -> bool { match self.press { - Some(Press::First { from, .. } | Press::Second { from, .. }) => ev.pos.distance(from) >= cx.tol(DRAG_PX), + Some(Press::First { from, .. } | Press::Second { from, .. } | Press::Third { from, .. }) => ev.pos.distance(from) >= cx.tol(DRAG_PX), None => false, } } @@ -173,6 +309,13 @@ impl Tool for CircleTool { *dragged = false; (*at, *on_first) } + // With `dragThird` off, a click on the third point's press: the point goes back + // to where it was pressed. + Press::Third { at, from, dragged, .. } => { + *dragged = false; + *at = self.snap.press(cx, *from, &[], None); + (*at, false) + } }; // A click on the first point places nothing: the pointer goes back to that point, so // the tool shows no circle. @@ -184,10 +327,27 @@ impl Tool for CircleTool { PointerKind::Move => { let leave = self.leave(cx, ev.mods); let p = self.snap.hover(cx, ev.pos, &[], leave.as_ref()); - self.pointer = Some(self.first.map_or(p, |a| round_diameter(cx, a, p, ev.mods))); + // Alt's rounding of the diameter is for the second point only. + let rounds = self.first.filter(|_| self.second.is_none()); + self.pointer = Some(rounds.map_or(p, |a| round_diameter(cx, a, p, ev.mods))); vec![] } PointerKind::Down => { + if let (Some(a), Some((b, clicked))) = (self.first, self.second) { + let at = self.snap.press(cx, ev.pos, &[], None); + let reach = cx.tol(REACH_PX); + let to_second = ev.pos.distance(b).min(ev.pos.distance(clicked)); + let (mut on_first, mut on_second) = (at == a || ev.pos.distance(a) <= reach, at == b || to_second <= reach); + // A press in reach of both points is on the one it snapped to, otherwise on the + // nearer one. + if on_first && on_second { + let first = if (at == a) != (at == b) { at == a } else { ev.pos.distance(a) < to_second }; + (on_first, on_second) = (first, !first); + } + self.press = Some(Press::Third { at, from: ev.pos, on_first, on_second, dragged: false }); + self.pointer = Some(at); + return vec![]; + } match self.first { None => { let at = self.snap.press(cx, ev.pos, &[], None); @@ -207,7 +367,28 @@ impl Tool for CircleTool { vec![] } PointerKind::Drag => { + let drag_third = self.options.drag_third; + let first = self.first; match &mut self.press { + // With `dragThird` off, the second point follows the pointer as it does before + // the press. + // The point stays where it was pressed until the press is a drag. + Some(Press::Second { at, snapped, from, on_first: false, dragged }) if !drag_third => { + *dragged |= ev.pos.distance(*from) >= cx.tol(DRAG_PX); + if *dragged { + let leave = first.map(|a| Leave::segment(cx, a, ev.mods.shift)); + *snapped = self.snap.drag(cx, ev.pos, leave.as_ref()); + *at = first.map_or(*snapped, |a| round_diameter(cx, a, *snapped, ev.mods)); + self.pointer = Some(*at); + } + } + Some(Press::Third { at, from, dragged, .. }) => { + *dragged |= ev.pos.distance(*from) >= cx.tol(DRAG_PX); + if *dragged { + *at = self.snap.drag(cx, ev.pos, None); + self.pointer = Some(*at); + } + } Some(Press::First { at, from, dragged }) => { *dragged |= ev.pos.distance(*from) >= cx.tol(DRAG_PX); let leave = Leave::segment(cx, *at, ev.mods.shift); @@ -230,6 +411,16 @@ impl Tool for CircleTool { vec![] } PointerKind::Up => match (self.press.take(), self.first, self.pointer) { + (Some(Press::Third { at, on_first, on_second, dragged, .. }), ..) => self.third_up(at, on_first, on_second, dragged), + // With `dragThird` off, the release places the second point; let go on the first + // point, as a press there is, it places nothing. + (Some(Press::Second { at, snapped, on_first: false, .. }), Some(a), _) if !self.options.drag_third => { + if !(at == a || snapped == a || ev.pos.distance(a) <= cx.tol(REACH_PX)) { + self.second = Some((at, ev.pos)); + } + self.snap.clear(); + vec![] + } (Some(Press::First { at, dragged: true, .. }), _, Some(b)) if b.distance(at) >= cx.tol(DRAG_PX) => self.draw(&[at, b]), // A click places the first point; the guides of the press go. (Some(Press::First { .. }), ..) => { @@ -296,22 +487,33 @@ impl Tool for CircleTool { let mut o = self.snap.guides().to_vec(); let points = self.points(); let color = crate::draw2::FEEDBACK; - if let Some((c, r)) = circle_of(&points) { - let path = shapes::ellipse(Rect::new(c.x - r, c.y - r, c.x + r, c.y + r)).to_bezpath(); + if let Some((c, r)) = drawn_circle(&points, self.options.standard_anchors) { + // The path the release draws: with `standardAnchors` off, the one with an anchor at each point. + let path = if self.options.standard_anchors { + shapes::ellipse(Rect::new(c.x - r, c.y - r, c.x + r, c.y + r)).to_bezpath() + } else { + shapes::circle_with_anchors_at(c, r, &points).to_bezpath() + }; // The canvas draws a dashed outline dash by dash along its whole length: a circle longer // than DASHED_PX on screen is drawn solid instead. let dashed = std::f64::consts::TAU * r <= cx.tol(DASHED_PX); o.push(Overlay::Path { path, color, width: 1.0, dashed }); - for p in &points { - o.push(Overlay::Line { a: c, b: *p, color, dashed: false }); + let opts = self.options; + let lines = COLORS.get(opts.color).map_or(color, |(_, rgb)| *rgb); + if opts.radii { + for p in &points { + o.push(Overlay::Line { a: c, b: *p, color: lines, dashed: false }); + } } - let arm = cx.tol(CROSS_PX); - o.push(Overlay::Line { a: c - Vec2::new(arm, 0.0), b: c + Vec2::new(arm, 0.0), color, dashed: false }); - o.push(Overlay::Line { a: c - Vec2::new(0.0, arm), b: c + Vec2::new(0.0, arm), color, dashed: false }); - if let Some(p) = self.pointer.filter(|_| cx.measurement_labels) { + if opts.center { + let arm = cx.tol(CROSS_PX); + o.push(Overlay::Line { a: c - Vec2::new(arm, 0.0), b: c + Vec2::new(arm, 0.0), color: lines, dashed: false }); + o.push(Overlay::Line { a: c - Vec2::new(0.0, arm), b: c + Vec2::new(0.0, arm), color: lines, dashed: false }); + } + if let Some(p) = self.pointer.filter(|_| cx.measurement_labels && opts.diameter) { o.push(Overlay::Measure { p: p + Vec2::new(cx.tol(12.0), cx.tol(12.0)), text: format!("D: {}", cx.len(2.0 * r)) }); } - } else if let Some(p) = self.pointer.filter(|_| too_large(&points)) { + } else if let Some(p) = self.pointer.filter(|_| too_large(&points, self.options.standard_anchors)) { o.push(Overlay::Label { p, text: "Circle too large".into(), color }); } for p in self.first.into_iter().chain(self.second()) { @@ -323,6 +525,43 @@ impl Tool for CircleTool { fn cursor(&self, _cx: &ToolContext, _p: Point, _mods: Mods) -> Cursor { Cursor::Crosshair } + + fn options(&self) -> Value { + let o = self.options; + let color = COLORS.get(o.color).map_or("blue", |(name, _)| *name); + json!({ + "center": o.center, + "radii": o.radii, + "diameter": o.diameter, + "color": color, + "standardAnchors": o.standard_anchors, + "dragThird": o.drag_third, + }) + } + + /// Takes the values [`check_options`] takes. + fn check_option(&self, key: &str, value: &Value) -> Result<(), String> { + check_options(&Map::from_iter([(key.to_string(), value.clone())])) + } + + /// Sets one option; a value the option does not take leaves it as it was. Switching + /// `dragThird` drops the points placed so far. + fn set_option(&mut self, key: &str, value: &Value) { + if key == "color" { + if let Some(i) = value.as_str().and_then(|s| COLORS.iter().position(|(name, _)| *name == s)) { + self.options.color = i; + } + return; + } + let Some(on) = value.as_bool() else { return }; + let was = self.options.drag_third; + if let Some(switch) = self.options.switch(key) { + *switch = on; + } + if self.options.drag_third != was { + self.clear(); + } + } } #[cfg(test)] diff --git a/crates/tools/src/circle/tests.rs b/crates/tools/src/circle/tests.rs index 9d68bdbe27..4e700b6c3b 100644 --- a/crates/tools/src/circle/tests.rs +++ b/crates/tools/src/circle/tests.rs @@ -94,6 +94,302 @@ fn a_click_and_a_drag_draw_the_circle_through_three_points() { assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, (300.0, 360.0), Mods::default())), circle(&[(300.0, 300.0), (380.0, 300.0), (300.0, 360.0)])); } +/// The lines the tool shows from the center `c`: (radius lines, arms of the center cross), each +/// with its color. +fn annotations(o: &[Overlay], c: Point) -> (Vec<[u8; 3]>, Vec<[u8; 3]>) { + let (mut radii, mut cross) = (vec![], vec![]); + for o in o { + if let Overlay::Line { a, b, color, .. } = o { + if *a == c { + radii.push(*color); + } else if a.midpoint(*b).distance(c) < 1e-9 { + cross.push(*color); + } + } + } + (radii, cross) +} + +/// `center`, `radii` and `diameter` show or hide the center cross, the radius lines and the +/// diameter label, each on its own, and `color` is the color of the cross and the lines; the +/// outline stays in the feedback color. Each option lasts in [`Tool::options`]. +#[test] +fn the_options_show_or_hide_the_center_radii_and_diameter_in_their_color() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = CircleTool::default(); + click(&mut t, &cx, (300.0, 300.0)); + t.pointer(&cx, &ev(PointerKind::Move, (380.0, 360.0), Mods::default())); + let c = Point::new(340.0, 330.0); + let blue = crate::draw2::FEEDBACK; + assert_eq!(annotations(&t.overlays(&cx), c), (vec![blue; 2], vec![blue; 2])); + let diameter = |t: &CircleTool| t.overlays(&cx).iter().any(|o| matches!(o, Overlay::Measure { .. })); + assert!(diameter(&t)); + t.set_option("center", &json!(false)); + assert_eq!(annotations(&t.overlays(&cx), c), (vec![blue; 2], vec![])); + t.set_option("radii", &json!(false)); + assert_eq!(annotations(&t.overlays(&cx), c), (vec![], vec![])); + assert!(diameter(&t)); + t.set_option("diameter", &json!(false)); + assert!(!diameter(&t)); + t.set_option("center", &json!(true)); + t.set_option("radii", &json!(true)); + t.set_option("color", &json!("red")); + let red = [0xe5, 0x2d, 0x27]; + let o = t.overlays(&cx); + assert_eq!(annotations(&o, c), (vec![red; 2], vec![red; 2])); + assert!(o.iter().any(|o| matches!(o, Overlay::Path { color, .. } if *color == blue)), "{o:?}"); + assert_eq!(t.options(), json!({"center": true, "radii": true, "diameter": false, "color": "red", "standardAnchors": true, "dragThird": true})); + // A value an option does not take leaves it as it was. + for (key, value) in [("color", json!("orange")), ("center", json!("no")), ("radii", json!(0))] { + t.set_option(key, &value); + } + assert_eq!(t.options()["color"], json!("red")); + assert_eq!((&t.options()["center"], &t.options()["radii"]), (&json!(true), &json!(true))); +} + +/// With `standardAnchors` off, the circle's anchors go at the points it was drawn through. +#[test] +fn anchors_at_the_points_asks_for_them() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = CircleTool::default(); + t.set_option("standardAnchors", &json!(false)); + let acts = drag(&mut t, &cx, (300.0, 300.0), &[(380.0, 360.0)], Mods::default()); + let points = json!([[300.0, 300.0], [380.0, 360.0]]); + assert_eq!(acts, vec![Action::Exec("shape.circleThroughPoints".into(), json!({"points": points, "anchors": "points"}))]); +} + +/// With `standardAnchors` off, the tool shows the path with an anchor at each point, the one its +/// release draws. +#[test] +fn anchors_at_the_points_show_the_path_they_draw() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = CircleTool::default(); + t.set_option("standardAnchors", &json!(false)); + click(&mut t, &cx, (300.0, 300.0)); + t.pointer(&cx, &ev(PointerKind::Down, (380.0, 300.0), Mods::default())); + t.pointer(&cx, &ev(PointerKind::Drag, (310.0, 340.0), Mods::default())); + let points = [Point::new(300.0, 300.0), Point::new(380.0, 300.0), Point::new(310.0, 340.0)]; + let (c, r) = circle_of(&points).expect("a circle"); + let want = shapes::circle_with_anchors_at(c, r, &points).to_bezpath(); + let o = t.overlays(&cx); + assert!(o.iter().any(|o| matches!(o, Overlay::Path { path, .. } if *path == want)), "{o:?}"); +} + +/// With `standardAnchors` off, a circle within 1 pt of the canvas edge whose path with anchors at +/// the points curves past that edge is not shown and not drawn; with standard anchors it is. +#[test] +fn anchors_at_the_points_keep_the_path_on_the_canvas() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let r = MAX_COORD - 1.0; + let at = |deg: f64| (r * deg.to_radians().cos(), r * deg.to_radians().sin()); + let points = [at(0.0), at(70.0), at(180.0)]; + let geom: Vec = points.iter().map(|(x, y)| Point::new(*x, *y)).collect(); + assert!(drawn_circle(&geom, true).is_some()); + assert_eq!(drawn_circle(&geom, false), None); + let mut t = CircleTool::default(); + t.set_option("standardAnchors", &json!(false)); + click(&mut t, &cx, points[0]); + t.pointer(&cx, &ev(PointerKind::Down, points[1], Mods::default())); + t.pointer(&cx, &ev(PointerKind::Drag, points[2], Mods::default())); + // No outline at all: at this size the tool would draw it solid, not dashed. + let o = t.overlays(&cx); + assert!(!o.iter().any(|o| matches!(o, Overlay::Path { .. })), "{o:?}"); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, points[2], Mods::default())), vec![]); +} + +/// With `dragThird` off, a click in reach of both placed points is on the nearer one: nearer the +/// first point it places nothing, nearer the second it draws the circle on the two. +#[test] +fn with_third_point_by_dragging_off_a_click_near_both_points_takes_the_nearer() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = CircleTool::default(); + t.set_option("dragThird", &json!(false)); + click(&mut t, &cx, (100.0, 100.0)); + assert_eq!(click(&mut t, &cx, (104.0, 100.0)), vec![]); + assert_eq!(click(&mut t, &cx, (101.0, 100.0)), vec![]); + assert_eq!(click(&mut t, &cx, (103.0, 100.0)), circle(&[(100.0, 100.0), (104.0, 100.0)])); +} + +/// With `dragThird` off, a press on the second point shows the circle on the two points, which its +/// release draws, and a press on the first point shows none. +#[test] +fn with_third_point_by_dragging_off_a_press_shows_the_circle_its_release_draws() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = CircleTool::default(); + t.set_option("dragThird", &json!(false)); + click(&mut t, &cx, (100.0, 100.0)); + click(&mut t, &cx, (200.0, 100.0)); + t.pointer(&cx, &ev(PointerKind::Down, (101.0, 101.0), Mods::default())); + assert_eq!(preview(&t.overlays(&cx)), None); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, (101.0, 101.0), Mods::default())), vec![]); + t.pointer(&cx, &ev(PointerKind::Down, (202.0, 101.0), Mods::default())); + let o = t.overlays(&cx); + assert!(near(preview(&o).expect("the circle is shown"), Rect::new(100.0, 50.0, 200.0, 150.0)), "{o:?}"); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, (202.0, 101.0), Mods::default())), circle(&[(100.0, 100.0), (200.0, 100.0)])); +} + +/// With `dragThird` off, a press that moves less than 2 screen points keeps the point where it was +/// pressed, for the second point and for the third. +#[test] +fn with_third_point_by_dragging_off_a_short_move_keeps_the_pressed_point() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let (down, drag, up) = (PointerKind::Down, PointerKind::Drag, PointerKind::Up); + let mut t = CircleTool::default(); + t.set_option("dragThird", &json!(false)); + click(&mut t, &cx, (100.0, 100.0)); + t.pointer(&cx, &ev(down, (200.0, 100.0), Mods::default())); + t.pointer(&cx, &ev(drag, (201.0, 100.0), Mods::default())); + assert_eq!(t.pointer(&cx, &ev(up, (200.0, 100.0), Mods::default())), vec![]); + t.pointer(&cx, &ev(down, (150.0, 200.0), Mods::default())); + t.pointer(&cx, &ev(drag, (151.0, 200.0), Mods::default())); + let three = circle(&[(100.0, 100.0), (200.0, 100.0), (150.0, 200.0)]); + assert_eq!(t.pointer(&cx, &ev(up, (150.0, 200.0), Mods::default())), three); +} + +/// With `dragThird` off, a second click places the second point and a third click draws the circle +/// through the three; a click on the second point again (as a double-click there does) draws the +/// circle on the two; a second point let go on the first places nothing; a drag from the first +/// point still draws the circle on its diameter. +#[test] +fn with_third_point_by_dragging_off_three_clicks_draw_the_circle() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = CircleTool::default(); + t.set_option("dragThird", &json!(false)); + click(&mut t, &cx, (300.0, 300.0)); + assert_eq!(click(&mut t, &cx, (380.0, 300.0)), vec![]); + t.pointer(&cx, &ev(PointerKind::Move, (300.0, 360.0), Mods::default())); + let o = t.overlays(&cx); + assert!(near(preview(&o).expect("the circle through the three is shown"), Rect::new(290.0, 280.0, 390.0, 380.0)), "{o:?}"); + assert_eq!(o.iter().filter(|o| matches!(o, Overlay::Anchor { .. })).count(), 2, "{o:?}"); + // A click on the first point places nothing and keeps both points. + assert_eq!(click(&mut t, &cx, (300.0, 300.0)), vec![]); + assert!(t.busy()); + assert_eq!(click(&mut t, &cx, (300.0, 360.0)), circle(&[(300.0, 300.0), (380.0, 300.0), (300.0, 360.0)])); + assert!(!t.busy()); + // The events of a double-click on the second point: its first click places it, the second + // draws the circle on the two points, and the double-click event that follows adds nothing. + click(&mut t, &cx, (100.0, 100.0)); + assert_eq!(click(&mut t, &cx, (200.0, 100.0)), vec![]); + assert_eq!(click(&mut t, &cx, (200.0, 100.0)), circle(&[(100.0, 100.0), (200.0, 100.0)])); + assert_eq!(t.pointer(&cx, &ev(PointerKind::DoubleClick, (200.0, 100.0), Mods::default())), vec![]); + assert!(!t.busy()); + // A drag that moves the second point places it where it is let go. + click(&mut t, &cx, (100.0, 100.0)); + assert_eq!(drag(&mut t, &cx, (150.0, 100.0), &[(180.0, 100.0), (200.0, 100.0)], Mods::default()), vec![]); + assert_eq!(click(&mut t, &cx, (100.0, 200.0)), circle(&[(100.0, 100.0), (200.0, 100.0), (100.0, 200.0)])); + // Three points on one line keep the two placed: the next click elsewhere draws. + click(&mut t, &cx, (100.0, 100.0)); + click(&mut t, &cx, (200.0, 100.0)); + assert_eq!(click(&mut t, &cx, (300.0, 100.0)), vec![]); + assert_eq!(click(&mut t, &cx, (100.0, 200.0)), circle(&[(100.0, 100.0), (200.0, 100.0), (100.0, 200.0)])); + // A second press elsewhere, dragged back and let go on the first point, places nothing: the + // next click places the second point. + click(&mut t, &cx, (100.0, 100.0)); + assert_eq!(drag(&mut t, &cx, (200.0, 100.0), &[(150.0, 100.0), (100.0, 100.0)], Mods::default()), vec![]); + assert!(t.busy()); + assert_eq!(click(&mut t, &cx, (200.0, 100.0)), vec![]); + assert_eq!(click(&mut t, &cx, (100.0, 200.0)), circle(&[(100.0, 100.0), (200.0, 100.0), (100.0, 200.0)])); + // A drag from the first point. + assert_eq!(drag(&mut t, &cx, (300.0, 300.0), &[(380.0, 360.0)], Mods::default()), circle(&[(300.0, 300.0), (380.0, 360.0)])); + // Switching the option drops the points placed so far. + click(&mut t, &cx, (100.0, 100.0)); + t.set_option("dragThird", &json!(true)); + assert!(!t.busy()); +} + +/// With `dragThird` off, a drag of the second or third point ends where it is let go, also when the +/// release is away from the last drag. +#[test] +fn with_third_point_by_dragging_off_a_drag_ends_where_it_is_let_go() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let (down, drag, up) = (PointerKind::Down, PointerKind::Drag, PointerKind::Up); + let mut t = CircleTool::default(); + t.set_option("dragThird", &json!(false)); + click(&mut t, &cx, (300.0, 300.0)); + t.pointer(&cx, &ev(down, (350.0, 300.0), Mods::default())); + t.pointer(&cx, &ev(drag, (380.0, 300.0), Mods::default())); + assert_eq!(t.pointer(&cx, &ev(up, (400.0, 300.0), Mods::default())), vec![]); + t.pointer(&cx, &ev(down, (350.0, 350.0), Mods::default())); + t.pointer(&cx, &ev(drag, (320.0, 380.0), Mods::default())); + assert_eq!(t.pointer(&cx, &ev(up, (300.0, 400.0), Mods::default())), circle(&[(300.0, 300.0), (400.0, 300.0), (300.0, 400.0)])); +} + +/// With `dragThird` off, an Alt-click places the second point where Alt's rounding of the diameter +/// puts it (88 pt rounds to 90 pt at 100%), and the tool shows it there: the marker, the preview, +/// the circle on the two points and the circle through three all use it. +#[test] +fn an_alt_click_places_the_second_point_where_it_is_shown() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let alt = Mods { alt: true, ..Mods::default() }; + let mut t = CircleTool::default(); + t.set_option("dragThird", &json!(false)); + click(&mut t, &cx, (300.0, 300.0)); + t.pointer(&cx, &ev(PointerKind::Down, (388.0, 300.0), alt)); + t.pointer(&cx, &ev(PointerKind::Up, (388.0, 300.0), alt)); + t.pointer(&cx, &ev(PointerKind::Move, (300.0, 390.0), Mods::default())); + let o = t.overlays(&cx); + let second = Point::new(390.0, 300.0); + assert!(o.iter().any(|o| matches!(o, Overlay::Anchor { p, .. } if p.distance(second) < 1e-9)), "{o:?}"); + // (300, 300), (390, 300) and (300, 390): center (345, 345), radius 45·√2. + let r = 45.0 * 2f64.sqrt(); + assert!(near(preview(&o).unwrap(), Rect::new(345.0 - r, 345.0 - r, 345.0 + r, 345.0 + r)), "{o:?}"); + assert_eq!(click(&mut t, &cx, (300.0, 390.0)), circle(&[(300.0, 300.0), (390.0, 300.0), (300.0, 390.0)])); + click(&mut t, &cx, (300.0, 300.0)); + t.pointer(&cx, &ev(PointerKind::Down, (388.0, 300.0), alt)); + t.pointer(&cx, &ev(PointerKind::Up, (388.0, 300.0), alt)); + assert_eq!(click(&mut t, &cx, (390.0, 300.0)), circle(&[(300.0, 300.0), (390.0, 300.0)])); + // In inches the ticks are farther apart, and the rounding can move the point more than the + // 3 screen points a click reaches: the second click of a double-click, where the first let go, + // still draws the circle on the two points, at the rounded point. + let inches = ToolContext { unit: vectorcraft_doc::Unit::Inches, ..cx }; + let d = 94.4; + let rounded = vectorcraft_doc::Unit::Inches.snap_to_ruler_tick(d, 1.0); + assert!((rounded - d).abs() > 3.0, "{rounded}"); + click(&mut t, &inches, (300.0, 300.0)); + t.pointer(&inches, &ev(PointerKind::Down, (300.0 + d, 300.0), alt)); + t.pointer(&inches, &ev(PointerKind::Up, (300.0 + d, 300.0), alt)); + assert_eq!(click(&mut t, &inches, (300.0 + d, 300.0)), circle(&[(300.0, 300.0), (300.0 + rounded, 300.0)])); +} + +/// `tool.setOption`'s check takes the values the options take and nothing else. +#[test] +fn check_options_takes_only_the_values_the_options_take() { + let ok = json!({"center": false, "radii": true, "diameter": false, "color": "gray", "standardAnchors": false, "dragThird": false}); + assert_eq!(check_options(ok.as_object().unwrap()), Ok(())); + // The tool's own check, which `tool.setOption` also runs, takes the same values. + let tool = CircleTool::default(); + assert_eq!(tool.check_options(ok.as_object().unwrap()), Ok(())); + for (bad, error) in [ + (json!({"center": 1}), "`center` must be true or false"), + (json!({"dragThird": null}), "`dragThird` must be true or false"), + (json!({"color": "orange"}), "`color` must be one of red, blue, magenta, green, black, gray"), + (json!({"colour": "red"}), "unknown Circle tool option `colour`"), + ] { + assert_eq!(check_options(bad.as_object().unwrap()), Err(error.to_string()), "{bad}"); + assert_eq!(tool.check_options(bad.as_object().unwrap()), Err(error.to_string()), "{bad}"); + } +} + /// A drag ends where it is let go, also when the release is away from the last drag: from a first /// press, from a second press, and from a press on the first point. A release within 2 screen /// points of a second press is still a click and keeps the point of the press. @@ -288,8 +584,8 @@ fn points_on_one_line_say_the_circle_is_too_large() { assert_eq!(label(&t), None, "a circle is shown"); t.pointer(&cx, &ev(PointerKind::Drag, (200.0, 200.0), Mods::default())); assert_eq!(label(&t), None, "the third point is on the second"); - assert!(too_large(&[Point::new(0.0, 0.0), Point::new(4.1e6, 0.0)])); - assert!(!too_large(&[Point::new(0.0, 0.0)]) && !too_large(&[Point::new(1.0, 0.0), Point::new(1.0, 0.0)])); + assert!(too_large(&[Point::new(0.0, 0.0), Point::new(4.1e6, 0.0)], true)); + assert!(!too_large(&[Point::new(0.0, 0.0)], true) && !too_large(&[Point::new(1.0, 0.0), Point::new(1.0, 0.0)], true)); } /// Escape drops the first point; so do a dropped press and an edit made outside the tool. A diff --git a/crates/tools/src/direct.rs b/crates/tools/src/direct.rs index e1c0c88dae..cd4432c3c8 100644 --- a/crates/tools/src/direct.rs +++ b/crates/tools/src/direct.rs @@ -78,6 +78,8 @@ struct HandleDrag { offset: Vec2, space: bool, independent: bool, + /// The opposite handle mirrors this one ([`DirectSelectionTool::mirrors`]). + symmetric: bool, translated: bool, } @@ -261,9 +263,27 @@ pub struct DirectSelectionTool { frame_click: Option<(NodeId, AnchorRef)>, /// Where the pointer last hovered: the type on a path bracket under it draws thicker. bracket_hover: Option, + /// The Cmd/Ctrl press that lent this tool for one gesture (`lentByCmd`) is still + /// held: it does not mirror a dragged handle. Once Cmd/Ctrl is let go, pressing it again does. + lent_cmd: bool, } impl DirectSelectionTool { + /// Whether a handle drag with `ev`'s modifiers mirrors the opposite handle: Cmd/Ctrl held + /// without Alt, unless it is still the press that lent this tool for one gesture while another + /// tool, such as the Pen, is chosen. + fn mirrors(&self, ev: &PointerEvent) -> bool { + ev.mods.cmd && !ev.mods.alt && !self.lent_cmd + } + + /// Forget the lending Cmd/Ctrl once an event comes without it. The session takes Cmd/Ctrl off + /// the press it lends the tool for, while the drags after it still carry it. + fn track_lent_cmd(&mut self, ev: &PointerEvent) { + if ev.kind != PointerKind::Down { + self.lent_cmd &= ev.mods.cmd; + } + } + pub fn new(group: bool) -> Self { Self { group, @@ -291,6 +311,7 @@ impl DirectSelectionTool { frame_revision: (0, 0), frame_click: None, bracket_hover: None, + lent_cmd: false, } } @@ -441,6 +462,21 @@ fn spine_anchor(cx: &ToolContext, (id, ai): (NodeId, usize)) -> Option Vec { + let q = if symmetric && ev.mods.shift { + spine_anchor(cx, (id, anchor)).map_or(p, |a| a.p + vectorcraft_geom::constrain_angle_from(p - a.p, 45.0, cx.constrain_angle)) + } else { + p + }; + let mut params = json!({"id": id.0, "anchor": anchor, "handle": if out {"out"} else {"in"}, "x": q.x, "y": q.y, "independent": ev.mods.alt}); + if symmetric { + params["symmetric"] = json!(true); + } + vec![Action::Preview("object.blend.spine.moveAnchor".into(), params)] +} + /// Blend `id`'s spine, built once for callers that look up several of its points. fn spine_path(cx: &ToolContext, id: NodeId) -> Option { match &cx.doc.node(id)?.kind { @@ -789,10 +825,15 @@ impl Tool for DirectSelectionTool { } /// Direct Selection picks the gradient mesh points the Eyedropper held (`meshPoints`); Group /// Selection, which selects whole objects, does not. + /// The session sets `lentByCmd` on the tool Cmd/Ctrl lends for one gesture + /// ([`DirectSelectionTool::mirrors`]). fn set_option(&mut self, key: &str, value: &Value) { if key == "meshPoints" && !self.group { self.mesh.set_options(value); } + if key == "lentByCmd" { + self.lent_cmd = value.as_bool().unwrap_or(false); + } } /// Escape during a drag (anchors, handles, segments, objects, type areas, blend spines, mesh /// points, corner widgets, the brackets of type on a path, a marquee) cancels it: what it moved @@ -851,6 +892,7 @@ impl Tool for DirectSelectionTool { } fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec { self.bracket_hover = (ev.kind == PointerKind::Move).then_some(ev.pos); + self.track_lent_cmd(ev); if let Some(out) = self.guide.pointer(cx, ev) { return out; } @@ -908,6 +950,7 @@ impl Tool for DirectSelectionTool { offset: Vec2::ZERO, space: false, independent: false, + symmetric: false, translated: false, }) } @@ -1012,10 +1055,11 @@ impl Tool for DirectSelectionTool { self.snapped = snapped(q.to_vec2(), p.to_vec2(), ev.mods.shift, &guides); self.guides = guides; let cmd = if cx.doc.node(id).is_some_and(is_path_type) { "text.setPathHandle" } else { "path.setHandle" }; - vec![Action::Preview( - cmd.into(), - json!({"id": id.0, "subpath": si, "anchor": ai, "which": if out {"out"} else {"in"}, "x": q.x, "y": q.y, "independent": ev.mods.alt}), - )] + let mut params = json!({"id": id.0, "subpath": si, "anchor": ai, "which": if out {"out"} else {"in"}, "x": q.x, "y": q.y, "independent": ev.mods.alt}); + if self.mirrors(ev) { + params["symmetric"] = json!(true); + } + vec![Action::Preview(cmd.into(), params)] } (PointerKind::Drag, State::SpinePoint { id, anchor, from, start, began }) => { let mut out = vec![]; @@ -1053,10 +1097,7 @@ impl Tool for DirectSelectionTool { )); out } - (PointerKind::Drag, State::SpineHandle { id, anchor, out }) => vec![Action::Preview( - "object.blend.spine.moveAnchor".into(), - json!({"id": id.0, "anchor": anchor, "handle": if out {"out"} else {"in"}, "x": p.x, "y": p.y, "independent": ev.mods.alt}), - )], + (PointerKind::Drag, State::SpineHandle { id, anchor, out }) => drag_spine_handle(cx, ev, (id, anchor, out), p, self.mirrors(ev)), (PointerKind::Drag, State::Mesh) => self.mesh.drag_to(p).unwrap_or_default(), (PointerKind::Up, State::Mesh) => { self.state = State::Idle; @@ -1568,15 +1609,20 @@ impl DirectSelectionTool { self.snapped = snapped(q.to_vec2(), input.to_vec2(), ev.mods.shift, &guides); self.guides = guides; drag.handle = q; - drag.independent = ev.mods.alt; } } + // Alt and Cmd/Ctrl take effect on every event, while Space is held too. + drag.independent = ev.mods.alt; + drag.symmetric = self.mirrors(ev); drag.last = p; drag.space = ev.mods.space; let mut params = json!({ "id": id.0, "subpath": si, "anchor": ai, "which": if out { "out" } else { "in" }, "x": drag.handle.x, "y": drag.handle.y, "independent": drag.independent, }); + if drag.symmetric { + params["symmetric"] = json!(true); + } if drag.translated { params["at"] = json!([drag.at.x, drag.at.y]); } @@ -1611,7 +1657,7 @@ impl DirectSelectionTool { // The grabbed anchor snaps and the others follow it. Shift keeps the move at its // angle, and the anchor slides along it onto what Smart Guides find there (#886). self.guides.clear(); - if segment && let Some(grid) = &self.partial_grid { + if segment && let Some(grid) = &mut self.partial_grid { (d, self.guides) = if ev.mods.shift { grid.snap_along(cx, grab, d, false) } else { grid.snap(cx, grab, d, false) }; } else if let Some(snap) = &self.anchor_snap { let shift = ev.mods.shift.then(|| Leave::segment(cx, grab, true)); @@ -1664,7 +1710,7 @@ impl DirectSelectionTool { && let Some(snap) = &self.partial_snap { let held = grab.unwrap_or(hold); - if let Some(grid) = &self.partial_grid { + if let Some(grid) = &mut self.partial_grid { (d, self.guides) = if ev.mods.shift { grid.snap_along(cx, held, d, false) } else { grid.snap(cx, held, d, false) }; } else { let shift = ev.mods.shift.then(|| Leave::segment(cx, held, true)); @@ -1684,7 +1730,7 @@ impl DirectSelectionTool { let shift = ev.mods.shift.then(|| Leave::segment(cx, grab, true)); let (q, guides) = snap.snap_from(cx, grab + (p - start), shift.as_ref()); (d, self.guides) = (q - grab, guides); - } else if let Some(snap) = &self.move_snap { + } else if let Some(snap) = &mut self.move_snap { (d, self.guides) = if ev.mods.shift { snap.snap_along(cx, hold, d, ev.mods.alt) } else { snap.snap(cx, hold, d, ev.mods.alt) }; } self.snapped = snapped(d, unsnapped, ev.mods.shift, &self.guides); diff --git a/crates/tools/src/draw2/anchor.rs b/crates/tools/src/draw2/anchor.rs index 1fe1fd72f3..66e2eea0b0 100644 --- a/crates/tools/src/draw2/anchor.rs +++ b/crates/tools/src/draw2/anchor.rs @@ -16,9 +16,9 @@ use serde_json::json; use vectorcraft_doc::NodeId; -use vectorcraft_geom::Point; +use vectorcraft_geom::{ParamCurve, Point}; -use super::{hit_anchor, hit_segment, insert_anchor, remove_anchor}; +use super::{FEEDBACK, hit_anchor, hit_segment, insert_anchor, remove_anchor}; use crate::direct::hit_handle; use crate::guides::{DrawSnap, HandleSnap}; use crate::{Action, Cursor, Mods, Overlay, PixelOp, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; @@ -95,10 +95,48 @@ enum SpaceResume { SpineHandle { id: NodeId, ai: usize, out: bool }, } +/// A cut chosen with the same anchor/segment priority for preview and press. +enum ScissorsCut { + Anchor { id: NodeId, si: usize, ai: usize }, + Segment { id: NodeId, si: usize, seg: usize, t: f64 }, +} + +impl ScissorsCut { + fn point(&self, cx: &ToolContext) -> Option { + let (id, si) = match *self { + Self::Anchor { id, si, .. } | Self::Segment { id, si, .. } => (id, si), + }; + let sp = cx.doc.node(id)?.path_data()?.subpaths.get(si)?; + if sp.anchors.len() < 2 { + return None; + } + let ai = match *self { + Self::Anchor { ai, .. } => ai, + Self::Segment { seg, t, .. } => { + if seg >= sp.segment_count() || !(0.0..=1.0).contains(&t) { + return None; + } + // path.split canonicalizes cuts near segment ends to the existing anchor. + if t <= 1e-6 { + seg + } else if t >= 1.0 - 1e-6 { + (seg + 1) % sp.anchors.len() + } else { + return Some(sp.segment(seg).eval(t)); + } + } + }; + let anchor = sp.anchors.get(ai)?; + // An open path cannot be split at either of its existing end points. + (sp.closed || (ai > 0 && ai + 1 < sp.anchors.len())).then_some(anchor.p) + } +} + /// The cursor reuses the last hover's point, with DrawSnap checking its target inputs. The /// Scissors-only inputs also bind the resolved point to the current cut eligibility. struct ScissorsHover { raw: Point, + shared: Point, snapped: Point, zoom: f64, isolation: Option, @@ -160,7 +198,7 @@ impl AnchorTool { /// Keep a shared art snap unless it prevents a cut the raw pointer could make. Outside art /// still supplies alignment and intersection guides; pixel and grid snapping keep precedence. - fn resolve_scissors_snap(&mut self, cx: &ToolContext, raw: Point, snapped: Point) -> Point { + fn scissors_point(cx: &ToolContext, raw: Point, snapped: Point) -> (Point, bool) { let eligible = |p| hit_anchor(cx, p, 0.0).is_some() || hit_segment(cx, p, cx.pick_tol()).is_some(); let fallback = (cx.smart_guides || cx.snap_to_point) && !cx.snaps_to_pixel(PixelOp::Drawing) @@ -168,14 +206,16 @@ impl AnchorTool { && snapped != raw && !eligible(snapped) && eligible(raw); - let snapped = if fallback { + (if fallback { raw } else { snapped }, fallback) + } + + fn resolve_scissors_snap(&mut self, cx: &ToolContext, raw: Point, shared: Point) -> Point { + let (snapped, fallback) = Self::scissors_point(cx, raw, shared); + if fallback { self.scissors_snap.clear(); - raw - } else { - snapped - }; + } self.scissors_hover = - Some(ScissorsHover { raw, snapped, zoom: cx.zoom, isolation: cx.isolation, selection_tolerance: cx.selection_tolerance }); + Some(ScissorsHover { raw, shared, snapped, zoom: cx.zoom, isolation: cx.isolation, selection_tolerance: cx.selection_tolerance }); snapped } @@ -198,18 +238,27 @@ impl AnchorTool { } let snapped = self.scissors_snap.press(cx, p, &[], None); let p = self.resolve_scissors_snap(cx, p, snapped); + match Self::scissors_cut(cx, p) { + Some(ScissorsCut::Anchor { id, si, ai }) => { + vec![Action::Exec("path.split".into(), json!({"id": id.0, "subpath": si, "anchor": ai}))] + } + Some(ScissorsCut::Segment { id, si, seg, t }) => { + vec![Action::Exec("path.split".into(), json!({"id": id.0, "subpath": si, "segment": seg, "t": t}))] + } + None => vec![], + } + } + + fn scissors_cut(cx: &ToolContext, p: Point) -> Option { let point = cx.point_tol(); // A path snap must not be pulled to a nearby anchor by the larger pick radius. // Shared anchor targets and the path's anchors use the same stored coordinates. let snapping = cx.smart_guides || cx.snap_to_point || cx.snaps_to_pixel(PixelOp::Drawing) || cx.snap_to_grid; let anchor_tol = if snapping { 0.0 } else { point }; if let Some((id, si, ai)) = hit_anchor(cx, p, anchor_tol) { - return vec![Action::Exec("path.split".into(), json!({"id": id.0, "subpath": si, "anchor": ai}))]; - } - match Self::scissors_segment(cx, p) { - Some((id, si, seg, t)) => vec![Action::Exec("path.split".into(), json!({"id": id.0, "subpath": si, "segment": seg, "t": t}))], - None => vec![], + return Some(ScissorsCut::Anchor { id, si, ai }); } + Self::scissors_segment(cx, p).map(|(id, si, seg, t)| ScissorsCut::Segment { id, si, seg, t }) } /// The Anchor Point tool as the Pen lends it with Alt held: an Alt-drag on a handle moves only @@ -694,8 +743,17 @@ impl Tool for AnchorTool { if matches!(self.state, State::Handle { .. }) { out.extend(self.guides.iter().cloned()); } - if self.id == "scissors" && self.current_scissors_hover(cx).is_some() { - out.extend_from_slice(self.scissors_snap.guides()); + if self.id == "scissors" + && let Some(h) = self.current_scissors_hover(cx) + { + // Selection priority can change without changing DrawSnap's geometry key. + let (p, _) = Self::scissors_point(cx, h.raw, h.shared); + if p == h.snapped { + out.extend_from_slice(self.scissors_snap.guides()); + } + if let Some(p) = Self::scissors_cut(cx, p).and_then(|cut| cut.point(cx)) { + out.push(Overlay::Anchor { p, color: FEEDBACK, filled: false, size: 7.0 }); + } } if cx.measurement_labels && let Some((p, dx, dy)) = self.measure diff --git a/crates/tools/src/draw2/anchor/tests.rs b/crates/tools/src/draw2/anchor/tests.rs index ba4bd4df27..d6d4896526 100644 --- a/crates/tools/src/draw2/anchor/tests.rs +++ b/crates/tools/src/draw2/anchor/tests.rs @@ -1049,3 +1049,239 @@ fn anchor_point_alt_drag_links_a_blend_spine_handle() { ); assert_eq!(tool.pointer(&c, &PointerEvent::new(PointerKind::Up, 190.0, 350.0).with_mods(alt)), vec![Action::Commit]); } + +fn review_8655_markers(tool: &AnchorTool, context: &ToolContext) -> Vec { + tool.overlays(context) + .into_iter() + .filter_map(|overlay| match overlay { + Overlay::Anchor { p, color, filled: false, size } if color == crate::draw2::FEEDBACK && size == 7.0 => Some(p), + _ => None, + }) + .collect() +} + +/// Compare the public overlay to geometry reconstructed from the real path.split action, +/// including points projected off the raw pointer and a rejected outside-art snap. +#[test] +fn review_8655_scissors_marker_matches_the_fresh_split_geometry() { + let paint = paint(); + let mut observed = Vec::new(); + for scenario in 0..5 { + let (mut d, mut target, mut selected) = if scenario == 1 { + scissors_crossing() + } else { + let (d, id) = doc_with_rect(); + (d, id, Selection::default()) + }; + if scenario == 3 { + let outside = d.alloc_id(); + d.insert( + Some(d.layers[0].id), + 1, + vectorcraft_doc::Node::path( + outside, + vectorcraft_geom::shapes::line(Point::new(150.0, 103.5), Point::new(350.0, 350.0)), + vectorcraft_doc::Appearance::default_art(), + ), + ) + .unwrap(); + } else if scenario == 4 { + let mut curve = vectorcraft_geom::SubPath::polyline(&[Point::new(100.0, 300.0), Point::new(200.0, 300.0)], false); + curve.anchors[0].h_out = Point::new(120.0, 340.0); + curve.anchors[1].h_in = Point::new(180.0, 340.0); + target = d.alloc_id(); + d.insert( + Some(d.layers[0].id), + 1, + vectorcraft_doc::Node::path(target, vectorcraft_geom::PathData::single(curve), vectorcraft_doc::Appearance::default_art()), + ) + .unwrap(); + } + selected.set([target]); + let (at, expected) = match scenario { + 0 => (Point::new(152.0, 101.5), Point::new(152.0, 100.0)), + 1 => (Point::new(152.0, 101.5), Point::new(150.0, 100.0)), + 2 => (Point::new(200.0, 104.25), Point::new(200.0, 100.0)), + 3 => (Point::new(150.0, 100.0), Point::new(150.0, 100.0)), + _ => (Point::new(150.0, 331.5), Point::new(150.0, 330.0)), + }; + let snapping = scenario == 1 || scenario == 3; + let context = ToolContext { + smart_guides: snapping, + snap_to_point: snapping, + snap_to_pixel: false, + snap_to_grid: false, + isolation: (scenario == 3).then_some(target), + ..cx(&d, &selected, &paint) + }; + let mut tool = AnchorTool::new("scissors"); + assert!(tool.pointer(&context, &PointerEvent::new(PointerKind::Move, at.x, at.y)).is_empty()); + let markers = review_8655_markers(&tool, &context); + let labels = scissors_labels(&tool, &context); + if scenario == 1 { + assert_eq!(labels, [("intersect".to_string(), expected)], "CONTROL: existing intersection guides remain"); + } else { + assert!(labels.is_empty(), "CONTROL: off/rejected snapping adds no guide: {labels:?}"); + } + assert_eq!(tool.cursor(&context, at, Mods::default()), Cursor::Scissors); + let actions = tool.pointer(&context, &PointerEvent::new(PointerKind::Down, at.x, at.y)); + let cut = scissors_cut_at(&d, target, &actions); + assert!(cut.distance(expected) < 1e-5, "CONTROL: scenario{scenario} actual split {cut:?}, expected{expected:?}"); + if scenario == 2 { + assert!(matches!(&actions[..], [Action::Exec(_, args)] if args["anchor"] == 1), "CONTROL: the actual stored anchor wins"); + } + if scenario == 0 || scenario == 4 { + assert!(cut.distance(at) > 1.0, "CONTROL: preview must show the path projection, not the raw point"); + } + observed.push((scenario, markers, cut)); + } + observed.extend(review_8655_endpoint_action_controls()); + // Every split/guide control above executes before the missing-feedback oracle on old code. + for (scenario, markers, cut) in observed { + assert_eq!(markers.len(), 1, "REGRESSION: scenario{scenario} needs exactly one hollow7px FEEDBACK anchor: {markers:?}"); + assert!(markers[0].distance(cut) < 1e-6, "REGRESSION: marker and actual fresh split disagree: {markers:?} versus{cut:?}"); + } +} + +#[test] +fn review_8655_scissors_selection_change_cannot_reuse_the_wrong_marker() { + let (mut d, rectangle) = doc_with_rect(); + let line = d.alloc_id(); + d.insert( + Some(d.layers[0].id), + 1, + vectorcraft_doc::Node::path( + line, + vectorcraft_geom::shapes::line(Point::new(120.0, 102.0), Point::new(240.0, 102.0)), + vectorcraft_doc::Appearance::default_art(), + ), + ) + .unwrap(); + let mut rectangle_selected = Selection::default(); + rectangle_selected.set([rectangle]); + let mut line_selected = Selection::default(); + line_selected.set([line]); + let paint = paint(); + // Only the selection changes: these contexts have the same document and DrawSnap key inputs. + let before = ToolContext { smart_guides: false, snap_to_point: false, ..cx(&d, &rectangle_selected, &paint) }; + let after = ToolContext { smart_guides: false, snap_to_point: false, ..cx(&d, &line_selected, &paint) }; + assert_eq!(before.revision, after.revision); + assert!(std::ptr::eq(before.doc, after.doc)); + let at = Point::new(150.0, 101.6); + let mut tool = AnchorTool::new("scissors"); + tool.pointer(&before, &PointerEvent::new(PointerKind::Move, at.x, at.y)); + let old_markers = review_8655_markers(&tool, &before); + let mut fresh = AnchorTool::new("scissors"); + let old_cut = scissors_cut_at(&d, rectangle, &fresh.pointer(&before, &PointerEvent::new(PointerKind::Down, at.x, at.y))); + let new_cut = scissors_cut_at(&d, line, &fresh.pointer(&after, &PointerEvent::new(PointerKind::Down, at.x, at.y))); + assert!(old_cut.distance(Point::new(150.0, 100.0)) < 1e-6, "CONTROL: selected rectangle beats nearer unselected line"); + assert!(new_cut.distance(Point::new(150.0, 102.0)) < 1e-6, "CONTROL: fresh selection changes the actual split owner"); + assert!(old_cut.distance(new_cut) > 1.0); + let stale = review_8655_markers(&tool, &after); + assert!(stale.iter().all(|p| p.distance(new_cut) < 1e-6), "no unchanged-key selection switch may show the old cut point: {stale:?}"); + tool.pointer(&after, &PointerEvent::new(PointerKind::Move, at.x, at.y)); + let new_markers = review_8655_markers(&tool, &after); + let actions = tool.pointer(&after, &PointerEvent::new(PointerKind::Down, at.x, at.y)); + assert!(scissors_cut_at(&d, line, &actions).distance(new_cut) < 1e-6); + assert_eq!(old_markers.len(), 1, "REGRESSION: valid first selection has feedback"); + assert!(old_markers[0].distance(old_cut) < 1e-6); + assert_eq!(new_markers.len(), 1, "REGRESSION: a fresh hover uses the fresh selected owner"); + assert!(new_markers[0].distance(new_cut) < 1e-6); +} + +#[test] +fn review_8655_scissors_feedback_clears_on_miss_alt_stale_and_leave() { + let (d, _) = doc_with_rect(); + let selected = Selection::default(); + let paint = paint(); + let context = ToolContext { smart_guides: false, snap_to_point: false, ..cx(&d, &selected, &paint) }; + let at = Point::new(170.0, 201.0); + let mut tool = AnchorTool::new("scissors"); + tool.pointer(&context, &PointerEvent::new(PointerKind::Move, at.x, at.y)); + let valid = review_8655_markers(&tool, &context); + // A context change must not keep a geometrically obsolete point visible before rehover. + let stale = ToolContext { zoom: 2.0, smart_guides: false, snap_to_point: false, ..cx(&d, &selected, &paint) }; + assert!(tool.overlays(&stale).is_empty(), "CONTROL: stale zoom shows neither guides nor marker"); + tool.pointer(&context, &PointerEvent::new(PointerKind::Move, 20.0, 20.0)); + assert!(tool.pointer(&context, &PointerEvent::new(PointerKind::Down, 20.0, 20.0)).is_empty()); + assert!(tool.overlays(&context).is_empty(), "CONTROL: a true miss has no cut feedback"); + tool.pointer(&context, &PointerEvent::new(PointerKind::Move, at.x, at.y)); + let alt = Mods { alt: true, ..Mods::default() }; + let event = PointerEvent::new(PointerKind::Down, at.x, at.y); + let mut add = AnchorTool::new("addAnchor"); + assert_eq!(tool.pointer(&context, &event.with_mods(alt)), add.pointer(&context, &event), "CONTROL: Alt remains Add Anchor Point"); + assert!(tool.overlays(&context).is_empty(), "CONTROL: Alt has no Scissors marker"); + tool.pointer(&context, &PointerEvent::new(PointerKind::Move, at.x, at.y)); + tool.hover_ended(&context); + assert!(tool.overlays(&context).is_empty(), "CONTROL: leaving clears the marker and guides"); + assert_eq!(valid.len(), 1, "REGRESSION: the initial valid cut needs visible feedback"); + assert!(valid[0].distance(Point::new(170.0, 200.0)) < 1e-6); +} + +/// The successful point is owned by path.split's consumer, including endpoint rejection and +/// its canonical anchor threshold. Keep the emitted Down action itself unchanged. +fn review_8655_endpoint_action_controls() -> Vec<(usize, Vec, Point)> { + let paint = paint(); + let (open_doc, rectangle, selected) = scissors_crossing(); + let open_cx = ToolContext { smart_guides: false, snap_to_point: false, ..cx(&open_doc, &selected, &paint) }; + let mut tool = AnchorTool::new("scissors"); + for (anchor, endpoint) in [(0, Point::new(145.0, 90.0)), (1, Point::new(165.0, 130.0))] { + tool.pointer(&open_cx, &PointerEvent::new(PointerKind::Move, endpoint.x, endpoint.y)); + let endpoint_markers = review_8655_markers(&tool, &open_cx); + let actions = tool.pointer(&open_cx, &PointerEvent::new(PointerKind::Down, endpoint.x, endpoint.y)); + let [Action::Exec(command, args)] = &actions[..] else { panic!("CONTROL: preserve the original endpoint Down action: {actions:?}") }; + assert_eq!(command, "path.split"); + assert_eq!(args["anchor"], anchor); + let owner = NodeId(args["id"].as_u64().unwrap()); + assert_ne!(owner, rectangle); + assert!(!open_doc.node(owner).unwrap().path_data().unwrap().subpaths[0].closed); + assert_eq!(scissors_cut_at(&open_doc, owner, &actions), endpoint); + assert!(endpoint_markers.is_empty(), "an open path's end point has no successful-cut marker"); + tool.pointer(&open_cx, &PointerEvent::new(PointerKind::Up, endpoint.x, endpoint.y)); + } + let interior = Point::new(155.0, 110.0); + tool.pointer(&open_cx, &PointerEvent::new(PointerKind::Move, interior.x, interior.y)); + let interior_markers = review_8655_markers(&tool, &open_cx); + let actions = tool.pointer(&open_cx, &PointerEvent::new(PointerKind::Down, interior.x, interior.y)); + let [Action::Exec(_, args)] = &actions[..] else { panic!("CONTROL: interior open path emits split: {actions:?}") }; + assert!(args.get("segment").is_some()); + let owner = NodeId(args["id"].as_u64().unwrap()); + assert!(scissors_cut_at(&open_doc, owner, &actions).distance(interior) < 1e-6); + + let (mut d, other_rectangle) = doc_with_rect(); + // Keep the unrelated fixture rectangle away: its exact(100,100) anchor must not steal + // the grid contact from the selected near-endpoint cubic. + d.node_mut(other_rectangle).unwrap().transform(vectorcraft_geom::Affine::translate((0.0, 250.0)), true); + d.grid = vectorcraft_doc::GridPrefs { spacing: 10.0, subdivisions: 1 }; + let start = Point::new(99.99995, 100.0); + // Explicit collinear cubic handles make t linear; a handle-free rectangle's cubic t + // would be about0.000408 here and would not exercise the consumer's1e-6 threshold. + let path = vectorcraft_geom::PathData::from_bezpath(&vectorcraft_geom::BezPath::from_vec(vec![ + vectorcraft_geom::PathEl::MoveTo(start), + vectorcraft_geom::PathEl::CurveTo(Point::new(133.33328333333333, 100.0), Point::new(166.66661666666666, 100.0), Point::new(199.99995, 100.0)), + vectorcraft_geom::PathEl::LineTo(Point::new(199.99995, 200.0)), + vectorcraft_geom::PathEl::LineTo(Point::new(99.99995, 200.0)), + vectorcraft_geom::PathEl::ClosePath, + ])); + let id = d.alloc_id(); + d.insert(Some(d.layers[0].id), 1, vectorcraft_doc::Node::path(id, path, vectorcraft_doc::Appearance::default_art())).unwrap(); + let mut selected = Selection::default(); + selected.set([id]); + let context = ToolContext { snap_to_grid: true, smart_guides: false, snap_to_point: false, ..cx(&d, &selected, &paint) }; + let raw = Point::new(100.1, 100.2); + let mut tool = AnchorTool::new("scissors"); + tool.pointer(&context, &PointerEvent::new(PointerKind::Move, raw.x, raw.y)); + let markers = review_8655_markers(&tool, &context); + let actions = tool.pointer(&context, &PointerEvent::new(PointerKind::Down, raw.x, raw.y)); + let [Action::Exec(command, args)] = &actions[..] else { panic!("CONTROL: near-end grid contact emits split: {actions:?}") }; + assert_eq!(command, "path.split"); + assert_eq!(args["id"], id.0); + assert_eq!(args["segment"], 0); + let t = args["t"].as_f64().unwrap(); + assert!(t > 0.0 && t <= 1e-6, "CONTROL: actual emitted t reaches the consumer's anchor canonicalization: {t}"); + let projected = scissors_cut_at(&d, id, &actions); + assert!(projected.distance(Point::new(100.0, 100.0)) < 1e-6); + assert!(projected.distance(start) > 1e-5, "CONTROL: raw curve evaluation differs from the committed canonical anchor"); + assert!(scissors_labels(&tool, &context).is_empty(), "grid contact adds no Smart Guide label"); + vec![(5, interior_markers, interior), (6, markers, start)] +} diff --git a/crates/tools/src/guides/targets.rs b/crates/tools/src/guides/targets.rs index 6022ab68fb..94344aab2c 100644 --- a/crates/tools/src/guides/targets.rs +++ b/crates/tools/src/guides/targets.rs @@ -707,6 +707,12 @@ impl Targets { self } + /// These targets without the ruler guides, once they stop showing during the drag they were + /// gathered for (#8363). + pub(crate) fn forget_rulers(&mut self) { + self.rulers.clear(); + } + /// The ruler guides alone ([`Self::with_rulers`]): what a dragged selection's grabbed point /// still snaps to with View → Snap to Point when Smart Guides line the selection up. pub(crate) fn rulers(cx: &ToolContext) -> Self { diff --git a/crates/tools/src/lib.rs b/crates/tools/src/lib.rs index f06c5cd5a6..688f295478 100644 --- a/crates/tools/src/lib.rs +++ b/crates/tools/src/lib.rs @@ -226,10 +226,21 @@ pub trait Tool: Send { fn ends_on_escape(&self, _cx: &ToolContext) -> bool { false } + /// The point a path the tool is drawing goes on from, and the direction the path arrives there + /// in (none for a path of one point), while the tool draws one: the Quick Pen toolbar sits + /// beside it. + fn drawing_end(&self, _cx: &ToolContext) -> Option<(Point, Option)> { + None + } /// Does the tool want typed text (Type tool editing)? Single-key shortcuts are suppressed. fn wants_text(&self) -> bool { false } + /// The tool a gradient stop's one-shot pick switches back to after its click (the Eyedropper + /// armed by the Gradient panel's eyedropper); None when no such pick is armed. + fn returns_to(&self) -> Option<&str> { + None + } fn text_input(&mut self, _cx: &ToolContext, _s: &str) -> Vec { vec![] } diff --git a/crates/tools/src/quickpen.rs b/crates/tools/src/quickpen.rs index 140278719d..6368ba160b 100644 --- a/crates/tools/src/quickpen.rs +++ b/crates/tools/src/quickpen.rs @@ -7,15 +7,17 @@ //! sharp-corner arc (it turns through the arc size, 180° by default, and meets the path before it //! at a corner). Alt (Option) pressed and let go on its own switches to the next action. C flips //! the last sharp-corner arc to the other side of its chord, and [ and ] make the arc size 15° -//! smaller or larger, for the last sharp-corner arc and the ones after it. A click on the first +//! smaller or larger, for the last sharp-corner arc and the ones after it; during a drag they +//! change the arc being dragged. A dragged piece ends where the press is let go. A click on the first //! point closes the path, a click on an end of an open path goes on drawing from it, and Escape //! or Enter ends the path. The path's points show as circles, without handles, and a preview //! shows the piece the next click adds. Points snap to Smart Guides. Each piece is one undo step. use std::f64::consts::{FRAC_PI_2, PI}; +use std::sync::Arc; use serde_json::{Value, json}; -use vectorcraft_doc::{NodeId, NodeKind}; +use vectorcraft_doc::{Document, Node, NodeId, NodeKind}; use vectorcraft_geom::{Anchor, AnchorKind, BezPath, Point, SubPath, Vec2}; use crate::draw2::FEEDBACK; @@ -39,6 +41,11 @@ const DRAG_PX: f64 = 3.0; /// A continuous arc whose end lies within this angle (radians) of straight ahead, or of straight /// behind, is drawn as a line: no circle runs there in the path's direction. const STRAIGHT: f64 = 1e-6; +/// The notice the tool asks for after each of its own edits, to see the path as the document then +/// has it. +const DRAWN: &str = "drawn"; +/// The notice after a press's piece is committed. +const PLACED: &str = "placed"; /// What the next click adds. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] @@ -214,21 +221,50 @@ pub fn build(base: &SubPath, pieces: &[Piece], closed: bool) -> SubPath { sp } -/// The path being drawn: subpath `si` of `id`, whose points were `base` before the tool drew on -/// (both none until the engine made a new path), then `pieces`. A new path starts at `start`. -#[derive(Clone, Debug, PartialEq)] +/// The path being drawn: subpath `si` of `id` (none until the engine made a new path, which starts +/// at `start`), and the `pieces` the tool added to it, each after the number of points in `kept` +/// the subpath had before it. `seen` is the path object as the document had it after the tool's +/// last edit, pixel alignment and other changes the engine makes after each edit included, and +/// `before_press` as it was when the press under way began. A piece is drawn again on the points +/// the document holds before it, so the points before it stay as they are. +#[derive(Clone, Debug, Default, PartialEq)] struct Drawing { id: Option, si: usize, - base: Option, start: Option, pieces: Vec, + kept: Vec, + seen: Option>, + before_press: Option>, + /// The document's revision ([`ToolContext::revision`]) after the tool's last edit. + revision: (u64, u64), +} + +/// The node `id` as the document shares it, found through the document's index. +fn shared_node(doc: &Document, id: NodeId) -> Option<&Arc> { + let path = doc.index_path(id)?; + let (first, rest) = path.split_first()?; + let mut cur = doc.layers.get(*first)?; + for &i in rest { + cur = cur.children()?.get(i)?; + } + Some(cur) +} + +/// Is `now` the node `then` was: the same shared node, or one equal to it? +fn same_node(now: &Node, then: &Arc) -> bool { + std::ptr::eq(now, Arc::as_ptr(then)) || *now == **then } impl Drawing { - /// The subpath as the tool drew it. - fn drawn(&self) -> Option { - Some(build(self.base.as_ref()?, &self.pieces, false)) + fn push(&mut self, piece: Piece, kept: usize) { + self.pieces.push(piece); + self.kept.push(kept); + } + + fn pop(&mut self) { + self.pieces.pop(); + self.kept.pop(); } } @@ -266,30 +302,41 @@ fn point_tol(cx: &ToolContext) -> f64 { cx.tol(5.0).max(cx.point_tol()) } +/// Asks to see the path once the actions before it are applied. +fn drawn() -> Action { + Action::Notify(DRAWN.into()) +} + impl QuickPenTool { - /// The subpath being drawn, while it is selected, editable, open and still exactly what the tool - /// drew: an edit made outside the tool (a point moved, the path it went on from changed) ends - /// the drawing, so the next piece does not undo it. + /// The subpath being drawn, while it is selected, editable, open and its path still exactly as + /// the tool's last edit left it: an edit made to the path outside the tool (a point moved, its + /// look changed, the path it went on from changed), also during a press, ends the drawing, so + /// the next piece does not undo it. fn active<'a>(&self, cx: &'a ToolContext) -> Option<(NodeId, &'a SubPath)> { let dr = self.drawing.as_ref()?; let id = dr.id?; if !selected_alone(cx, id) || !cx.doc.is_editable(id) { return None; } - let sp = cx.doc.node(id)?.path_data()?.subpaths.get(dr.si)?; - (!sp.closed && dr.drawn()?.anchors == sp.anchors).then_some((id, sp)) + let node = cx.doc.node(id)?; + if !same_node(node, dr.seen.as_ref()?) { + return None; + } + let sp = node.path_data()?.subpaths.get(dr.si)?; + (!sp.closed).then_some((id, sp)) } - /// `path.quickPen`'s params for the path being drawn, closed when `closed`. + /// `path.quickPen`'s params for the path being drawn: its last piece on the points before it, + /// closed when `closed`. fn params(&self, closed: bool) -> Value { let Some(dr) = &self.drawing else { return json!({}) }; - let pieces: Vec = dr.pieces.iter().map(Piece::to_json).collect(); + let pieces: Vec = dr.pieces.last().map(Piece::to_json).into_iter().collect(); let mut v = json!({"pieces": pieces}); match (dr.id, dr.start) { (Some(id), _) => { v["id"] = json!(id.0); v["subpath"] = json!(dr.si); - v["keep"] = json!(dr.base.as_ref().map_or(1, |b| b.anchors.len().max(1))); + v["keep"] = json!(dr.kept.last().copied().unwrap_or(1).max(1)); } (None, Some(s)) => v["start"] = json!([s.x, s.y]), (None, None) => {} @@ -300,15 +347,57 @@ impl QuickPenTool { v } - /// The last piece, while it is a sharp-corner arc and no press is under way. + /// The last piece, while it is a sharp-corner arc: the one drawn last while no press is under + /// way, or the one a press is drawing. fn last_sharp_arc(&self, cx: &ToolContext) -> Option { - if self.press.is_some() { - return None; + match self.press { + Some(pr) if !pr.begun => return None, + Some(_) => self.held(cx).then_some(())?, + None => self.active(cx).map(|_| ())?, } - self.active(cx)?; self.drawing.as_ref()?.pieces.last().copied().filter(|p| p.stroke == Stroke::SharpArc) } + /// During a press: is the path being drawn still active, and the document as the tool's last + /// preview left it? A preview starts again from the document as the press found it, so after + /// an edit made outside the tool the press previews no more. + fn held(&self, cx: &ToolContext) -> bool { + self.active(cx).is_some() && self.drawing.as_ref().is_some_and(|dr| dr.revision == cx.revision) + } + + /// Moves the end of the piece a press draws to `p` (snapped) and previews it. An edit made + /// outside the tool since the last preview ends the drawing instead: the press then commits + /// the document as it is. + fn drag_to(&mut self, cx: &ToolContext, p: Point) -> Vec { + if !self.held(cx) { + self.drawing = None; + self.snap.clear(); + return vec![]; + } + // The snapping leaves from the point before the piece being dragged, as the press found it. + let from = self.drawing.as_ref().and_then(|dr| { + let sp = dr.before_press.as_ref()?.path_data()?.subpaths.get(dr.si)?; + sp.anchors.get(dr.kept.last()?.checked_sub(1)?).map(|a| Leave::segment(cx, a.p, false).without_contact()) + }); + let q = self.snap.drag(cx, p, from.as_ref()); + let Some(last) = self.drawing.as_mut().and_then(|dr| dr.pieces.last_mut()) else { return vec![] }; + if last.to == q { + return vec![]; + } + last.to = q; + vec![Action::Preview(COMMAND.into(), self.params(false)), drawn()] + } + + /// Draws the path again after its last piece changed: a preview while a press draws that + /// piece, else a step of its own. + fn redraw(&self) -> Vec { + if self.press.is_some_and(|pr| pr.begun) { + vec![Action::Preview(COMMAND.into(), self.params(false)), drawn()] + } else { + vec![Action::Exec(COMMAND.into(), self.params(false)), drawn()] + } + } + fn piece_to(&self, to: Point) -> Piece { Piece { to, stroke: self.action, turn: self.turn, flip: false } } @@ -332,9 +421,9 @@ impl QuickPenTool { _ => return vec![], }; if sp.anchors.len() >= 2 && p.distance(first) <= tol && p.distance(first) <= p.distance(last) { - let piece = self.piece_to(first); + let (piece, kept) = (self.piece_to(first), sp.anchors.len()); if let Some(dr) = self.drawing.as_mut() { - dr.pieces.push(piece); + dr.push(piece, kept); } let out = vec![Action::Exec(COMMAND.into(), self.params(true))]; self.drawing = None; @@ -345,27 +434,25 @@ impl QuickPenTool { } let from = self.leave(cx).map(|l| l.1); let q = self.snap.press(cx, p, &[id], from.as_ref()); - let piece = self.piece_to(q); + let (piece, kept) = (self.piece_to(q), sp.anchors.len()); if let Some(dr) = self.drawing.as_mut() { - dr.pieces.push(piece); + dr.push(piece, kept); + dr.before_press = shared_node(cx.doc, id).cloned(); } self.press = Some(Press { at: p, dragged: false, begun: true }); - return vec![Action::Begin("Quick Pen".into()), Action::Preview(COMMAND.into(), self.params(false))]; + return vec![Action::Begin("Quick Pen".into()), Action::Preview(COMMAND.into(), self.params(false)), drawn()]; } if let Some((id, si, at_first)) = open_end_at(cx, p, tol, None) && cx.doc.is_editable(id) - && let Some(sp) = cx.doc.node(id).and_then(|n| n.path_data()).and_then(|pd| pd.subpaths.get(si)) { - // From its start, `continue_from` reverses the path first. - let mut base = sp.clone(); - if at_first { - base.reverse(); - } - self.drawing = Some(Drawing { id: Some(id), si, base: Some(base), start: None, pieces: vec![] }); - return continue_from(cx, id, si, at_first); + // From its start, `continue_from` reverses the path first; the tool then sees it. + self.drawing = Some(Drawing { id: Some(id), si, ..Drawing::default() }); + let mut out = continue_from(cx, id, si, at_first); + out.push(drawn()); + return out; } let q = self.snap.press(cx, p, &[], None); - self.drawing = Some(Drawing { id: None, si: 0, base: None, start: Some(q), pieces: vec![] }); + self.drawing = Some(Drawing { start: Some(q), ..Drawing::default() }); vec![Action::Exec(COMMAND.into(), self.params(false)), Action::Notify("created".into())] } @@ -427,36 +514,61 @@ impl Tool for QuickPenTool { } pr.dragged = true; self.press = Some(pr); - // The snapping leaves from the point before the piece being dragged. - let from = self.drawing.as_ref().and_then(|dr| { - let sp = build(dr.base.as_ref()?, dr.pieces.split_last().map_or(&[][..], |(_, rest)| rest), false); - sp.anchors.last().map(|a| Leave::segment(cx, a.p, false).without_contact()) - }); - let q = self.snap.drag(cx, p, from.as_ref()); - if let Some(last) = self.drawing.as_mut().and_then(|dr| dr.pieces.last_mut()) { - last.to = q; + if !pr.begun { + return vec![]; } - vec![Action::Preview(COMMAND.into(), self.params(false))] + self.drag_to(cx, p) } PointerKind::Up => { - self.snap.clear(); - match self.press.take() { - Some(pr) if pr.begun => vec![Action::Commit], + let out = match self.press { + // The piece ends where the press is let go, also past the last drag. + Some(pr) if pr.begun => { + let mut out = vec![]; + if pr.dragged || p.distance(pr.at) >= cx.tol(DRAG_PX) { + out = self.drag_to(cx, p); + } else if self.active(cx).is_none() { + // An edit made outside the tool during the press ends the path. + self.drawing = None; + } + // With Real-time Drawing off, the commit applies the piece. + out.extend([Action::Commit, Action::Notify(PLACED.into())]); + out + } _ => vec![], + }; + if let Some(dr) = self.drawing.as_mut() { + dr.before_press = None; } + self.press = None; + self.snap.clear(); + out } PointerKind::DoubleClick | PointerKind::TripleClick => vec![], } } fn notify(&mut self, cx: &ToolContext, what: &str) { + let Some(dr) = self.drawing.as_mut() else { return }; if what == "created" && let [id] = cx.selection.objects.as_slice() - && let Some(base) = cx.doc.node(*id).and_then(|n| n.path_data()).and_then(|pd| pd.subpaths.first()) - && let Some(dr) = self.drawing.as_mut() + && let Some(node) = shared_node(cx.doc, *id).filter(|n| n.path_data().is_some_and(|pd| !pd.subpaths.is_empty())) && dr.id.is_none() { - (dr.id, dr.si, dr.base, dr.start) = (Some(*id), 0, Some(base.clone()), None); + (dr.id, dr.si, dr.start, dr.seen) = (Some(*id), 0, None, Some(node.clone())); + } else if (what == DRAWN || what == PLACED) + && let Some(id) = dr.id + { + dr.seen = shared_node(cx.doc, id).cloned(); + dr.revision = cx.revision; + // Once committed, a piece that added no point to the path (the command refused it) is + // not kept for C and [ ] to change. + let points = dr.seen.as_ref().and_then(|n| n.path_data()).and_then(|pd| pd.subpaths.get(dr.si)).map(|sp| sp.anchors.len()); + if what == PLACED + && let (Some(points), Some(&kept)) = (points, dr.kept.last()) + && points <= kept + { + dr.pop(); + } } } @@ -465,6 +577,11 @@ impl Tool for QuickPenTool { self.active(cx).is_some() } + fn drawing_end(&self, cx: &ToolContext) -> Option<(Point, Option)> { + let (_, sp) = self.active(cx)?; + Some((sp.anchors.last()?.p, arrival(sp))) + } + fn claims_key(&self, cx: &ToolContext, key: ToolKey) -> bool { match key { ToolKey::Letter('c') => self.last_sharp_arc(cx).is_some(), @@ -475,13 +592,19 @@ impl Tool for QuickPenTool { } /// A dropped press does not end the path being drawn: the piece it added goes. - fn drop_press(&mut self, _cx: &ToolContext) -> Vec { + /// The drawing goes on only when the path is back as it was before the press. + fn drop_press(&mut self, cx: &ToolContext) -> Vec { + self.snap.clear(); if self.press.take().is_some_and(|pr| pr.begun) && let Some(dr) = self.drawing.as_mut() { - dr.pieces.pop(); + dr.pop(); + let now = dr.id.and_then(|id| cx.doc.node(id)); + match (now, dr.before_press.take()) { + (Some(now), Some(before)) if same_node(now, &before) => dr.seen = Some(before), + _ => self.drawing = None, + } } - self.snap.clear(); vec![] } @@ -495,7 +618,7 @@ impl Tool for QuickPenTool { if let Some(last) = self.drawing.as_mut().and_then(|dr| dr.pieces.last_mut()) { last.flip = !last.flip; } - vec![Action::Exec(COMMAND.into(), self.params(false))] + self.redraw() } ToolKey::BracketLeft | ToolKey::BracketRight => { let by = if key == ToolKey::BracketLeft { -TURN_STEP } else { TURN_STEP }; @@ -511,17 +634,17 @@ impl Tool for QuickPenTool { if let Some(last) = self.drawing.as_mut().and_then(|dr| dr.pieces.last_mut()) { last.turn = turn; } - vec![Action::Exec(COMMAND.into(), self.params(false))] + self.redraw() } ToolKey::AltTap => { self.action = self.action.next(); // A drag under way draws its piece with the new action. - if self.press.is_some_and(|pr| pr.begun) { + if self.press.is_some_and(|pr| pr.begun) && self.held(cx) { let (action, turn) = (self.action, self.turn); if let Some(last) = self.drawing.as_mut().and_then(|dr| dr.pieces.last_mut()) { (last.stroke, last.turn, last.flip) = (action, turn, false); } - return vec![Action::Preview(COMMAND.into(), self.params(false))]; + return vec![Action::Preview(COMMAND.into(), self.params(false)), drawn()]; } vec![] } diff --git a/crates/tools/src/select.rs b/crates/tools/src/select.rs index 6d1615cef8..fc18a978e6 100644 --- a/crates/tools/src/select.rs +++ b/crates/tools/src/select.rs @@ -309,10 +309,24 @@ impl MoveSnap { Self { bounds, targets: None, points: None, copy_targets: None, copy_points: None, rulers: None, by_edge: false } } + /// The ruler guides stopped showing since the move began (View › Hide Guides, or Trim View, + /// #8363): the move no longer snaps to them, for the rest of it, while its other targets stay. + /// They were gathered when it began, and nothing pulls toward a guide the canvas does not draw. + fn forget_hidden_rulers(&mut self, cx: &ToolContext) { + if cx.guides { + return; + } + self.rulers = None; + for t in [&mut self.points, &mut self.copy_points].into_iter().flatten() { + t.forget_rulers(); + } + } + /// The move (`copy`: the copy) by `d` of the selection grabbed at `start`, snapped, and its /// guides. With Smart Guides › Snap to Last Location, a move within Snapping Tolerance of where /// it began goes back there before anything else snaps ([`Targets::snap_back`]). - pub(crate) fn snap(&self, cx: &ToolContext, start: Point, mut d: Vec2, copy: bool) -> (Vec2, Vec) { + pub(crate) fn snap(&mut self, cx: &ToolContext, start: Point, mut d: Vec2, copy: bool) -> (Vec2, Vec) { + self.forget_hidden_rulers(cx); let (targets, points) = if copy { (&self.copy_targets, &self.copy_points) } else { (&self.targets, &self.points) }; if let Some(ov) = targets.as_ref().and_then(|t| t.snap_back(self.bounds, d, cx.snap_tol())) { return (Vec2::ZERO, ov); @@ -391,7 +405,8 @@ impl MoveSnap { /// passes an anchor or crosses a ruler guide ([`Targets::snap_point_along`]). A move of zero /// length does not snap, and Snap to Last Location goes back to where the move began first, as /// in [`Self::snap`]. - pub(crate) fn snap_along(&self, cx: &ToolContext, start: Point, mut d: Vec2, copy: bool) -> (Vec2, Vec) { + pub(crate) fn snap_along(&mut self, cx: &ToolContext, start: Point, mut d: Vec2, copy: bool) -> (Vec2, Vec) { + self.forget_hidden_rulers(cx); let len = d.hypot(); if !len.is_finite() || len <= 1e-9 { return (d, vec![]); @@ -1957,7 +1972,7 @@ impl SelectionTool { } let mut d = move_delta(start, p, m.shift, cx.constrain_angle); let unsnapped = d; - if let Some(snap) = &self.moving { + if let Some(snap) = &mut self.moving { (d, self.guides) = if m.shift { snap.snap_along(cx, hold, d, m.alt) } else { snap.snap(cx, hold, d, m.alt) }; } // Shift has already constrained `d`: any change is a snap. diff --git a/crates/tools/src/select/tests.rs b/crates/tools/src/select/tests.rs index 82588992b7..dd9c25b74d 100644 --- a/crates/tools/src/select/tests.rs +++ b/crates/tools/src/select/tests.rs @@ -2198,7 +2198,7 @@ fn move_follows_the_while_moving_option() { let p = paint(); let pixel_snap = PixelSnap { moving: false, ..PixelSnap::default() }; let c = ToolContext { snap_to_pixel: true, pixel_snap, smart_guides: false, snap_to_point: false, ..cx(&d, &s, &p) }; - let snap = MoveSnap::new(&c); + let mut snap = MoveSnap::new(&c); let (dv, _) = snap.snap(&c, Point::new(150.0, 150.0), Vec2::new(3.3, 4.6), false); assert!((dv - Vec2::new(3.3, 4.6)).hypot() < 1e-9, "{dv:?}"); let on = ToolContext { pixel_snap: PixelSnap::default(), ..c }; diff --git a/crates/tools/src/settings.rs b/crates/tools/src/settings.rs index 4f4ac487e2..e4b67e6a9f 100644 --- a/crates/tools/src/settings.rs +++ b/crates/tools/src/settings.rs @@ -45,6 +45,9 @@ const ROWS: &[Row] = &[ "affectsDensity", ], ), + // The graphic style the Symbol Styler and the Symbol Sprayer's User Defined Style apply, set + // from the Graphic Styles panel. + (&["symbolSprayer", "symbolStyler"], Some("symbolismStyle"), &["style"]), (&["mirrorCut"], None, &["axis", "keep"]), (&["puppetWarp"], None, &["showMesh", "expand"]), (&["arc"], None, &["closed", "lengthX", "lengthY", "reference", "baseAlong", "slope", "fillArc"]), @@ -75,6 +78,8 @@ const ROWS: &[Row] = &[ (&["star"], None, &["points"]), // The Ellipse dialog's Anchors. (&["ellipse"], None, &["anchors"]), + // Circle Tool Options (`circle::CircleTool`). + (&[crate::circle::ID], None, &["center", "radii", "diameter", "color", "standardAnchors", "dragThird"]), (&["freeTransform"], None, &["constrain"]), // Shape Builder Tool Options (`builder::ShapeBuilderOptions`). ( diff --git a/crates/tools/src/symbolism.rs b/crates/tools/src/symbolism.rs index a4fc04e0cc..165ced795e 100644 --- a/crates/tools/src/symbolism.rs +++ b/crates/tools/src/symbolism.rs @@ -48,6 +48,8 @@ pub struct SymbolismTool { active: bool, hover: Option, alt: bool, + /// Shift was held when the drag began (the Shifter, Sizer, Stainer and Styler have a Shift form). + shift: bool, /// Brush diameter in points. pub diameter: f64, /// 1..10. @@ -113,6 +115,7 @@ impl SymbolismTool { active: false, hover: None, alt: false, + shift: false, diameter: 80.0, intensity: 5.0, density: 5.0, @@ -196,6 +199,9 @@ impl SymbolismTool { v["proportional"] = json!(self.proportional); v["affectsDensity"] = json!(self.affects_density); } + if self.shift && matches!(tool, "shift" | "size" | "stain" | "style") { + v["shift"] = json!(true); + } ("symbol.adjust".into(), v) } } @@ -230,6 +236,7 @@ impl Tool for SymbolismTool { self.previewed = 1; self.active = true; self.alt = ev.mods.alt; + self.shift = ev.mods.shift; let (c, v) = self.command(cx); vec![Action::Begin(self.label().into()), Action::Preview(c, v)] } @@ -577,6 +584,39 @@ mod tests { assert!(v["method"] == "random" && v.get("proportional").is_none(), "{v}"); } + /// A drag begun with Shift sends `shift` with the Shifter, Sizer, Stainer and Styler, and only + /// with them; one begun without it sends none. + #[test] + fn shift_reaches_the_tools_that_have_a_shift_form() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = cx(&d, &s, &p); + let shifted = Mods { shift: true, ..Default::default() }; + for (id, sends) in [ + ("symbolShifter", true), + ("symbolSizer", true), + ("symbolStainer", true), + ("symbolStyler", true), + ("symbolScruncher", false), + ("symbolSpinner", false), + ("symbolScreener", false), + ("symbolSprayer", false), + ] { + let mut t = SymbolismTool::new(id); + let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 5.0, 5.0).with_mods(shifted)); + let Action::Preview(_, v) = &a[1] else { panic!("{a:?}") }; + assert_eq!(v.get("shift"), sends.then_some(&json!(true)), "{id}"); + // The drag keeps the Shift it began with. + let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 60.0, 5.0)); + let Action::Preview(_, v) = &a[0] else { panic!("{a:?}") }; + assert_eq!(v.get("shift"), sends.then_some(&json!(true)), "{id} drag"); + t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 60.0, 5.0)); + let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 5.0, 5.0)); + let Action::Preview(_, v) = &a[1] else { panic!("{a:?}") }; + assert!(v.get("shift").is_none(), "{id} without Shift: {v}"); + } + } + /// With Use Pressure Pen a drag sample where the pen stays is kept when the pressure changes; /// without it, or with the same pressure, the drag keeps thinning the samples by distance. #[test] diff --git a/crates/tools/src/xform/eyedropper.rs b/crates/tools/src/xform/eyedropper.rs index b2d0fdadba..d45dff84ed 100644 --- a/crates/tools/src/xform/eyedropper.rs +++ b/crates/tools/src/xform/eyedropper.rs @@ -16,7 +16,8 @@ //! //! The Gradient panel's eyedropper sets the `stop` option (the tool to return to): the next click //! samples the colour under the cursor into the selected gradient stop (`paint.sampleColor -//! {stop}`) and switches back to that tool. +//! {stop}`) and switches back to that tool. Armed for the Live Paint Bucket, a click once its stop +//! is no longer selected ends the pick without sampling and switches back to the bucket. //! //! Gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso before switching //! to the Eyedropper stay picked (its `meshPoints` option), and go back to one of those tools @@ -479,10 +480,15 @@ fn renumber(doc: &mut Document, n: &mut Node) { /// as that pixel). fn image_color_at(s: &Sampler, n: &Node, p: Point) -> Option { let NodeKind::Image(im) = &n.kind else { return None }; - if im.xf.determinant().abs() < 1e-12 { - return None; - } - let px = im.xf.inverse() * p; + // A distorted image's pixel under `p` is found through its projective map. + let px = if n.is_distorted_image() { + n.image_map()?.inverse()?.apply(p)? + } else { + if im.xf.determinant().abs() < 1e-12 { + return None; + } + im.xf.inverse() * p + }; let blob = s.doc.images.get(&im.key)?; let object = (im.width, im.height); if let Some(inks) = blob.sample_cmyk_object(px.x, px.y, object, s.raster_sample) { @@ -531,6 +537,15 @@ impl Tool for EyedropperTool { self.stop = None; return vec![Action::Dialog("brushKeyColor".into(), json!({ "color": color_json(&c) })), Action::SwitchTool(back)]; } + // A pick for a stop of the Live Paint Bucket's gradient (the default paint's) ends without + // sampling once that stop is no longer selected (a Cmd-click selected another object) or no + // longer there (another paint was chosen): the click switches back. + let bucket_paint = if cx.fill_active { &cx.paint.fill } else { &cx.paint.stroke }; + let bucket_stop = cx.gradient_stop.filter(|i| matches!(bucket_paint, Paint::Gradient(g) if *i < g.gradient.stops.len())); + if self.stop.as_deref() == Some("livePaintBucket") && bucket_stop.is_none() { + self.stop = None; + return vec![Action::SwitchTool("livePaintBucket".into())]; + } let stop = self.stop.as_ref().zip(cx.gradient_stop); // A plain click on a selected gradient mesh gives the fill color to the point there, else // to the four points of the patch there. @@ -655,6 +670,10 @@ impl Tool for EyedropperTool { vec![] } + fn returns_to(&self) -> Option<&str> { + self.stop.as_deref().filter(|_| !self.brush_key_color && self.image_trace_ignore_color.is_none()) + } + /// Escape is the tool's while a pick is armed, so it switches back and ends nothing else. fn claims_key(&self, _cx: &ToolContext, key: ToolKey) -> bool { key == ToolKey::Escape && self.picking() @@ -833,6 +852,27 @@ mod tests { ] ); assert_eq!(t.options(), json!({"stop": null, "brushKeyColor": false}), "one sample only"); + // Armed for the Live Paint Bucket with its stop no longer selected, a click ends the pick. + cx.gradient_stop = None; + t.set_option("stop", &json!("livePaintBucket")); + let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 100.0, 150.0)); + assert_eq!(a, vec![Action::SwitchTool("livePaintBucket".into())]); + assert_eq!(t.returns_to(), None); + // So does a click once the default paint has no such stop (here, a solid fill). + cx.gradient_stop = Some(1); + assert!(!matches!(cx.paint.fill, Paint::Gradient(_))); + t.set_option("stop", &json!("livePaintBucket")); + assert_eq!(t.returns_to(), Some("livePaintBucket")); + let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 100.0, 150.0)); + assert_eq!(a, vec![Action::SwitchTool("livePaintBucket".into())]); + // Neither a Key Color pick nor an Image Trace ignored-color pick is a gradient stop's. + t.set_option("brushKeyColor", &json!(true)); + t.set_option("stop", &json!("livePaintBucket")); + assert_eq!(t.returns_to(), None); + let mut t = EyedropperTool::default(); + t.set_option("imageTraceIgnoreColor", &json!({"dialog": "imageTrace"})); + t.set_option("stop", &json!("livePaintBucket")); + assert_eq!(t.returns_to(), None); } /// #8024: Escape ends a gradient stop's pick and a Key Color pick without sampling and @@ -1050,6 +1090,12 @@ mod tests { assert_eq!(sampled_hex(&EyedropperTool::default().pointer(&crate::testutil::cx(&d, &s, &p), &click)), "#00ff00"); d.node_mut(l).unwrap().visible = false; assert!(EyedropperTool::default().pointer(&crate::testutil::cx(&d, &s, &p), &click).is_empty()); + // Distorted with its left and right swapped, the blue pixel is drawn at the left. + d.node_mut(l).unwrap().visible = true; + let q = [(30.0, 0.0), (0.0, 0.0), (0.0, 10.0), (40.0, 10.0)].map(|(x, y)| vectorcraft_geom::Point::new(x, y)); + d.node_mut(id).unwrap().set_image_corners(q).unwrap(); + let left = PointerEvent::new(PointerKind::Down, 4.0, 5.0); + assert_eq!(sampled_hex(&EyedropperTool::default().pointer(&crate::testutil::cx(&d, &s, &p), &left)), "#0000ff"); } /// #2276: a CMYK image gives its ink amounts as they are, not the RGB its decoder shows. diff --git a/crates/ui-egui/src/app/commands.rs b/crates/ui-egui/src/app/commands.rs index fc04c051fc..042e8b37a5 100644 --- a/crates/ui-egui/src/app/commands.rs +++ b/crates/ui-egui/src/app/commands.rs @@ -479,6 +479,10 @@ impl VectorcraftApp { if crate::touch::is_drawing_tool(now) { self.ui.touch_drawing_tool = Some(now.to_string()); } + // Selecting the Quick Pen tool shows its toolbar, even after Hide Toolbar. + if now == vectorcraft_tools::quickpen::ID { + self.ui.quick_pen_bar = true; + } Ok(()) } diff --git a/crates/ui-egui/src/app/view.rs b/crates/ui-egui/src/app/view.rs index a1c2af21ff..1e9d931a0a 100644 --- a/crates/ui-egui/src/app/view.rs +++ b/crates/ui-egui/src/app/view.rs @@ -122,7 +122,7 @@ impl VectorcraftApp { zoom: self.view().map_or(1.0, |v| v.screen_zoom(self.canvas_ui_zoom)), outline: self.outline_view(), smart_guides: self.ui.view.smart_guides, - guides: self.ui.view.guides, + guides: self.ui.view.guides_shown(), snap_to_grid: self.ui.view.snap_to_grid, pixel_preview: self.ui.view.pixel_preview, snap_to_pixel: self.ui.view.snap_to_pixel, diff --git a/crates/ui-egui/src/caches.rs b/crates/ui-egui/src/caches.rs index be5ff73c54..6e1d229023 100644 --- a/crates/ui-egui/src/caches.rs +++ b/crates/ui-egui/src/caches.rs @@ -25,8 +25,8 @@ pub struct CanvasCache { /// last render took more than 8 ms, the canvas draws the frame shown reprojected and renders /// once the view has been still for [`canvas::STILL_SECS`]. pub waits_for_still: bool, - /// The cache key the canvas last asked for and when it first asked for it (seconds, egui's - /// input time), kept while [`Self::waits_for_still`] is set. + /// The cache key the canvas last asked for and when it first asked for its view (seconds, + /// egui's input time), kept while [`Self::waits_for_still`] is set. pub still: Option<(CacheKey, f64)>, /// The low-resolution frame that covers the parts of the canvas the frame shown leaves /// uncovered while it is drawn for a view it was not rendered for ([`canvas::Fill`]). diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index e4d21df36f..8b366665d4 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -28,6 +28,7 @@ mod input; mod outline; mod overlays; mod panes; +mod quick_pen_bar; mod raster; mod selection_marks; mod task_bar; @@ -68,12 +69,14 @@ use overlays::{ }; pub use panes::{Layout as TileLayout, Panes}; pub(crate) use panes::{consolidate, note_drop, noted_cursor, pane, release_on_noted, tile, tiled_area}; +pub(crate) use quick_pen_bar::quick_pen_bar_rect; pub(crate) use raster::{KeptFrame, color_image, color_image_owned, render_job}; use raster::{changed_pixels, frame_ppp, pixel_region, upload}; pub use selection_marks::SelectionMarks; use task_bar::task_bar; +pub(crate) use task_bar::{TASK_BAR_ACTIONS, TASK_BAR_CHIPS, is_task_bar_action, read_hidden_task_bar_actions}; #[cfg(test)] -pub(crate) use task_bar::{chip_paints, images_with_other_art}; +pub(crate) use task_bar::{bar_action_name, chip_paints, images_with_other_art, task_bar_offered}; pub(crate) use task_bar::{has_colors, task_bar_rect, task_bar_shows_fonts, task_bar_shows_type}; #[cfg(test)] use tool_overlays::{DIAL_RADIUS, HiddenMarks}; @@ -325,7 +328,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { paint_paper(app, st, ui, &painter, &xf, rect, (&t, app.outline_view())); // The grid behind the art (Guides & Grid › Grids In Back), else over it below. - let grid_look = (app.ui.view.grid && !presenting).then(|| LineLook::grid(&app.session.prefs)); + let grid_look = (app.ui.view.grid_shown() && !presenting).then(|| LineLook::grid(&app.session.prefs)); let grids_in_back = app.session.prefs.grids_in_back; if let Some(look) = grid_look.filter(|_| grids_in_back) { grid(&painter, &xf, doc.grid.spacing, doc.grid.subdivisions, look); @@ -358,8 +361,10 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { poll_worker(app, ui, key.doc); // With `waits_for_still` set (the web build, which has no render worker), a heavy document is // not rendered while only the view changes: the frame shown is drawn reprojected below, and the - // first frame after the view has been still for STILL_SECS renders. + // first frame after the view has been still for STILL_SECS renders. An edit meanwhile is drawn + // into the frame shown ([`edit_in_frame_shown`]). let wait = if app.canvas.waits_for_still { + edit_in_frame_shown(app, &key, &doc, &effects, &drawn, (mask_view, smooth_images)); let slow = app.canvas.last_ms > 8.0 && app.canvas.texture.is_some(); still_wait(&mut app.canvas.still, app.canvas.key.as_ref(), &key, slow, ui.input(|i| i.time)) } else { @@ -413,7 +418,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { grid(&painter, &xf, 1.0, 1, LineLook { color: PIXEL_GRID, dots: false }); } artboard_outlines(app, ui, &painter, &xf, &t); - if app.ui.view.guides { + if app.ui.view.guides_shown() { guide_lines(app, &painter, &xf, rect, &t); } nine_slice_overlay(app, &painter, &xf); @@ -460,6 +465,8 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { task_bar(app, ui, &xf); } if app.ui.screen_mode < 3 { + // The Quick Pen toolbar gives way to a drag as the task bar does. + quick_pen_bar::quick_pen_bar(app, ui, &xf); contour_bar::contour_bar(app, ui, &xf); // After the task bar, which the row of character alternates keeps clear of. alternates_bar::alternates_bar(app, ui, &xf); @@ -896,7 +903,7 @@ fn cache_key( outline: app.outline_view(), trim: app.ui.view.trim_view, templates: app.ui.view.templates, - guides: app.ui.view.guides, + guides: app.ui.view.guides_shown(), ppp, hidden: vec![], rot: v.rotation, @@ -1095,7 +1102,7 @@ fn frame_options( overprint_preview: vectorcraft_render::proof::overprint_preview_on(), trim: app.ui.view.trim_view, hide_templates: !app.ui.view.templates, - hide_guides: !app.ui.view.guides, + hide_guides: !app.ui.view.guides_shown(), tile_edge: vectorcraft_color::Color::from_hex(&app.session.prefs.pattern_tile_edge_color).map_or(opts.tile_edge, |c| { let [r, g, b, _] = c.to_rgba8(1.0); [r, g, b] @@ -1149,6 +1156,72 @@ struct Frame<'a> { /// shows the document's paper without the art: about a frame at 60 Hz. pub(crate) const FIRST_FRAME_GRACE: std::time::Duration = std::time::Duration::from_millis(16); +/// Draw `region` of `frame` again, into the texture of the frame shown, which then shows `frame`'s +/// key: only the document changed since the frame shown, in that part of it +/// ([`changed_pixels`]). `None`: nothing in view changed. `last_ms` stays the whole frame's. +fn draw_changed(app: &mut VectorcraftApp, frame: &Frame, region: Option<[u32; 4]>) { + let Frame { key, doc, effects, view, opts, pixel, .. } = frame; + let t0 = now_ms(); + if region.is_none() { + // Nothing in view to draw again: what was made to measure the edit isn't drawn. + app.canvas.renderer.let_go_of_measured(); + } + let display = app.display_profile.transform(app.session.prefs.monitor_profile_display); + if let (Some([x0, y0, x1, y1]), Some(tex)) = (region, &mut app.canvas.texture) { + let renderer = &mut app.canvas.renderer; + let part_view = Affine::translate((-f64::from(x0), -f64::from(y0))) * *view; + let mut part = effects.view(|| renderer.render(doc, x1 - x0, y1 - y0, part_view, opts)); + let width = part.width; + crate::display_profile::convert_over(display.as_deref(), &mut part.pixels, width, part_view, key.over()); + let color = color_image(&part); + let options = if pixel.is_some() { egui::TextureOptions::NEAREST } else { egui::TextureOptions::LINEAR }; + tex.set_partial([x0 as usize, y0 as usize], color, options); + app.canvas.moved |= app.canvas.renderer.stats.moved > 0; + } + app.canvas.key = Some((*key).clone()); + app.canvas.shown = Some(((*doc).clone(), opts.clone())); + app.perf.render_ms = now_ms() - t0; +} + +/// With `waits_for_still` set (the web build) and the last render slow, an edit while the view +/// moves (a tool's drag that scrolls the view at an edge of the canvas, or a wheel scroll during a +/// drag) is drawn into the frame shown, at the view it was rendered for: the part the edit changed +/// only ([`changed_pixels`]). The frame shown then stays drawn reprojected with the view, and the +/// canvas renders whole once the view has been still for [`STILL_SECS`], as for a view change +/// without an edit (#8688). When more than the view and the document differ from the frame shown, +/// or the edit changed more than half of it, nothing is drawn here: the frame renders whole. +fn edit_in_frame_shown( + app: &mut VectorcraftApp, + key: &CacheKey, + doc: &std::sync::Arc, + effects: &vectorcraft_plugins::deferred::Deferrals, + drawn: &View, + (mask_view, smooth_images): (Option, bool), +) { + let slow = app.canvas.last_ms > 8.0 && app.canvas.texture.is_some(); + let Some(shown) = app.canvas.key.clone().filter(|_| slow) else { return }; + let at_shown = CacheKey { + zoom: shown.zoom, + cx: shown.cx, + cy: shown.cy, + w: shown.w, + h: shown.h, + ppp: shown.ppp, + rot: shown.rot, + pixel: shown.pixel, + ..key.clone() + }; + if at_shown == shown || at_shown == *key || shown.pixel.is_some() != key.pixel.is_some() { + return; + } + let v = View { center: Point::new(shown.cx, shown.cy), zoom: shown.zoom, rotation: shown.rot, ..*drawn }; + let (w, h, view) = frame_view(at_shown.pixel, (at_shown.w, at_shown.h), &v, at_shown.ppp); + let opts = frame_options(app, &at_shown, mask_view, smooth_images); + if let Some(region) = changed_pixels(app, &at_shown, doc, &opts, view, w, h) { + draw_changed(app, &Frame { key: &at_shown, doc, effects, size: (w, h), view, opts, pixel: at_shown.pixel }, region); + } +} + fn draw_frame(app: &mut VectorcraftApp, ui: &Ui, frame: Frame) { let Frame { key, doc, effects, size: (w, h), view, opts, pixel } = frame; // Frames that would be slow on this thread (the last one took over 8 ms) go @@ -1172,27 +1245,7 @@ fn draw_frame(app: &mut VectorcraftApp, ui: &Ui, frame: Frame) { match (&mut app.canvas.worker, heavy, changed) { // Only the document changed since the frame shown, in a part of it: that part is // rendered again, here, into the texture. `last_ms` stays the whole frame's. - (_, _, Some(region)) => { - let t0 = now_ms(); - if region.is_none() { - // Nothing in view to draw again: what was made to measure the edit isn't drawn. - app.canvas.renderer.let_go_of_measured(); - } - if let (Some([x0, y0, x1, y1]), Some(tex)) = (region, &mut app.canvas.texture) { - let renderer = &mut app.canvas.renderer; - let part_view = Affine::translate((-f64::from(x0), -f64::from(y0))) * view; - let mut part = effects.view(|| renderer.render(doc, x1 - x0, y1 - y0, part_view, &opts)); - let width = part.width; - crate::display_profile::convert_over(display.as_deref(), &mut part.pixels, width, part_view, key.over()); - let color = color_image(&part); - let options = if pixel.is_some() { egui::TextureOptions::NEAREST } else { egui::TextureOptions::LINEAR }; - tex.set_partial([x0 as usize, y0 as usize], color, options); - app.canvas.moved |= app.canvas.renderer.stats.moved > 0; - } - app.canvas.key = Some(key.clone()); - app.canvas.shown = Some((doc.clone(), opts.clone())); - app.perf.render_ms = now_ms() - t0; - } + (_, _, Some(region)) => draw_changed(app, &Frame { key, doc, effects, size: (w, h), view, opts, pixel }, region), (Some(worker), true, None) => { // The worker draws the frame: what this thread's renderer made to measure the edit // isn't drawn here. diff --git a/crates/ui-egui/src/canvas/cursor.rs b/crates/ui-egui/src/canvas/cursor.rs index 864a708e34..d9e589c246 100644 --- a/crates/ui-egui/src/canvas/cursor.rs +++ b/crates/ui-egui/src/canvas/cursor.rs @@ -51,11 +51,13 @@ pub(super) fn hover_wait(moved: &mut Option<(ViewKey, f64)>, key: ViewKey, now: /// Note that the canvas asks for `key` at time `now` (seconds, egui's input time) → how many more /// seconds it draws the frame `shown` reprojected instead of rendering `key`: while the last -/// render was `slow`, only the view differs between the two, and the canvas has asked for `key` -/// for less than [`STILL_SECS`]. `still` holds the key last asked for and when the canvas first -/// asked for it. None: the canvas renders `key` now, unless it is the frame shown. +/// render was `slow`, only the view differs between the two, and the canvas has asked for the view +/// of `key` for less than [`STILL_SECS`]. `still` holds the key last asked for and when the canvas first +/// asked for its view. An edit leaves that time as it is: with the view still and edits drawn into +/// the frame shown at each step of a drag, the canvas still renders whole once the view has been +/// still for [`STILL_SECS`]. None: the canvas renders `key` now, unless it is the frame shown. pub(super) fn still_wait(still: &mut Option<(CacheKey, f64)>, shown: Option<&CacheKey>, key: &CacheKey, slow: bool, now: f64) -> Option { - if still.as_ref().is_none_or(|(k, _)| k != key) { + if still.as_ref().is_none_or(|(k, _)| !same_view(k, key)) { *still = Some((key.clone(), now)); } let waited = still.as_ref().map_or(0.0, |(_, at)| now - at); @@ -64,6 +66,12 @@ pub(super) fn still_wait(still: &mut Option<(CacheKey, f64)>, shown: Option<&Cac (slow && waiting && shown.is_some_and(|s| s != key && only_view_differs(s, key))).then_some(STILL_SECS - waited) } +/// Whether two cache keys are of the same document at the same view (zoom, center, rotation, +/// canvas size, pixel density and Pixel Preview's document pixels), whatever else differs. +fn same_view(a: &CacheKey, b: &CacheKey) -> bool { + (a.doc, a.zoom, a.cx, a.cy, a.w, a.h, a.ppp, a.rot, a.pixel) == (b.doc, b.zoom, b.cx, b.cy, b.w, b.h, b.ppp, b.rot, b.pixel) +} + /// Whether two cache keys differ only in the view (zoom, center, rotation, canvas size, pixel /// density and Pixel Preview's document pixels), with Pixel Preview on in both or off in both. pub(super) fn only_view_differs(a: &CacheKey, b: &CacheKey) -> bool { diff --git a/crates/ui-egui/src/canvas/grid.rs b/crates/ui-egui/src/canvas/grid.rs index 5d533f7eaf..97c68269fb 100644 --- a/crates/ui-egui/src/canvas/grid.rs +++ b/crates/ui-egui/src/canvas/grid.rs @@ -222,7 +222,14 @@ pub(super) fn ruler_input(app: &mut VectorcraftApp, ui: &Ui, full: egui::Rect, c if resp.clicked_by(egui::PointerButton::Primary) { ui.data_mut(|d| d.insert_temp(last_click, now)); } - if resp.double_clicked_by(egui::PointerButton::Primary) + // Trim View hides the guides (#8363): a guide made now could not be seen, so none is. + let trim_view = app.ui.view.trim_view; + let refuse = |app: &mut VectorcraftApp| app.status(crate::menus::TRIM_VIEW_HIDES.to_string()); + if trim_view && first_here && resp.double_clicked_by(egui::PointerButton::Primary) { + refuse(app); + } + if !trim_view + && resp.double_clicked_by(egui::PointerButton::Primary) && first_here && let Some(p) = resp.interact_pointer_pos().or_else(|| ui.input(|i| i.pointer.latest_pos())) { @@ -253,12 +260,22 @@ pub(super) fn ruler_input(app: &mut VectorcraftApp, ui: &Ui, full: egui::Rect, c } else { continue; }; - let p = resp.interact_pointer_pos().or_else(|| ui.input(|i| i.pointer.latest_pos())); - let on_canvas = p.is_some_and(|p| canvas.contains(p)); - if on_canvas { - // The new guide shows even if guides were hidden. - app.ui.view.guides = true; + // A drag Trim View is on for at any point makes no guide, so none previews, even when + // Trim View is turned off again before the release: the whole gesture is cancelled and + // stays so until the button is released. + let cancel = egui::Id::unique(if vertical { "ruler-left-trim-cancel" } else { "ruler-top-trim-cancel" }); + if resp.drag_started() { + ui.data_mut(|d| d.remove::(cancel)); } + if trim_view && ui.data(|d| d.get_temp::(cancel).is_none()) { + refuse(app); + ui.data_mut(|d| d.insert_temp(cancel, true)); + } + let cancelled = ui.data(|d| d.get_temp::(cancel).is_some()); + if cancelled && kind == PointerKind::Up { + ui.data_mut(|d| d.remove::(cancel)); + } + let p = resp.interact_pointer_pos().or_else(|| ui.input(|i| i.pointer.latest_pos())); let ev = PointerEvent { kind, pos: p.map_or(Point::ZERO, |p| xf.to_doc(p)), @@ -267,6 +284,21 @@ pub(super) fn ruler_input(app: &mut VectorcraftApp, ui: &Ui, full: egui::Rect, c pressure: 1.0, pen: None, }; + if cancelled { + // A guide already dragged when Trim View turned on ends as a release off the canvas + // does: no guide, no undo step. + if app.session.ruler_guide_dragging() + && let Err(e) = app.session.ruler_guide(vertical, &PointerEvent { kind: PointerKind::Up, ..ev }, false, app.view_info()) + { + app.status(e.to_string()); + } + continue; + } + let on_canvas = p.is_some_and(|p| canvas.contains(p)); + if on_canvas { + // The new guide shows even if guides were hidden. + app.ui.view.guides = true; + } if let Err(e) = app.session.ruler_guide(vertical, &ev, on_canvas, app.view_info()) { app.status(e.to_string()); } @@ -288,11 +320,14 @@ pub(super) fn ruler_input(app: &mut VectorcraftApp, ui: &Ui, full: egui::Rect, c let drag_id = ruler_origin_drag_id(); let uid = app.session.active().map(|d| d.uid); if corner.drag_started_by(egui::PointerButton::Primary) { - ui.data_mut(|d| d.insert_temp(drag_id, (uid, false))); + ui.data_mut(|d| d.insert_temp(drag_id, OriginDrag { doc: uid, cancelled: false, trim_view: app.ui.view.trim_view })); } let mut preview = None; - if let Some((started_in, mut cancelled)) = ui.data(|d| d.get_temp::<(Option, bool)>(drag_id)) { - cancelled |= started_in != uid || ui.input(|i| !i.focused || i.key_pressed(egui::Key::Escape)); + if let Some(OriginDrag { doc: started_in, mut cancelled, trim_view }) = ui.data(|d| d.get_temp::(drag_id)) { + // Trim View turned on or off during the drag: the snap targets gathered at its start + // hold the ruler guides, or leave them out, as they no longer show (#8363), so the origin + // could snap to a guide nobody sees. The drag is cancelled as for hidden rulers. + cancelled |= started_in != uid || trim_view != app.ui.view.trim_view || ui.input(|i| !i.focused || i.key_pressed(egui::Key::Escape)); let pointer = corner.interact_pointer_pos().or_else(|| ui.input(|i| i.pointer.latest_pos())).filter(|p| canvas.contains(*p)).map(|p| xf.to_doc(p)); // The origin snaps as a drawn point does (Smart Guides, Snap to Point, pixels, the grid). @@ -313,7 +348,7 @@ pub(super) fn ruler_input(app: &mut VectorcraftApp, ui: &Ui, full: egui::Rect, c } else if !ui.input(|i| i.pointer.primary_down()) { end_ruler_origin_drag(app, ui); } else { - ui.data_mut(|d| d.insert_temp(drag_id, (started_in, cancelled))); + ui.data_mut(|d| d.insert_temp(drag_id, OriginDrag { doc: started_in, cancelled, trim_view })); if !cancelled { preview = at; } @@ -333,10 +368,21 @@ pub(super) fn rulers_hidden(app: &mut VectorcraftApp, ui: &Ui) -> Option /// Ends a drag from the rulers' corner, released or cancelled: its state and its snapping guides go. fn end_ruler_origin_drag(app: &mut VectorcraftApp, ui: &Ui) { - ui.data_mut(|d| d.remove::<(Option, bool)>(ruler_origin_drag_id())); + ui.data_mut(|d| d.remove::(ruler_origin_drag_id())); app.session.end_ruler_origin_drag(); } +/// A drag of the rulers' origin out of their corner, kept between frames. +#[derive(Clone, Copy)] +struct OriginDrag { + /// The document it started in (`Document::uid`): another one active cancels it. + doc: Option, + /// Cancelled (Escape, focus lost, another document, Trim View toggled): it sets nothing. + cancelled: bool, + /// View › Trim View was on when it started. + trim_view: bool, +} + /// The key of the ruler origin drag's state in egui's temporary data. fn ruler_origin_drag_id() -> egui::Id { egui::Id::unique("ruler-origin-drag") @@ -345,7 +391,7 @@ fn ruler_origin_drag_id() -> egui::Id { /// Is a drag from the rulers' corner in progress? It stays true after Escape cancels the move, until /// the button is released. pub(crate) fn ruler_origin_dragging(ctx: &egui::Context) -> bool { - ctx.data(|d| d.get_temp::<(Option, bool)>(ruler_origin_drag_id()).is_some()) + ctx.data(|d| d.get_temp::(ruler_origin_drag_id()).is_some()) } /// What the rulers count, and from where: `unit`, from `origin` (document points), with each diff --git a/crates/ui-egui/src/canvas/outline.rs b/crates/ui-egui/src/canvas/outline.rs index 9d1794ab7d..c2ab7945be 100644 --- a/crates/ui-egui/src/canvas/outline.rs +++ b/crates/ui-egui/src/canvas/outline.rs @@ -188,7 +188,7 @@ pub(super) fn hit_with( path_only: prefs.object_selection_by_path_only, type_path_only: prefs.type_selection_by_path_only, scope: app.session.active().and_then(|st| st.isolation), - skip_guides: !app.ui.view.guides, + skip_guides: !app.ui.view.guides_shown(), ..Default::default() }; test(&app.session.active()?.doc, p, opt) diff --git a/crates/ui-egui/src/canvas/panes.rs b/crates/ui-egui/src/canvas/panes.rs index cef27dab18..63d89f2be2 100644 --- a/crates/ui-egui/src/canvas/panes.rs +++ b/crates/ui-egui/src/canvas/panes.rs @@ -554,7 +554,7 @@ fn draw_pane(app: &mut VectorcraftApp, ui: &Ui, w: Win, cell: egui::Rect) -> boo let xf = Xf::at(rect, &v, ui_zoom); let painter = ui.painter_at(rect); paint_paper(app, st, ui, &painter, &xf, rect, (&t, v.outline)); - let grid_look = app.ui.view.grid.then(|| LineLook::grid(&app.session.prefs)); + let grid_look = app.ui.view.grid_shown().then(|| LineLook::grid(&app.session.prefs)); let grids_in_back = app.session.prefs.grids_in_back; if let Some(look) = grid_look.filter(|_| grids_in_back) { grid(&painter, &xf, st.doc.grid.spacing, st.doc.grid.subdivisions, look); @@ -587,7 +587,7 @@ fn draw_pane(app: &mut VectorcraftApp, ui: &Ui, w: Win, cell: egui::Rect) -> boo if shows_artboards(app) { artboard_edges(app, &st.doc, (&painter, &xf, &t), (v.artboard, dim_on_canvas(&t, v.outline)), |_| false); } - if app.ui.view.guides { + if app.ui.view.guides_shown() { guides_of(app, st, (&painter, &xf, &t), rect); } if app.ui.view.edges { diff --git a/crates/ui-egui/src/canvas/quick_pen_bar.rs b/crates/ui-egui/src/canvas/quick_pen_bar.rs new file mode 100644 index 0000000000..fdca1884de --- /dev/null +++ b/crates/ui-egui/src/canvas/quick_pen_bar.rs @@ -0,0 +1,278 @@ +//! The Quick Pen toolbar: a floating bar on the canvas while the Quick Pen tool is active. It holds +//! the tool's actions (Straight Line, Continuous Arc, Sharp Corner Arc), Flip Arc for the last +//! sharp-corner arc, and a More Options menu with Hide Toolbar, Pin Toolbar Position and Reset +//! Toolbar Position. Its handle, at its left end, drags it. +//! +//! Public behavior: selecting the tool shows the toolbar, its actions decide what a click or drag +//! draws, Flip Arc flips the sharp-corner arc just drawn, the More menu hides the toolbar and resets +//! its position, and the toolbar moves by dragging its left side +//! ([Draw with the Quick Pen tool](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/draw-with-quick-pen-tool.html)). +//! The toolbar follows the drawing, beside the point the path goes on from and away from what was +//! drawn ([Behind the design: the Quick Pen tool](https://adobe.design/ideas/behind-the-design-adobe-illustrator-s-quick-pen-tool)). +//! VectorCraft's own rules: the exact place beside the point, moving to the drawn side where the +//! other side runs off the canvas, the place with no path being drawn, how a drag's offset is kept, +//! Pin Toolbar Position (which holds the toolbar at its place in the canvas window, not on the +//! artboard), and Window › Quick Pen Toolbar to show it again. + +use vectorcraft_tools::quickpen::{self, Stroke as Action}; + +use super::{Color32, CornerRadius, Pos2, Sense, Stroke, Tokens, Ui, Vec2, VectorcraftApp, Xf, json, pos2, vec2, widgets}; + +/// The space between the point the path goes on from and the toolbar's nearest corner. +const GAP: f32 = 24.0; +/// The width of the toolbar's handle. +const HANDLE: f32 = 4.0; +/// The side of the toolbar's buttons. +const BUTTON: f32 = 28.0; +/// The space between the toolbar's controls. +const SPACING: f32 = 4.0; + +fn bar_id() -> egui::Id { + egui::Id::unique("quick-pen-bar") +} + +/// Where the Quick Pen toolbar was last drawn (none while it isn't shown). +pub(crate) fn quick_pen_bar_rect(ctx: &egui::Context) -> Option { + let id = bar_id(); + ctx.memory(|m| m.areas().is_visible(&egui::LayerId::new(egui::Order::Middle, id)).then(|| m.area_rect(id)).flatten()) +} + +/// The toolbar's top-left corner, of `size`, beside `end` (the point the path goes on from, on +/// screen), on the side the path arrives there from `dir` (on screen): to its right and below it +/// for a path drawn to the right and down, so the toolbar stays off what was drawn. A path of one +/// point puts it to the right and below. Where that side runs out of `room` (the canvas) and the +/// other side fits, it goes on the other side; where neither fits, on the side with more room. +/// Kept in `room` ([`keep_in`]), it covers `end` only when neither side fits across or down. +fn beside(end: Pos2, dir: Option, size: Vec2, room: egui::Rect) -> Pos2 { + // `first` unless it runs out of room and `other` fits or runs out by less. + let pick = |first: f32, other: f32, lo: f32, hi: f32, len: f32| { + let over = |p: f32| (lo - p).max(0.0) + (p + len - hi).max(0.0); + if over(other) < over(first) { other } else { first } + }; + let (right, left) = (end.x + GAP, end.x - GAP - size.x); + let (below, above) = (end.y + GAP, end.y - GAP - size.y); + let x = if dir.is_none_or(|d| d.x >= 0.0) { (right, left) } else { (left, right) }; + let y = if dir.is_none_or(|d| d.y >= 0.0) { (below, above) } else { (above, below) }; + pos2(pick(x.0, x.1, room.left(), room.right(), size.x), pick(y.0, y.1, room.top(), room.bottom(), size.y)) +} + +/// The toolbar's place with no path being drawn: centered at the bottom of the canvas area `room`. +fn resting(room: egui::Rect, size: Vec2) -> Pos2 { + pos2(room.center().x - size.x / 2.0, room.bottom() - size.y) +} + +/// `p` moved, as little as it takes, for a toolbar of `size` to lie inside `room`. +fn keep_in(p: Pos2, size: Vec2, room: egui::Rect) -> Pos2 { + p.clamp(room.min, (room.max - size).max(room.min)) +} + +/// Where an unpinned toolbar of `size` sits: `home` moved by the drag `offset`, kept in `room`, +/// unless that would cover `end` (the point the path goes on from, on screen), where it sits at +/// `home` as if never dragged. +fn unpinned(home: Pos2, offset: Vec2, end: Option, size: Vec2, room: egui::Rect) -> Pos2 { + let moved = keep_in(home + offset, size, room); + if end.is_some_and(|e| egui::Rect::from_min_size(moved, size).contains(e)) { keep_in(home, size, room) } else { moved } +} + +/// What a click on the toolbar does. +enum Click { + Action(Action), + Run(&'static str, serde_json::Value), +} + +/// Is a drag under way (past the drag threshold) that began on the canvas `canvas` outside the +/// toolbar's last place `bar`? A stroke, a Space or middle-button pan and a drag from a path's first +/// point all are; a drag of the toolbar's handle is not. +fn canvas_drag(dragging: bool, press: Option, canvas: egui::Rect, bar: Option) -> bool { + dragging && press.is_some_and(|p| canvas.contains(p) && !bar.is_some_and(|b| b.contains(p))) +} + +/// The Quick Pen toolbar, while the Quick Pen tool is active, Window › Quick Pen Toolbar is on and +/// no press is dragging on the canvas. Selecting the tool turns Window › Quick Pen Toolbar on +/// ([`VectorcraftApp::try_select_tool`]). +pub(super) fn quick_pen_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) { + if !app.ui.quick_pen_bar || app.session.tool_id() != quickpen::ID { + return; + } + let (dragging, press, down) = ui.input(|i| (i.pointer.is_decidedly_dragging(), i.pointer.press_origin(), i.pointer.any_down())); + // The handle's drag moves the toolbar away from where the press began. + let handle_id = bar_id().with("handle"); + if !down { + ui.ctx().data_mut(|d| d.insert_temp(handle_id, false)); + } + let on_handle = ui.ctx().data(|d| d.get_temp::(handle_id)).unwrap_or(false); + let shown = app.ui.quick_pen_bar_place.shown_at.zip(egui::AreaState::load(ui.ctx(), bar_id()).and_then(|s| s.size)); + if canvas_drag(dragging && !on_handle, press, xf.rect, shown.map(|(at, size)| egui::Rect::from_min_size(xf.rect.min + at, size))) { + return; + } + let Some(doc) = app.session.active().map(|st| st.uid) else { return }; + let view = app.view_info(); + let end = app.session.tool_drawing_end(view); + let flip = app.session.tool_claims_key(vectorcraft_tools::ToolKey::Letter('c'), view); + let current = app.session.tool_options().get("action").and_then(serde_json::Value::as_str).and_then(Action::parse).unwrap_or_default(); + let t = Tokens::get(ui.ctx()); + let id = bar_id(); + let bounds = xf.rect.shrink(8.0); + let est = vec2(HANDLE + 5.0 * BUTTON + 6.0 * SPACING + 16.0, BUTTON + 12.0); + let size = egui::AreaState::load(ui.ctx(), id).and_then(|s| s.size).unwrap_or(est); + let end = end.map(|(p, dir)| { + let at = xf.to_screen(p); + (at, dir.map(|d| xf.to_screen(p + d) - at)) + }); + let drawing = end.is_some(); + let home = match end { + Some((at, dir)) => beside(at, dir, size, bounds), + None => resting(bounds, size), + }; + let place = &mut app.ui.quick_pen_bar_place; + // Just unpinned: follow the drawing from the pinned spot. + if !place.pinned + && let Some(at) = place.pin_at.take() + { + place.offset = Some((doc, drawing, xf.rect.min + at - home)); + } + // A drag's offset holds in the document and the kind of place (beside the drawing, or resting) + // it was made in. + let offset = place.offset.filter(|(d, beside, _)| *d == doc && *beside == drawing).map_or(Vec2::ZERO, |(_, _, o)| o); + let pos = match place.pin_at { + Some(at) => keep_in(xf.rect.min + at, size, bounds), + None => unpinned(home, offset, end.map(|(at, _)| at), size, bounds), + }; + place.shown_at = Some(pos - xf.rect.min); + // Pinned before it ever showed: hold it here. + if place.pinned && place.pin_at.is_none() { + place.pin_at = place.shown_at; + } + let pinned = place.pinned; + let mut moved = Vec2::ZERO; + let mut click: Option = None; + egui::Area::new(id).order(egui::Order::Middle).fixed_pos(pos).show(ui.ctx(), |ui| { + egui::Frame::NONE + .fill(t.panel) + .stroke(Stroke::new(1.0, t.tool_active)) + .corner_radius(CornerRadius::same(5)) + .inner_margin(egui::Margin::symmetric(8, 6)) + .shadow(egui::epaint::Shadow { offset: [0, 3], blur: 10, spread: 0, color: Color32::from_black_alpha(70) }) + .show(ui, |ui| { + // In a canvas pane narrower than the toolbar, its controls wrap onto more rows. + ui.set_max_width((bounds.width() - 18.0).max(HANDLE + SPACING + BUTTON)); + ui.horizontal_wrapped(|ui| { + ui.spacing_mut().item_spacing = vec2(SPACING, SPACING); + let (g, grip) = ui.allocate_exact_size(vec2(HANDLE, BUTTON), Sense::drag()); + let active = grip.hovered() || grip.dragged(); + ui.painter().rect_filled(g.shrink2(vec2(0.5, 4.0)), CornerRadius::same(2), if active { t.text_dim } else { t.button_border }); + if grip.dragged() { + ui.ctx().data_mut(|d| d.insert_temp(handle_id, true)); + ui.ctx().set_cursor_icon(egui::CursorIcon::Grabbing); + moved = grip.drag_delta(); + } else if grip.hovered() { + ui.ctx().set_cursor_icon(egui::CursorIcon::Grab); + } + let actions = [ + (Action::Line, "dc-line", tl!("Straight Line")), + (Action::ContinuousArc, "spline", tl!("Continuous Arc")), + (Action::SharpArc, "dc-arc", tl!("Sharp Corner Arc")), + ]; + for (action, icon, tip) in actions { + if widgets::icon_button(ui, icon, tip, current == action, BUTTON).clicked() { + click = Some(Click::Action(action)); + } + } + if widgets::icon_button_enabled(ui, "flip-horizontal-2", tl!("Flip Arc"), false, flip, BUTTON).clicked() { + click = Some(Click::Run("tool.quickPen.flipArc", json!({}))); + } + let more = widgets::icon_button(ui, "ellipsis", tl!("More Options"), false, BUTTON); + egui::Popup::menu(&more).show(|ui| { + ui.set_min_width(170.0); + let items = [ + (tl!("Hide Toolbar"), "window.quickPenToolbar", false), + (tl!("Pin Toolbar Position"), "window.quickPenToolbar.pin", pinned), + (tl!("Reset Toolbar Position"), "window.quickPenToolbar.reset", false), + ]; + for (label, cmd, checked) in items { + if widgets::menu_item(ui, label, true, checked) { + click = Some(Click::Run(cmd, json!({}))); + } + } + }); + }); + }); + }); + if moved != Vec2::ZERO { + let to = keep_in(pos + moved, size, bounds); + let place = &mut app.ui.quick_pen_bar_place; + if place.pinned { + place.pin_at = Some(to - xf.rect.min); + } else { + place.offset = Some((doc, drawing, to - home)); + } + ui.ctx().request_repaint(); + } + let r = match click { + Some(Click::Action(a)) => app.run("tool.setOption", json!({"key": "action", "value": a.name()})).map(|_| ()), + Some(Click::Run(cmd, p)) => app.run(cmd, p).map(|_| ()), + None => Ok(()), + }; + if let Err(e) = r { + app.ui.status = e; + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The toolbar sits off what was drawn: ahead of a path drawn right and down, behind-left and + /// above for one drawn left and up, and to the right and below a single point. + #[test] + fn the_toolbar_sits_beside_the_end_away_from_the_drawing() { + let (end, size) = (pos2(500.0, 300.0), vec2(180.0, 40.0)); + let room = egui::Rect::from_min_max(pos2(8.0, 8.0), pos2(808.0, 608.0)); + assert_eq!(beside(end, Some(vec2(1.0, 0.0)), size, room), pos2(524.0, 324.0)); + assert_eq!(beside(end, Some(vec2(-1.0, -1.0)), size, room), pos2(500.0 - 24.0 - 180.0, 300.0 - 24.0 - 40.0)); + assert_eq!(beside(end, Some(vec2(0.0, 1.0)), size, room), pos2(524.0, 324.0)); + assert_eq!(beside(end, Some(vec2(-1.0, 0.5)), size, room), pos2(296.0, 324.0)); + assert_eq!(beside(end, None, size, room), pos2(524.0, 324.0)); + assert_eq!(resting(room, size), pos2(318.0, 568.0)); + // Near the canvas's bottom right corner, the side that runs off it gives way to the other. + let corner = pos2(700.0, 580.0); + assert_eq!(beside(corner, Some(vec2(1.0, 1.0)), size, room), pos2(700.0 - 24.0 - 180.0, 580.0 - 24.0 - 40.0)); + // Near the top left corner, a path heading up and left still gets a toolbar off its end. + let corner = pos2(30.0, 30.0); + assert_eq!(beside(corner, Some(vec2(-1.0, -1.0)), size, room), pos2(54.0, 54.0)); + // On a canvas too narrow for either side across, the toolbar goes on the side with more + // room and stays off the end by going below it. + let narrow = egui::Rect::from_min_max(pos2(8.0, 8.0), pos2(208.0, 608.0)); + let end = pos2(60.0, 300.0); + let at = keep_in(beside(end, Some(vec2(-1.0, 1.0)), size, narrow), size, narrow); + assert_eq!(at, pos2(28.0, 324.0)); + assert!(!egui::Rect::from_min_size(at, size).contains(end)); + } + + /// Any drag that began on the canvas hides the toolbar, whether or not the tool has a press + /// (a pan does not); a drag that began on the toolbar, and no drag, do not. + #[test] + fn a_drag_that_began_on_the_canvas_hides_the_toolbar() { + let canvas = egui::Rect::from_min_max(pos2(0.0, 0.0), pos2(800.0, 600.0)); + let bar = Some(egui::Rect::from_min_size(pos2(300.0, 500.0), vec2(180.0, 40.0))); + assert!(canvas_drag(true, Some(pos2(100.0, 100.0)), canvas, bar), "a pan or stroke on the canvas"); + assert!(canvas_drag(true, Some(pos2(100.0, 100.0)), canvas, None), "no toolbar shown yet"); + assert!(!canvas_drag(false, Some(pos2(100.0, 100.0)), canvas, bar), "a click, not a drag"); + assert!(!canvas_drag(true, Some(pos2(310.0, 510.0)), canvas, bar), "the toolbar's own drag"); + assert!(!canvas_drag(true, Some(pos2(900.0, 100.0)), canvas, bar), "a drag in another panel"); + assert!(!canvas_drag(true, None, canvas, bar)); + } + + /// A drag's offset moves the toolbar from its place, unless that would put it over the point + /// the path goes on from. + #[test] + fn a_dragged_toolbar_never_covers_the_end() { + let size = vec2(180.0, 40.0); + let room = egui::Rect::from_min_max(pos2(8.0, 8.0), pos2(808.0, 608.0)); + let (end, home) = (pos2(500.0, 300.0), pos2(524.0, 324.0)); + assert_eq!(unpinned(home, vec2(30.0, 40.0), Some(end), size, room), pos2(554.0, 364.0)); + assert_eq!(unpinned(home, vec2(-60.0, -40.0), Some(end), size, room), home, "over the end"); + assert_eq!(unpinned(home, vec2(-60.0, -40.0), None, size, room), pos2(464.0, 284.0)); + assert_eq!(unpinned(home, vec2(900.0, 0.0), Some(end), size, room), pos2(628.0, 324.0), "kept on the canvas"); + } +} diff --git a/crates/ui-egui/src/canvas/task_bar.rs b/crates/ui-egui/src/canvas/task_bar.rs index c133c003f8..03ced4f7c6 100644 --- a/crates/ui-egui/src/canvas/task_bar.rs +++ b/crates/ui-egui/src/canvas/task_bar.rs @@ -19,6 +19,14 @@ pub(crate) fn task_bar_shows_fonts(ctx: &egui::Context) -> bool { task_bar_rect(ctx).is_some() && ctx.data(|d| d.get_temp::(task_bar_id().with("fonts")).unwrap_or(false)) } +/// The actions and chips the Contextual Task Bar offered where it was last drawn, before Bar +/// Actions left any out, as More Options › Bar Actions lists them: each one's name, its id in +/// [`TASK_BAR_ACTIONS`] or [`TASK_BAR_CHIPS`] (none: Bar Actions cannot turn it off) and whether it +/// shows. +pub(crate) fn task_bar_offered(ctx: &egui::Context) -> Vec<(&'static str, Option<&'static str>, bool)> { + ctx.data(|d| d.get_temp(task_bar_id().with("offered")).unwrap_or_default()) +} + /// Whether the objects `ids` (or anything inside them) are painted with a colour: a solid colour, /// a gradient's stops or a mesh's points, which Recolor Artwork can change. pub(crate) fn has_colors(doc: &vectorcraft_doc::Document, ids: &[vectorcraft_doc::NodeId]) -> bool { @@ -182,7 +190,10 @@ pub(crate) fn task_bar_shows_type(app: &VectorcraftApp) -> bool { /// On a blank canvas, a document with no artwork and a selection tool in use, it sits under the /// active artboard and offers Draw (Pencil) and Place Image. /// Its handle drags it anywhere on the canvas; unpinned it keeps that offset as it follows the -/// selection, pinned it stays put ([`crate::state::TaskBarPlace`]). +/// selection, pinned it stays put ([`crate::state::TaskBarPlace`]). More Options › Bar Actions +/// turns each action and chip the bar offers on or off ([`TASK_BAR_ACTIONS`], [`TASK_BAR_CHIPS`]); +/// the bar leaves out the ones that are off, and Reset Bar Actions shows them all again. With every +/// one of them off, the bar still shows its handle and More Options, where they turn back on. pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) { let t = Tokens::get(ui.ctx()); let on_artboards = app.session.tool_id() == "artboard"; @@ -351,6 +362,13 @@ pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) { let paints = chip_paints(app, ui.ctx()); let colored = has_colors(&st.doc, &st.selection.objects); let doc = st.uid; + // Every action and chip the bar offers here, with its name and its id in TASK_BAR_ACTIONS or + // TASK_BAR_CHIPS (none: Bar Actions cannot turn it off), for More Options › Bar Actions; the + // ones that are off there are left out of the bar. + let hidden = &app.ui.task_bar_hidden_actions; + let mut offered: Vec<(&'static str, Option<&'static str>)> = + items.iter().map(|(label, _, cmd, params)| (*label, action_id(cmd, params))).collect(); + items.retain(|(_, _, cmd, params)| action_id(cmd, params).is_none_or(|a| !hidden.contains(a))); let bounds = xf.rect.shrink(8.0); // The canvas's width less the frame's margins and stroke. let room = bounds.width() - BAR_FRAME; @@ -371,6 +389,13 @@ pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) { .into_iter() .filter_map(|(shown, chip)| shown.then_some(chip)) .collect(); + offered.extend(chips.iter().map(|c| (c.label(shape.is_some()), Some(c.id(shape.is_some()))))); + let chips: Vec = chips.into_iter().filter(|c| !hidden.contains(c.id(shape.is_some()))).collect(); + // Bar Actions reads this list through task_bar_offered while its menu is open. + let offered: Vec<(&'static str, Option<&'static str>, bool)> = + offered.into_iter().map(|(label, action)| (label, action, action.is_none_or(|a| !hidden.contains(a)))).collect(); + ui.ctx().data_mut(|d| d.insert_temp(task_bar_id().with("offered"), offered)); + let any_hidden = !hidden.is_empty(); let widths: Vec = items.iter().map(|(label, _, cmd, _)| item_width(ui, label, cmd)).collect(); let fidelity = app.session.tool_options()["fidelity"].as_f64(); let font_w = fonts.then(|| { @@ -498,6 +523,21 @@ pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) { run = Some((cmd, json!({}))); } } + // The actions and chips the bar offers for this selection or tool, each + // checked while it shows, which turns it on or off; then Reset Bar + // Actions, which shows every action again. + ui.menu_button(format!(" {}", tl!("Bar Actions")), |ui| { + ui.set_min_width(170.0); + for (label, action, shown) in task_bar_offered(ui.ctx()) { + let Some(action) = action else { continue }; + if widgets::menu_item_name(ui, bar_action_name(label), true, shown) { + run = Some(("window.taskBar.actions", json!({ "action": action }))); + } + } + }); + if widgets::menu_item(ui, tl!("Reset Bar Actions"), any_hidden, false) { + run = Some(("window.taskBar.resetActions", json!({}))); + } ui.separator(); if widgets::menu_item(ui, tl!("Show Properties Panel"), true, false) { run = Some(("window.panel", json!({"panel": "properties"}))); @@ -579,6 +619,112 @@ impl Chip { Chip::Recolor | Chip::Lock => 30.0, } } + + /// The chip's id in [`TASK_BAR_CHIPS`]; Lock is `shapeProperties` while it shows a basic + /// `shape`'s properties. + fn id(self, shape: bool) -> &'static str { + match self { + Chip::Fill => "fill", + Chip::Stroke => "stroke", + Chip::Recolor => "recolor", + Chip::Lock if shape => "shapeProperties", + Chip::Lock => "lock", + } + } + + /// The chip's name in More Options › Bar Actions, translated. + fn label(self, shape: bool) -> &'static str { + match self { + Chip::Fill => tl!("Fill"), + Chip::Stroke => tl!("Stroke"), + Chip::Recolor => tl!("Recolor Artwork"), + Chip::Lock if shape => tl!("Shape Properties"), + Chip::Lock => tl!("Lock"), + } + } +} + +/// The Contextual Task Bar's actions that More Options › Bar Actions turns on or off +/// (`window.taskBar.actions {action, visible?}`): each action's id, the command its button runs and +/// the `tool` that command names, if any. An action that is off stays out of the bar, and More +/// Options does not list it either; turning one off changes only the bar. Every action starts on. +pub(crate) const TASK_BAR_ACTIONS: [(&str, &str, Option<&str>); 37] = [ + ("imageTrace", TASK_BAR_IMAGE_TRACE, None), + ("cropImage", "ui.cropImage", None), + ("removeBackground", crate::addons::image::REMOVE_BACKGROUND, None), + ("removeAnchorPoints", "path.removeAnchors", None), + ("join", "path.join", None), + ("cutPath", "path.cutAtAnchors", None), + ("convertToCorner", TASK_BAR_TO_CORNER, None), + ("convertToSmooth", TASK_BAR_TO_SMOOTH, None), + ("group", "object.group", None), + ("makeClippingMask", "object.clippingMask.make", None), + ("unite", "object.pathfinder.unite", None), + ("expand", "imageTrace.expand", None), + ("editClippingPath", "object.clippingMask.editMask", None), + ("releaseClippingMask", "object.clippingMask.release", None), + ("ungroup", "object.ungroup", None), + ("isolate", "object.isolate", None), + ("editPath", "tool.select", Some("directSelection")), + ("releaseCompoundPath", "object.compoundPath.release", None), + ("createOutlines", "type.createOutlines", None), + ("convertToPointType", "type.convertToPointType", None), + ("convertToAreaType", "type.convertToAreaType", None), + ("typeOnPathOptions", "type.pathOptions", None), + ("centerOnTop", "type.pathCenter.top", None), + ("centerOnBottom", "type.pathCenter.bottom", None), + ("dynamicText", "type.dynamicText", None), + ("offsetPath", "object.path.offsetPath", None), + ("simplify", "object.path.simplify", None), + ("smooth", "object.path.smooth", None), + ("duplicate", "edit.duplicate", None), + ("drawPencil", "tool.select", Some("pencil")), + ("placeImage", "file.place", None), + ("fidelity", TASK_BAR_FIDELITY, None), + ("smoothToolOptions", "tool.options", Some("smooth")), + ("resizeArtboard", TASK_BAR_ARTBOARD_OPTIONS, None), + ("duplicateArtboards", TASK_BAR_DUPLICATE_ARTBOARDS, None), + ("rearrangeArtboards", TASK_BAR_REARRANGE_ARTBOARDS, None), + ("exportArtboards", "file.exportForScreens", None), +]; + +/// The ids of the Contextual Task Bar's chips that More Options › Bar Actions turns on or off, +/// as [`TASK_BAR_ACTIONS`] are. +pub(crate) const TASK_BAR_CHIPS: [&str; 5] = ["fill", "stroke", "recolor", "lock", "shapeProperties"]; + +/// Whether `id` names one of the Contextual Task Bar's actions or chips. +pub(crate) fn is_task_bar_action(id: &str) -> bool { + TASK_BAR_ACTIONS.iter().any(|a| a.0 == id) || TASK_BAR_CHIPS.contains(&id) +} + +/// The id in [`TASK_BAR_ACTIONS`] of the bar's item that runs `cmd` with `params`. +fn action_id(cmd: &str, params: &serde_json::Value) -> Option<&'static str> { + let tool = params.get("tool").and_then(serde_json::Value::as_str); + TASK_BAR_ACTIONS.iter().find(|(_, c, t)| *c == cmd && *t == tool).map(|a| a.0) +} + +/// The name More Options › Bar Actions lists for the bar's item `label`: without a field's colon +/// (a full-width one too), the space some languages put before it, or a final ellipsis (`…` or +/// `...`), in whichever order they come. +pub(crate) fn bar_action_name(label: &str) -> &str { + let mut name = label.trim_end(); + loop { + let rest = name.trim_end_matches([':', ':', '…']); + let rest = rest.strip_suffix("...").unwrap_or(rest).trim_end(); + if rest == name { + return name; + } + name = rest; + } +} + +/// Reads the Contextual Task Bar's actions and chips that are off, as kept in the preferences. Ids +/// the bar does not have are dropped, and a value that is not a list of strings reads as none off, +/// so the bar shows every action. +pub(crate) fn read_hidden_task_bar_actions<'de, D: serde::Deserializer<'de>>(d: D) -> Result, D::Error> { + let value = ::deserialize(d)?; + let ids = value.as_array().into_iter().flatten().filter_map(serde_json::Value::as_str); + Ok(ids.filter(|id| is_task_bar_action(id)).map(str::to_string).collect()) } /// What a click on one of the bar's [`Chip`]s does: make the Fill (`true`) or the Stroke active and diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 35c9fd3737..d5244aa234 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -4357,7 +4357,8 @@ fn a_pan_fills_the_area() { /// With the web build's setting (`waits_for_still`, no render worker), a heavy document's canvas /// is not rendered while the view moves: each frame draws the frame shown moved and scaled with /// the view and asks for a frame within STILL_SECS. The canvas renders once the view has been -/// still for STILL_SECS, and at once after an edit. With a worker's build settings the same frames render at once, as +/// still for STILL_SECS. An edit while the view moves draws the part it changed into the frame +/// shown, and one that changes most of the frame renders it whole at once. With a worker's build settings the same frames render at once, as /// before. #[test] fn without_a_worker_a_heavy_canvas_is_reprojected_until_the_view_is_still() { @@ -4421,15 +4422,39 @@ fn without_a_worker_a_heavy_canvas() { let now = app.canvas.key.clone().unwrap(); assert_eq!((now.cx, now.zoom), (app.view().unwrap().center.x, app.view().unwrap().zoom), "rendered for the view"); assert!((b.min - rect.min).length() < 0.01 && (b.max - rect.max).length() < 0.01, "{b:?} over {rect:?}"); - // An edit renders at once, even while the view moves. + // An edit while the view moves shows at once: the part it changed is drawn into the frame + // shown, at the view that frame was rendered for, and the frame stays drawn reprojected until + // the view is still (#8688). app.canvas.last_ms = 50.0; app.view_mut().unwrap().center.y += 10.0; frame(&mut app); assert_eq!(app.canvas.key.as_ref(), Some(&now), "waiting"); - app.session.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + app.session.execute("shape.rectangle", &json!({"x": 110, "y": 60, "width": 20, "height": 20})).unwrap(); + let render_ms = app.canvas.last_ms; + let (b, delay) = frame(&mut app); + let k = app.canvas.key.clone().unwrap(); + assert_eq!(k.revision, app.session.active().unwrap().revision, "the edit is drawn"); + assert_eq!((k.cx, k.cy, k.zoom), (now.cx, now.cy, now.zoom), "at the view of the frame shown"); + assert_eq!(app.canvas.last_ms, render_ms, "the frame was not rendered whole"); + let (old, new) = (Xf::new(rect, &View { center: Point::new(now.cx, now.cy), ..*app.view().unwrap() }), Xf::new(rect, app.view().unwrap())); + let (a, z) = (new.to_screen(old.to_doc(rect.min)), new.to_screen(old.to_doc(rect.max))); + assert!((b.min - a).length() < 0.01 && (b.max - z).length() < 0.01, "{b:?}: the frame shown at {a:?} to {z:?}"); + assert!(delay <= std::time::Duration::from_secs_f64(STILL_SECS), "a frame within STILL_SECS: {delay:?}"); + let mut frames = 0; + while app.canvas.key.as_ref() == Some(&k) && frames < 60 { + frames += 1; + frame(&mut app); + } + let k = app.canvas.key.clone().unwrap(); + assert_eq!((k.revision, k.cy), (app.session.active().unwrap().revision, app.view().unwrap().center.y), "rendered once still"); + // An edit that changes more than half of the frame renders whole at once, view and all. + app.canvas.last_ms = 50.0; + app.view_mut().unwrap().center.y += 10.0; + frame(&mut app); + app.session.execute("shape.rectangle", &json!({"x": -1000, "y": -1000, "width": 3000, "height": 3000})).unwrap(); frame(&mut app); let k = app.canvas.key.clone().unwrap(); - assert_eq!((k.revision, k.cy), (app.session.active().unwrap().revision, app.view().unwrap().center.y), "rendered after the edit"); + assert_eq!((k.revision, k.cy), (app.session.active().unwrap().revision, app.view().unwrap().center.y), "rendered whole after the edit"); // With a worker's build settings and no worker (VECTORCRAFT_SYNC_RENDER), a heavy document // renders every change of view at once. app.canvas.waits_for_still = false; @@ -4439,6 +4464,48 @@ fn without_a_worker_a_heavy_canvas() { assert_eq!(app.canvas.key.as_ref().map(|k| k.cx), Some(app.view().unwrap().center.x), "rendered at once"); } +/// With the web build's setting (`waits_for_still`, no render worker), a heavy document's view +/// that stops moving while a drag goes on editing the document renders whole once the view has +/// been still for STILL_SECS: each edit is drawn into the frame shown and does not start the wait +/// again. +#[test] +fn without_a_worker_edits_while_the_view_is_still_do_not_hold_off_the_render() { + keeping_color_settings(edits_while_the_view_is_still); +} + +fn edits_while_the_view_is_still() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + app.session.execute("shape.rectangle", &json!({"x": 100, "y": 50, "width": 200, "height": 200})).unwrap(); + app.canvas.worker_started = true; // no worker, as in the web build + app.canvas.waits_for_still = true; + let ctx = egui::Context::default(); + let frame = |app: &mut VectorcraftApp| { + let raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))), ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| show(app, ui)); + out.textures_delta.clear(); + }; + frame(&mut app); // the first frame fits the view to the artboard + frame(&mut app); + app.canvas.last_ms = 50.0; + // The view moves once (a drag at an edge of the canvas scrolls it) and then stays still. + app.view_mut().unwrap().center.y += 10.0; + frame(&mut app); + let shown = app.canvas.key.clone().unwrap(); + assert_ne!(shown.cy, app.view().unwrap().center.y, "waiting"); + // The drag edits the document on every frame, at 60 fps (egui's input time without a clock). + let mut frames = 0; + while app.canvas.key.as_ref().is_none_or(|k| k.cy != app.view().unwrap().center.y) && frames < 60 { + frames += 1; + let x = 110 + (frames % 10) * 5; + app.session.execute("shape.rectangle", &json!({"x": x, "y": 60, "width": 4, "height": 4})).unwrap(); + frame(&mut app); + let k = app.canvas.key.as_ref().unwrap(); + assert_eq!(k.revision, app.session.active().unwrap().revision, "each edit is drawn"); + } + assert!((11..=13).contains(&frames), "rendered whole about STILL_SECS after the view stopped: {frames} frames"); +} + /// [`still_wait`] waits while only the view changes on a slow canvas: each change starts /// STILL_SECS again. It does not wait for a light document, a still view, a clock that went /// back, an edit, a switch into Pixel Preview or a canvas with no frame shown. @@ -15290,3 +15357,250 @@ fn auto_spell_check_is_a_toggle_of_the_canvas_lines() { assert_eq!(count(&mut app), 0, "off"); assert!(app.canvas.spelling.lines.is_empty(), "no node is kept"); } + +/// #8363: Trim View hides the ruler guides, the guide paths and the grid while it is on, and they +/// are neither snapped to nor picked, as hidden guides are; turned off, they come back as they +/// were. The rulers stay. +#[test] +fn trim_view_hides_the_guides_and_the_grid() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.canvas.worker_started = true; // render on this thread + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + app.session.execute("guide.add", &json!({"vertical": true, "pos": 100})).unwrap(); + app.run("shape.rectangle", json!({"x": 150, "y": 100, "width": 100, "height": 100})).unwrap(); + app.run("view.guides.make", json!({})).unwrap(); + app.run("select.none", json!({})).unwrap(); + (app.ui.view.grid, app.ui.view.guides, app.ui.view.rulers) = (true, true, true); + let (red, green) = (Color32::from_rgb(255, 0, 0), Color32::from_rgb(0, 255, 0)); + app.session.execute("prefs.set", &json!({"values": {"gridColor": "#ff0000", "guideColor": "#00ff00"}})).unwrap(); + let ctx = egui::Context::default(); + // → (a gridline, a ruler guide, guide paths in the art, guides snapped to and picked). + let drawn = |app: &mut VectorcraftApp| { + let s = shapes(app, &ctx); + let line = |c: Color32| s.iter().any(|s| matches!(s, Shape::LineSegment { stroke, .. } if stroke.color == c)); + let guide_paths = !app.canvas.shown.as_ref().unwrap().1.hide_guides; + (line(red), line(green), guide_paths, app.view_info().guides) + }; + assert_eq!(drawn(&mut app), (true, true, true, true), "Trim View off: all of them"); + + app.run("view.trimView", json!({})).unwrap(); + assert_eq!(drawn(&mut app), (false, false, false, false), "Trim View on: none of them"); + assert!(app.ui.view.grid && app.ui.view.guides && app.ui.view.rulers, "the choices stay, and so do the rulers"); + + app.run("view.trimView", json!({})).unwrap(); + assert_eq!(drawn(&mut app), (true, true, true, true), "Trim View off: back as they were"); + + // Hidden before, they stay hidden after. + app.run("view.guides", json!({})).unwrap(); + app.run("view.trimView", json!({})).unwrap(); + app.run("view.trimView", json!({})).unwrap(); + assert_eq!(drawn(&mut app), (true, false, false, false), "guides hidden before Trim View stay hidden"); +} + +/// #8363: a selected guide path is deselected when Trim View hides it, as Hide Guides does (#3219). +#[test] +fn trim_view_deselects_selected_guide_paths() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let id = app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap(); + app.run("view.guides.make", json!({})).unwrap(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + assert_eq!(app.session.active().unwrap().selection.objects, vec![vectorcraft_doc::NodeId(id)]); + + app.run("view.trimView", json!({})).unwrap(); + + assert!(app.session.active().unwrap().selection.objects.is_empty()); +} + +/// #8363: Trim View hides the guides, so a guide dragged or double-clicked out of a ruler while it +/// is on would be made but never seen. None is: no preview line, no guide, no undo step, the +/// stored Show/Hide Guides choice is left alone, and the status line says why. A drag already +/// going when Trim View turns on ends as a release off the canvas does. +#[test] +fn trim_view_makes_no_guide_from_the_rulers() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + app.ui.view.rulers = true; + app.ui.view.guides = false; + app.ui.view.smart_guides = false; + app.ui.view.snap_to_point = false; + app.ui.view.trim_view = true; + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + let rect = app.canvas_rect.unwrap(); + let from = pos2(rect.center().x, rect.top() - RULER / 2.0); + let at = pos2(rect.center().x, rect.top() + 120.0); + let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + let across = |s: &Shape| { + matches!(s, Shape::LineSegment { points, .. } + if (points[0].y - at.y).abs() <= 2.0 && points[0].y == points[1].y && (points[1].x - points[0].x).abs() >= rect.width() - 0.5) + }; + let count = |app: &VectorcraftApp| app.session.active().unwrap().doc.ruler_guides().len(); + let steps = |app: &VectorcraftApp| app.session.active().unwrap().history.undo.len(); + let before = steps(&app); + + // A drag: nothing previews and nothing is made. + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(from)]); + frame(&mut app, &ctx, vec![button(from, true)]); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at)]); + assert!(!shapes(&mut app, &ctx).iter().any(across), "no guide previews"); + assert!(!app.session.ruler_guide_dragging()); + frame(&mut app, &ctx, vec![button(at, false)]); + assert_eq!(count(&app), 0, "no guide from a drag"); + assert!(!app.ui.view.guides, "the stored choice is left alone"); + assert_eq!(app.ui.status, crate::menus::TRIM_VIEW_HIDES); + + // A double-click: nothing either. + app.ui.status.clear(); + let click = |app: &mut VectorcraftApp| { + frame(app, &ctx, vec![egui::Event::PointerMoved(from)]); + frame(app, &ctx, vec![button(from, true)]); + frame(app, &ctx, vec![button(from, false)]); + }; + click(&mut app); + click(&mut app); + assert_eq!(count(&app), 0, "no guide from a double-click"); + assert!(!app.ui.view.guides); + assert_eq!(app.ui.status, crate::menus::TRIM_VIEW_HIDES); + assert_eq!(steps(&app), before, "no undo step"); + + // Trim View turned on during a drag: the drag ends without a guide. + app.ui.view.trim_view = false; + let from2 = pos2(rect.center().x + 30.0, rect.top() - RULER / 2.0); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(from2)]); + frame(&mut app, &ctx, vec![button(from2, true)]); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at)]); + assert!(app.session.ruler_guide_dragging(), "the drag started with Trim View off"); + app.ui.view.trim_view = true; + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(pos2(at.x + 5.0, at.y))]); + assert!(!app.session.ruler_guide_dragging(), "ended"); + assert!(!shapes(&mut app, &ctx).iter().any(across), "no guide previews"); + frame(&mut app, &ctx, vec![button(at, false)]); + assert_eq!(count(&app), 0, "no guide from the drag Trim View interrupted"); + assert_eq!(steps(&app), before, "no undo step"); + + // With Trim View off again, a drag makes a guide as before. + app.ui.view.trim_view = false; + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(from)]); + frame(&mut app, &ctx, vec![button(from, true)]); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at)]); + frame(&mut app, &ctx, vec![button(at, false)]); + assert_eq!(count(&app), 1); + assert!(app.ui.view.guides, "the new guide shows"); +} + +/// #8363: a guide drag Trim View cancelled stays cancelled until the button is released. Trim +/// View turned off again before the release does not start a new guide: the release makes none +/// and adds no undo step. The next drag works as before. +#[test] +fn a_ruler_drag_trim_view_cancelled_stays_cancelled_until_released() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + app.ui.view.rulers = true; + app.ui.view.smart_guides = false; + app.ui.view.snap_to_point = false; + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + let rect = app.canvas_rect.unwrap(); + let from = pos2(rect.center().x, rect.top() - RULER / 2.0); + let at = pos2(rect.center().x, rect.top() + 120.0); + let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + let count = |app: &VectorcraftApp| app.session.active().unwrap().doc.ruler_guides().len(); + let steps = |app: &VectorcraftApp| app.session.active().unwrap().history.undo.len(); + let before = steps(&app); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(from)]); + frame(&mut app, &ctx, vec![button(from, true)]); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at)]); + assert!(app.session.ruler_guide_dragging()); + app.ui.view.trim_view = true; + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(pos2(at.x, at.y + 5.0))]); + assert!(!app.session.ruler_guide_dragging(), "Trim View ends the drag"); + app.ui.view.trim_view = false; + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(pos2(at.x, at.y + 10.0))]); + assert!(!app.session.ruler_guide_dragging(), "turned off again, no new guide starts"); + frame(&mut app, &ctx, vec![button(pos2(at.x, at.y + 10.0), false)]); + assert_eq!(count(&app), 0, "the release makes no guide"); + assert_eq!(steps(&app), before, "no undo step"); + // The next drag makes a guide. + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(from)]); + frame(&mut app, &ctx, vec![button(from, true)]); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at)]); + frame(&mut app, &ctx, vec![button(at, false)]); + assert_eq!(count(&app), 1); +} + +/// #8363: Trim View turned on or off during a drag of the rulers' origin out of their corner +/// cancels it, as hiding the rulers does: the snap targets gathered at its start would hold +/// guides Trim View hides. The origin is left where it was. A drag wholly with Trim View on, or +/// wholly off, sets it. +#[test] +fn trim_view_toggled_during_a_ruler_origin_drag_cancels_it() { + for (start, end, sets) in [(false, true, false), (true, false, false), (true, true, true), (false, false, true)] { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + app.session.execute("guide.add", &json!({"vertical": true, "pos": 150})).unwrap(); + app.ui.view.rulers = true; + app.ui.view.trim_view = start; + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + let rect = app.canvas_rect.unwrap(); + let xf = Xf::new(rect, app.view().unwrap()); + let origin = |app: &VectorcraftApp| { + let d = &app.session.active().unwrap().doc; + format!("{:?} {:?}", d.ruler_origin, d.artboard_ruler_origins) + }; + let was = origin(&app); + let from = pos2(rect.left() - RULER / 2.0, rect.top() - RULER / 2.0); + let at = xf.to_screen(Point::new(151.0, 100.0)); + let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(from)]); + frame(&mut app, &ctx, vec![button(from, true)]); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at)]); + assert!(crate::canvas::ruler_origin_dragging(&ctx), "{start} {end}: dragging"); + app.ui.view.trim_view = end; + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at + vec2(1.0, 0.0))]); + frame(&mut app, &ctx, vec![button(at + vec2(1.0, 0.0), false)]); + assert_eq!(origin(&app) != was, sets, "Trim View {start} then {end}: origin set {sets}"); + } +} + +/// #8363: a Selection move begun with the guides shown gathers the ruler guides to snap to. When +/// they stop showing during the move (Trim View or Hide Guides turned on), it no longer snaps to +/// them; with them shown throughout, it does. +#[test] +fn a_move_stops_snapping_to_guides_hidden_during_it() { + // What hides the guides mid-move (none: they stay shown), and whether the move then snaps. + for (hide, snaps) in [(None, true), (Some("trim"), false), (Some("guides"), false)] { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run("shape.rectangle", json!({"x": 50, "y": 50, "width": 50, "height": 50})).unwrap(); + app.session.execute("guide.add", &json!({"vertical": true, "pos": 200})).unwrap(); + app.select_tool("selection"); + app.ui.view.smart_guides = false; + app.ui.view.snap_to_point = true; + app.ui.view.guides = true; + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + let rect = app.canvas_rect.unwrap(); + let xf = Xf::new(rect, app.view().unwrap()); + let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + // Grabbed at its centre, moved first well away from the guide, then 1.5 px short of it. + let grab = xf.to_screen(Point::new(75.0, 75.0)); + let away = xf.to_screen(Point::new(120.0, 75.0)); + let near = xf.to_screen(Point::new(200.0, 75.0)) - vec2(1.5, 0.0); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(grab)]); + frame(&mut app, &ctx, vec![button(grab, true)]); + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(away)]); + match hide { + Some("trim") => app.ui.view.trim_view = true, + Some(_) => app.ui.view.guides = false, + None => {} + } + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(near)]); + frame(&mut app, &ctx, vec![button(near, false)]); + let b = app.session.active().unwrap().doc.art_bounds().unwrap(); + let centre = (b.x0 + b.x1) / 2.0; + assert_eq!((centre - 200.0).abs() < 1e-6, snaps, "{hide:?}: the grabbed centre at {centre}"); + assert!((centre - xf.to_doc(near).x).abs() < 1e-6 || snaps, "{hide:?}: unsnapped, it follows the pointer: {centre}"); + } +} diff --git a/crates/ui-egui/src/chrome.rs b/crates/ui-egui/src/chrome.rs index 261534e643..511967d45f 100644 --- a/crates/ui-egui/src/chrome.rs +++ b/crates/ui-egui/src/chrome.rs @@ -157,8 +157,7 @@ pub fn app_bar(app: &mut VectorcraftApp, ui: &mut Ui) { }) .inner; if clicked && enabled { - app.ui.palette_open = !app.ui.palette_open; - app.ui.palette_query.clear(); + crate::palette::toggle(app); } if learn { let shown = crate::panels::learn::visible(&app.ui); diff --git a/crates/ui-egui/src/chrome/status_bar.rs b/crates/ui-egui/src/chrome/status_bar.rs index 57b1b2a457..126cc956f3 100644 --- a/crates/ui-egui/src/chrome/status_bar.rs +++ b/crates/ui-egui/src/chrome/status_bar.rs @@ -209,7 +209,8 @@ pub(super) fn info_text(app: &VectorcraftApp) -> (String, Option) { (text, Some(next)) } StatusBarShow::Undos => { - let text = st.map(|d| format!("{}: {} {}: {}", tl!("Undos"), d.history.undo.len(), tl!("Redos"), d.history.redo.len())); + let (undos, redos) = (crate::i18n::colon(tl!("Undos")), crate::i18n::colon(tl!("Redos"))); + let text = st.map(|d| format!("{undos} {} {redos} {}", d.history.undo.len(), d.history.redo.len())); (text.unwrap_or_default(), None) } StatusBarShow::ColorProfile => (st.map(|d| color_profile_name(&d.doc)).unwrap_or_default(), None), diff --git a/crates/ui-egui/src/chrome/tests.rs b/crates/ui-egui/src/chrome/tests.rs index 5a4d92ab6d..3b889b1f09 100644 --- a/crates/ui-egui/src/chrome/tests.rs +++ b/crates/ui-egui/src/chrome/tests.rs @@ -1127,6 +1127,12 @@ fn the_status_bar_info_field_shows_the_chosen_readout() { app.run("edit.undo", json!({})).unwrap(); assert_eq!(counts(&app), format!("Undos: {before} Redos: 1")); assert!(status_after(&mut app, &ctx, 0.1, vec![]).iter().any(|t| t.text == counts(&app)), "the redo step counts"); + // The labels take the UI language's colon (#7991). + let fr = crate::i18n::Lang::from_code("fr").unwrap(); + crate::i18n::set_current(fr); + let (french, _) = super::status_bar::info_text(&app); + crate::i18n::set_current(crate::i18n::Lang::EN); + assert_eq!(french, format!("{}\u{a0}: {before} {}\u{a0}: 1", crate::i18n::tr(fr, "Undos"), crate::i18n::tr(fr, "Redos"))); app.run("view.statusBarShow", json!({"show": "colorProfile"})).unwrap(); let working = vectorcraft_color::cms::working_settings(); diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 6d2417a0fd..218312750d 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -268,6 +268,11 @@ pub fn inspect(app: &VectorcraftApp, ctx: &egui::Context) -> Value { "pinned": app.ui.task_bar_place.pinned, "rect": crate::canvas::task_bar_rect(ctx).map(|r| json!([r.left(), r.top(), r.width(), r.height()])), }, + // The Quick Pen toolbar: pinned (not saved either) and where it shows. + "quickPenToolbar": { + "pinned": app.ui.quick_pen_bar_place.pinned, + "rect": crate::canvas::quick_pen_bar_rect(ctx).map(|r| json!([r.left(), r.top(), r.width(), r.height()])), + }, // The Free Transform tool's widget, where it shows. "freeTransformWidget": crate::free_transform::rect(ctx).map(|r| json!([r.left(), r.top(), r.width(), r.height()])), "view": app.view().map(|v| serde_json::to_value(v).unwrap_or_default()), diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 1f34a72f9a..a24755ab12 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -25,6 +25,7 @@ pub mod brush_replace_art; pub mod bullets_numbering; pub mod char_style_options; pub mod check_spelling; +pub mod circle_options; pub mod color_balance; pub mod color_group_options; pub mod color_guide_options; @@ -155,6 +156,7 @@ mod tiff_bmp_tga; pub mod tile_edge_color; mod tools; pub mod trace_presets; +pub mod tracing_presets; pub(crate) mod transform; pub mod transform_each; pub mod variables; @@ -381,6 +383,9 @@ registry! { FlattenTransparency: [flatten::KIND] => flatten::SPEC, FlattenerPresets: [flattener_presets::KIND] => flattener_presets::SPEC, ImageTracePreset: [trace_presets::KIND] => trace_presets::SPEC, + TracingPresets: [tracing_presets::KIND] => tracing_presets::SPEC, + TracingPreset: [tracing_presets::PRESET_KIND] => tracing_presets::PRESET_SPEC, + TracingPresetsReplace: [tracing_presets::REPLACE_KIND] => tracing_presets::REPLACE_SPEC, SaveStyleLibrary: [save_style_library::KIND] => save_style_library::SPEC, SaveSymbolLibrary: [save_symbol_library::KIND] => save_symbol_library::SPEC, SaveBrushLibrary: [save_brush_library::KIND] => save_brush_library::SPEC, @@ -472,6 +477,7 @@ registry! { FreehandOptions: [freehand::KIND] => freehand::SPEC, ShapeBuilderOptions: [shape_builder_options::KIND] => shape_builder_options::SPEC, ObjectsOnPathOptions: [objects_on_path_options::KIND] => objects_on_path_options::SPEC, + CircleOptions: [circle_options::KIND] => circle_options::SPEC, ThreePointArcOptions: [three_point_arc_options::KIND] => three_point_arc_options::SPEC, FlareOptions: [flare_options::KIND] => flare_options::SPEC, SymbolOptions: [symbol_options::KIND] => symbol_options::SPEC, @@ -629,6 +635,8 @@ pub fn accepts_field(d: &Dialog, field: &str) -> bool { /// Import PDF `allPages` set this way to the other pick sets Import PDF pages as links back to its /// default. A Dimension Tool Options `arrowStyle` set this way clears `arrowHead`, and a built-in /// `arrowHead` set this way sets both values of its Arrow Style entry, as that menu does. +/// A Pathfinder effect's precision set this way replaces a stored precision out of range, the +/// bound included. pub fn set_field(d: &mut Dialog, field: String, value: Value) { if d.kind == brush_options::KIND { brush_art_options::note_set(d, &field); @@ -651,6 +659,11 @@ pub fn set_field(d: &mut Dialog, field: String, value: Value) { if d.kind == new_document::KIND || new_document::popup_open(d) { new_document::note_set(d, &field); } + // A Pathfinder effect's precision set this way replaces a stored one out of range, as one + // entered in its field does. + if d.kind == "effect" && field == "precision" { + d.fields.remove(effect::OPENED_PRECISION); + } // Create Object Mosaic's Resize Using Percentages shows the new size the other way, as its checkbox does. if d.kind == object_mosaic::KIND && field == "percentages" { object_mosaic::set_percentages(d, &value); diff --git a/crates/ui-egui/src/dialogs/circle_options.rs b/crates/ui-egui/src/dialogs/circle_options.rs new file mode 100644 index 0000000000..6a828a7e17 --- /dev/null +++ b/crates/ui-egui/src/dialogs/circle_options.rs @@ -0,0 +1,169 @@ +//! Circle Tool Options (double-click the Circle tool, or `tool.options`): Show Center, Show Radii +//! and Show Diameter switch the center cross, the radius lines and the diameter label the tool +//! shows while a circle is drawn; Color is the color of the cross and the lines; Anchors at +//! Standard Positions off puts the circle's anchors at the points it was drawn through; Third +//! Point by Dragging off places the second point with a click and the third with another. OK sets +//! them with `tool.setOption {tool: "circle", values}`; they last across tool switches and are +//! saved with the preferences. + +use serde_json::{Map, Value, json}; +use vectorcraft_tools::circle::{COLORS, ID as TOOL}; + +use super::{DialogSpec, run_and_close}; +use crate::state::Dialog; +use crate::{VectorcraftApp, widgets}; + +/// The dialog kind of Circle Tool Options. +pub const KIND: &str = "circleOptions"; + +pub(super) const SPEC: DialogSpec = DialogSpec { heading, body, confirm, min_width: 300.0, ..DialogSpec::FORM }; + +/// The options the dialog edits, in the order it shows its check boxes, with their labels. +const SWITCHES: [(&str, &str); 5] = [ + ("center", "Show Center"), + ("radii", "Show Radii"), + ("diameter", "Show Diameter"), + ("standardAnchors", "Anchors at Standard Positions"), + ("dragThird", "Third Point by Dragging"), +]; + +/// The labels of [`COLORS`], in its order. +const COLOR_LABELS: [&str; 6] = ["Red", "Blue", "Magenta", "Green", "Black", "Gray"]; + +/// Width of the label column. +const LABEL_W: f32 = 60.0; + +fn heading(_: &Dialog) -> String { + let label = vectorcraft_tools::tool_info(TOOL).map_or("", |t| t.label); + crate::i18n::fmt(tl!("{tool} Options"), &[("tool", tl!(label))]) +} + +/// Open the tool's options with their current values. +pub fn open(app: &mut VectorcraftApp) -> Value { + let o = app.session.tool_options_of(TOOL); + let keys = SWITCHES.iter().map(|(key, _)| *key).chain(["color"]); + let fields: Map = keys.filter_map(|key| Some((key.to_string(), o.get(key)?.clone()))).collect(); + app.ui.dialog = Some(Dialog { kind: KIND.into(), fields }); + json!({ "dialog": KIND }) +} + +fn check(ui: &mut egui::Ui, d: &mut Dialog, key: &str, label: &str) { + let on = d.bool(key); + if widgets::check(ui, tl!(label), on, true) { + d.fields.insert(key.into(), json!(!on)); + } +} + +fn body(_app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { + for (key, label) in &SWITCHES[..3] { + check(ui, d, key, label); + } + let color = d.str("color"); + let at = COLORS.iter().position(|(name, _)| *name == color).unwrap_or(1); + widgets::label_row(ui, tl!("Color:"), LABEL_W, |ui| { + let shown = COLOR_LABELS.get(at).copied().unwrap_or("Blue"); + if let Some((name, _)) = + widgets::dropdown_named(ui, "circle-options-color", Some(tl!("Color:")), shown, &COLOR_LABELS, 110.0).and_then(|i| COLORS.get(i)) + { + d.fields.insert("color".into(), json!(name)); + } + }); + ui.add_space(8.0); + for (key, label) in &SWITCHES[3..] { + check(ui, d, key, label); + } + false +} + +/// OK: set the tool's options. +fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + let keys = SWITCHES.iter().map(|(key, _)| *key).chain(["color"]); + let values: Map = keys.filter_map(|key| Some((key.to_string(), d.fields.get(key)?.clone()))).collect(); + run_and_close(app, "tool.setOption", json!({ "tool": TOOL, "values": values })) +} + +#[cfg(test)] +mod tests { + use super::*; + use vectorcraft_engine::Session; + + fn app() -> VectorcraftApp { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + app + } + + /// The labels the open dialog paints. + fn painted(app: &mut VectorcraftApp) -> String { + crate::tests_labels::painted_text(app, |app, ui| super::super::show(app, ui.ctx())) + } + + /// Every label the dialog shows has a row for each of [`COLORS`]. + #[test] + fn every_color_has_a_label() { + assert_eq!(COLOR_LABELS.len(), COLORS.len()); + for (label, (name, _)) in COLOR_LABELS.iter().zip(COLORS) { + assert_eq!(label.to_lowercase(), *name); + } + } + + #[test] + fn double_clicking_the_tool_opens_its_options_and_ok_sets_them() { + let mut app = app(); + let o = app.session.tool_options_of(TOOL); + for key in ["center", "radii", "diameter", "standardAnchors", "dragThird"] { + assert_eq!(o[key], json!(true), "{key}"); + } + assert_eq!(o["color"], json!("blue")); + let r = app.run("tool.options", json!({"tool": TOOL})).unwrap(); + assert_eq!(r["dialog"], json!(KIND)); + let text = painted(&mut app); + for label in [ + "Circle Tool Options", + "Show Center", + "Show Radii", + "Show Diameter", + "Color:", + "Blue", + "Anchors at Standard Positions", + "Third Point by Dragging", + "OK", + "Cancel", + ] { + assert!(text.contains(label), "{label} in {text}"); + } + let d = app.ui.dialog.as_mut().unwrap(); + for key in ["radii", "standardAnchors", "dragThird"] { + assert!(d.bool(key), "{key}"); + d.fields.insert(key.into(), json!(false)); + } + d.fields.insert("color".into(), json!("magenta")); + super::super::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + let o = app.session.tool_options_of(TOOL); + let got: Vec<&Value> = ["center", "radii", "diameter", "standardAnchors", "dragThird", "color"].iter().map(|k| &o[*k]).collect(); + assert_eq!(got, [&json!(true), &json!(false), &json!(true), &json!(false), &json!(false), &json!("magenta")]); + // They last while another tool is chosen, and the dialog opens on them again. + app.select_tool(TOOL); + app.select_tool("selection"); + app.run("tool.options", json!({"tool": TOOL})).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + assert!(!d.bool("standardAnchors") && d.bool("center")); + assert_eq!(d.str("color"), "magenta"); + } + + /// `tool.setOption` takes only the values the options take, and an invalid one changes none. + #[test] + fn invalid_values_are_errors_and_change_nothing() { + let mut app = app(); + for (values, error) in [ + (json!({"center": false, "radii": "no"}), "`radii` must be true or false"), + (json!({"center": false, "color": "orange"}), "`color` must be one of red, blue, magenta, green, black, gray"), + (json!({"center": false, "size": 3}), "unknown Circle tool option `size`"), + ] { + let e = app.run("tool.setOption", json!({"tool": TOOL, "values": values})).unwrap_err(); + assert!(e.contains(error), "{e}"); + assert_eq!(app.session.tool_options_of(TOOL)["center"], json!(true)); + } + } +} diff --git a/crates/ui-egui/src/dialogs/effect.rs b/crates/ui-egui/src/dialogs/effect.rs index 987fceeea4..df5789e649 100644 --- a/crates/ui-egui/src/dialogs/effect.rs +++ b/crates/ui-egui/src/dialogs/effect.rs @@ -18,7 +18,16 @@ use crate::theme::Tokens; use crate::{VectorcraftApp, widgets}; pub(super) const SPEC: DialogSpec = DialogSpec { - heading: |d| if super::warp_effect::is_warp(&d.str("__effect")) { tl!("Warp Options").to_string() } else { heading_label(d) }, + heading: |d| { + let id = d.str("__effect"); + if super::warp_effect::is_warp(&id) { + tl!("Warp Options").to_string() + } else if has_only_pathfinder_options(&id) { + tl!("Pathfinder Options").to_string() + } else { + heading_label(d) + } + }, body, confirm, preview: true, @@ -125,6 +134,7 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { fields.insert("__editTarget".into(), edit_target); fields.insert("__index".into(), json!(k)); fields.extend(params_of(e)); + fill_pathfinder_options(app, id, &mut fields, false); } None => { if let Some(k) = applied.iter().rposition(|e| e.id == id) { @@ -135,6 +145,7 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result { return Ok(json!({ "pending": EXISTS })); } fields.extend(info.defaults.as_object().cloned().unwrap_or_default()); + fill_pathfinder_options(app, id, &mut fields, true); if super::warp_effect::is_warp(id) { super::warp_effect::merge_remembered(&mut fields, app.last_warp.as_ref()); } @@ -155,6 +166,55 @@ fn target_effects(app: &VectorcraftApp, p: &Value) -> (Value, Vec bool { + vectorcraft_effects::takes_pathfinder_options(id) + && vectorcraft_effects::default_params(id).is_some_and(|d| d.as_object().is_none_or(Map::is_empty)) +} + +/// A Pathfinder effect's Pathfinder Options in `fields`, where they are missing: for a new effect +/// (`fresh`) the Pathfinder panel's current options, as `effect.apply` takes them; for an applied +/// one saved without them, the values it evaluates with. A precision out of range (one that Scale +/// Strokes & Effects took past it) or not a number opens at the value it evaluates with, kept in +/// `__openedPrecision`: OK leaves that value out unless the user enters a precision, so the stored +/// one stays until the user changes it. +fn fill_pathfinder_options(app: &VectorcraftApp, id: &str, fields: &mut Map, fresh: bool) { + if !vectorcraft_effects::takes_pathfinder_options(id) { + return; + } + let options = + if fresh { super::pathfinder_options::options_in_force(app) } else { vectorcraft_effects::PathfinderEffectOptions::default().to_params() }; + for (key, v) in options.as_object().into_iter().flatten() { + fields.entry(key.clone()).or_insert_with(|| v.clone()); + } + if fields.get("precision").is_some_and(|v| !v.as_f64().is_some_and(|p| vectorcraft_effects::PATHFINDER_EFFECT_PRECISION.contains(&p))) { + let evaluated = vectorcraft_effects::PathfinderEffectOptions::from_params(&json!({"precision": fields["precision"]})).precision; + fields.insert("precision".into(), json!(evaluated)); + fields.insert(OPENED_PRECISION.into(), json!(evaluated)); + } +} + +/// The precision a Pathfinder effect's dialog opened at in place of a stored one out of range, +/// until the user enters a precision. +pub(super) const OPENED_PRECISION: &str = "__openedPrecision"; + +/// A Pathfinder effect's fields: Soft Mix's Mixing Rate as the other effects show their +/// parameters, then the Pathfinder Options. Returns whether the values changed. +fn pathfinder_fields(ui: &mut egui::Ui, d: &mut Dialog, id: &str, unit: vectorcraft_doc::Unit) -> bool { + let before = d.fields.clone(); + if !has_only_pathfinder_options(id) { + let options: Vec<(String, Value)> = + vectorcraft_effects::PATHFINDER_OPTION_KEYS.iter().filter_map(|k| d.fields.remove(*k).map(|v| (k.to_string(), v))).collect(); + let doc = vectorcraft_effects::effect_info(id).map(|e| e.params).unwrap_or_default(); + form::param_fields(ui, d, &|_| false, &|k| choices(id, k), &|k| doc_rank(doc, k), unit); + d.fields.extend(options); + ui.add_space(6.0); + } + super::pathfinder_options::fields(ui, d); + before != d.fields +} + /// An applied effect's values over its defaults. fn params_of(e: &vectorcraft_doc::Effect) -> Map { match vectorcraft_effects::merged_params(&e.id, &e.params) { @@ -174,6 +234,7 @@ fn confirm_exists(app: &mut VectorcraftApp, d: &Dialog) -> Result let id = d.str("__effect"); let defaults = vectorcraft_effects::default_params(&id); fields.extend(defaults.and_then(|v| v.as_object().cloned()).unwrap_or_default()); + fill_pathfinder_options(app, &id, &mut fields, true); if super::warp_effect::is_warp(id.as_str()) { super::warp_effect::merge_remembered(&mut fields, app.last_warp.as_ref()); } @@ -183,6 +244,7 @@ fn confirm_exists(app: &mut VectorcraftApp, d: &Dialog) -> Result let applied = app.session.appearance_effect_target(&edit_target).map(|(_, effects)| effects.to_vec()).unwrap_or_default(); let params = applied.get(k).map(params_of).unwrap_or_default(); fields.extend(params); + fill_pathfinder_options(app, &d.str("__effect"), &mut fields, false); fields.insert("__item".into(), target); } fields.insert("preview".into(), json!(true)); @@ -237,6 +299,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { super::raster_effects::effect_fields(app, ui, d); values_changed(d) } + None if vectorcraft_effects::takes_pathfinder_options(&id) => pathfinder_fields(ui, d, &id, app.session.general_unit()), None => { let doc = vectorcraft_effects::effect_info(&id).map(|e| e.params).unwrap_or_default(); let unit = app.session.general_unit(); @@ -1035,6 +1098,12 @@ fn command(d: &Dialog) -> (&'static str, Value) { p["index"] = index.clone(); p["item"] = item.unwrap_or(Value::Null); p["params"] = params; + // A precision the dialog opened at in place of a stored one out of range keeps the stored one. + if let (Some(opened), Some(Value::Object(m))) = (d.fields.get(OPENED_PRECISION).and_then(Value::as_f64), p.get_mut("params")) + && m.get("precision").and_then(Value::as_f64) == Some(opened) + { + m.remove("precision"); + } let id = d.str("__effect"); // Each target keeps the map its own Warp draws with: the dialog's `version` is the first // target's. @@ -1517,6 +1586,101 @@ mod tests { ); } + /// An applied Pathfinder effect opens Pathfinder Options with its own values (the defaults for + /// one saved without them); OK keeps a change as one undo step, and OK with nothing changed + /// records none. Soft Mix's dialog has Mixing Rate too, and a new one takes the panel's options. + #[test] + fn a_pathfinder_effect_opens_pathfinder_options_with_its_own_values() { + let mut app = VectorcraftApp::new(vectorcraft_engine::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("shape.rectangle", json!({"x": 40, "y": 40, "width": 50, "height": 50})).unwrap(); + app.run("select.all", json!({})).unwrap(); + app.run("effect.apply", json!({"effect": "pathfinder.add", "params": {"precision": 0.5}})).unwrap(); + let g = app.session.doc().unwrap().selection.objects[0]; + let steps = |app: &VectorcraftApp| app.session.doc().unwrap().history.undo.len(); + let paint = |app: &mut VectorcraftApp| crate::tests_labels::painted_text(app, |app, ui| super::super::show(app, ui.ctx())); + app.run("effect.dialog", json!({"effect": "pathfinder.add", "index": 0, "item": null})).unwrap(); + let text = paint(&mut app); + for s in ["Pathfinder Options", "Precision:", "Remove Redundant Points", "Divide and Outline Will Remove Unpainted Artwork"] { + assert!(text.lines().any(|l| l == s), "{s} in {text}"); + } + assert_eq!(app.ui.dialog.as_ref().unwrap().fields["precision"], json!(0.5)); + let before = steps(&app); + super::super::confirm(&mut app).unwrap(); + assert_eq!(steps(&app), before, "OK with nothing changed records no step"); + app.run("effect.dialog", json!({"effect": "pathfinder.add", "index": 0, "item": null})).unwrap(); + paint(&mut app); + app.ui.dialog.as_mut().unwrap().fields.insert("removeRedundantPoints".into(), json!(true)); + paint(&mut app); + super::super::confirm(&mut app).unwrap(); + assert_eq!(steps(&app), before + 1, "one step"); + let params = |app: &VectorcraftApp| app.session.doc().unwrap().doc.node(g).unwrap().appearance.effects[0].params.clone(); + assert_eq!(params(&app)["removeRedundantPoints"], json!(true)); + // Saved without options, it opens with the values it evaluates with. + app.session + .edit("t", |d, _| { + d.node_mut(g).unwrap().appearance.effects[0].params = json!({}); + Ok(()) + }) + .unwrap(); + app.run("effect.dialog", json!({"effect": "pathfinder.add", "index": 0, "item": null})).unwrap(); + let fields = &app.ui.dialog.as_ref().unwrap().fields; + assert_eq!( + (&fields["precision"], &fields["removeRedundantPoints"], &fields["removeUnpainted"]), + (&json!(0.01), &json!(false), &json!(false)) + ); + app.ui.dialog = None; + let _ = app.session.cancel_interaction(); + // A new Soft Mix takes the panel's options and shows Mixing Rate beside them. + app.run("object.pathfinder.options", json!({"removeUnpainted": true})).unwrap(); + app.run("effect.dialog", json!({"effect": "pathfinder.softMix"})).unwrap(); + let text = paint(&mut app); + assert!(text.contains("Mixing Rate") && text.lines().any(|l| l == "Remove Redundant Points"), "{text}"); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields["removeUnpainted"], json!(true)); + } + + /// A Pathfinder effect whose precision Scale Strokes & Effects took past the range opens at the + /// bound it evaluates at. OK with nothing changed records no step, OK with another option + /// changed keeps the stored precision, and a precision the user sets replaces it. + #[test] + fn a_pathfinder_precision_scaled_past_its_range_opens_at_the_bound_and_ok_keeps_it() { + let mut app = VectorcraftApp::new(vectorcraft_engine::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("shape.rectangle", json!({"x": 40, "y": 40, "width": 50, "height": 50})).unwrap(); + app.run("select.all", json!({})).unwrap(); + app.run("effect.apply", json!({"effect": "pathfinder.add", "params": {"precision": 8}})).unwrap(); + let g = app.session.doc().unwrap().selection.objects[0]; + app.run("object.scale", json!({"sx": 200, "strokes": true})).unwrap(); + let params = |app: &VectorcraftApp| app.session.doc().unwrap().doc.node(g).unwrap().appearance.effects[0].params.clone(); + assert_eq!(params(&app)["precision"].as_f64(), Some(16.0)); + let steps = |app: &VectorcraftApp| app.session.doc().unwrap().history.undo.len(); + let open = |app: &mut VectorcraftApp| { + app.run("effect.dialog", json!({"effect": "pathfinder.add", "index": 0, "item": null})).unwrap(); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields["precision"].as_f64(), Some(10.0)); + }; + open(&mut app); + let before = steps(&app); + super::super::confirm(&mut app).unwrap(); + assert_eq!((steps(&app), params(&app)["precision"].as_f64()), (before, Some(16.0)), "OK with nothing changed"); + open(&mut app); + app.ui.dialog.as_mut().unwrap().fields.insert("removeRedundantPoints".into(), json!(true)); + super::super::confirm(&mut app).unwrap(); + assert_eq!((params(&app)["precision"].as_f64(), ¶ms(&app)["removeRedundantPoints"]), (Some(16.0), &json!(true))); + open(&mut app); + app.ui.dialog.as_mut().unwrap().fields.insert("precision".into(), json!(2.5)); + super::super::confirm(&mut app).unwrap(); + assert_eq!(params(&app)["precision"].as_f64(), Some(2.5)); + // Setting the bound itself (`ui.dialog.set`, or the Precision field) replaces a stored value past it. + app.run("object.scale", json!({"sx": 800, "strokes": true})).unwrap(); + assert_eq!(params(&app)["precision"].as_f64(), Some(20.0)); + open(&mut app); + super::super::set_field(app.ui.dialog.as_mut().unwrap(), "precision".into(), json!(10.0)); + super::super::confirm(&mut app).unwrap(); + assert_eq!(params(&app)["precision"].as_f64(), Some(10.0)); + } + /// A Radial Blur whose saved Blur Center lies outside the object's bounds (a document written /// by hand or by another build) opens with the center at the nearest edge, and OK stores that /// edge instead of sending the saved value, which `effect.setParams` refuses. diff --git a/crates/ui-egui/src/dialogs/graph_design.rs b/crates/ui-egui/src/dialogs/graph_design.rs index 75659920e5..8c0c536542 100644 --- a/crates/ui-egui/src/dialogs/graph_design.rs +++ b/crates/ui-egui/src/dialogs/graph_design.rs @@ -9,8 +9,12 @@ //! For Fractions; OK runs `graph.column`. //! Marker: the design the selected graph series draw their data points with, or None (the default //! square marker); OK runs `graph.marker`. +//! Column and Marker also list, under each library's name, the graph designs of the documents +//! Window › Swatch Libraries › Other Library… loaded that the document lacks; OK on one copies it +//! into the document with the resources its art uses. //! //! Fields: `selected` (the selected designs' names; Column and Marker: one name, null for None), +//! in Column and Marker `library` (the library of the selected design, null for the document's), //! in Graph Design `name` (the name Rename gives), and in Column `columnType`, `each` and //! `fractions`. @@ -46,6 +50,7 @@ pub(super) const COLUMN_SPEC: DialogSpec = DialogSpec { confirm: |app, d| { let p = json!({ "design": d.fields.get("selected").and_then(Value::as_str), + "library": library_of(d), "columnType": d.str("columnType"), "each": d.f64("each", vectorcraft_doc::ColumnDesign::EACH), "fractions": d.str("fractions"), @@ -59,7 +64,9 @@ pub(super) const COLUMN_SPEC: DialogSpec = DialogSpec { pub(super) const MARKER_SPEC: DialogSpec = DialogSpec { heading: |_| tl!("Graph Marker").into(), body: marker_body, - confirm: |app, d| run_and_close(app, "graph.marker", json!({ "design": d.fields.get("selected").and_then(Value::as_str) })), + confirm: |app, d| { + run_and_close(app, "graph.marker", json!({ "design": d.fields.get("selected").and_then(Value::as_str), "library": library_of(d) })) + }, min_width: 300.0, ..DialogSpec::FORM }; @@ -95,6 +102,24 @@ fn names(app: &VectorcraftApp) -> Result, String> { Ok(st.doc.graph_designs.iter().map(|d| d.name.clone()).collect()) } +/// The designs of the loaded libraries that the document lacks (the document's own design of a name +/// is the one used), by library: its id, its name and the design names, libraries with none left +/// out. +fn library_designs(app: &VectorcraftApp) -> Vec<(String, String, Vec)> { + let own = names(app).unwrap_or_default(); + app.session + .graph_design_libraries + .iter() + .map(|l| (l.id.clone(), l.name.clone(), l.doc.graph_designs.iter().map(|g| g.name.clone()).filter(|n| !own.contains(n)).collect::>())) + .filter(|(.., names)| !names.is_empty()) + .collect() +} + +/// Column and Marker's `library`: the library of the selected design, `None` for the document's. +fn library_of(d: &Dialog) -> Option<&str> { + d.fields.get("library").and_then(Value::as_str) +} + /// Graph Design's selected designs. fn selected(d: &Dialog) -> Vec { d.fields.get("selected").and_then(Value::as_array).map(|a| a.iter().filter_map(|v| v.as_str().map(str::to_string)).collect()).unwrap_or_default() @@ -105,8 +130,9 @@ fn select(d: &mut Dialog, names: Vec) { d.fields.insert("selected".into(), json!(names)); } -/// A design's art drawn in `r` (cached by the art's identity). -fn preview(ui: &egui::Ui, app: &VectorcraftApp, name: &str, r: egui::Rect) { +/// A design's art drawn in `r` (cached by the art's identity): the document's design `name`, or +/// with `library` that loaded library's. +fn preview(ui: &egui::Ui, app: &VectorcraftApp, library: Option<&str>, name: &str, r: egui::Rect) { use std::cell::RefCell; use std::collections::HashMap; thread_local! { @@ -114,11 +140,18 @@ fn preview(ui: &egui::Ui, app: &VectorcraftApp, name: &str, r: egui::Rect) { static CACHE: crate::graphics::TexCache> = crate::graphics::TexCache::default(); } let Some(st) = app.session.active() else { return }; - let Some(art) = st.doc.graph_designs.iter().find(|x| x.name == name).map(|x| x.art.clone()) else { return }; + let doc = match library { + Some(id) => match app.session.graph_design_libraries.get(id) { + Some(l) => &l.doc, + None => return, + }, + None => &st.doc, + }; + let Some(art) = doc.graph_designs.iter().find(|x| x.name == name).map(|x| x.art.clone()) else { return }; let key = std::sync::Arc::as_ptr(&art) as usize; let px = (r.width() * ui.ctx().pixels_per_point()).round() as u32; let tex = CACHE.with(|c| c.borrow().get(&key).cloned()).or_else(|| { - let img = RENDERER.with(|rr| rr.borrow_mut().render_node_thumbnail(&st.doc, &art, px.max(16), Some([255, 255, 255, 255])))?; + let img = RENDERER.with(|rr| rr.borrow_mut().render_node_thumbnail(doc, &art, px.max(16), Some([255, 255, 255, 255])))?; let color = crate::canvas::color_image(&img); let tex = ui.ctx().load_texture(format!("graph-design-{key}"), color, egui::TextureOptions::LINEAR); CACHE.with(|c| { @@ -177,7 +210,7 @@ fn design_body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> b let (r, _) = ui.allocate_exact_size(egui::vec2(PREVIEW, PREVIEW), egui::Sense::hover()); ui.painter().rect_stroke(r, 0.0, egui::Stroke::new(1.0, egui::Color32::from_gray(160)), egui::StrokeKind::Inside); if let Some(n) = &one { - preview(ui, app, n, r.shrink(4.0)); + preview(ui, app, None, n, r.shrink(4.0)); } ui.add_space(6.0); let button = @@ -220,37 +253,66 @@ fn design_body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> b false } -/// The list of Column and Marker: None, then the designs `names`; a click picks one into `selected` (null for None). -fn one_design_list(ui: &mut egui::Ui, d: &mut Dialog, names: &[String], salt: &str) { +/// The list of Column and Marker: None, the document's designs `names`, then each loaded library's +/// name and the designs of it in `libraries` ([`library_designs`]); a click picks one into +/// `selected` (null for None) and its library into `library` (null for the document's). +fn one_design_list(ui: &mut egui::Ui, d: &mut Dialog, names: &[String], libraries: &[(String, String, Vec)], salt: &str) { widgets::list_box(ui, |ui| { egui::ScrollArea::vertical().id_salt(salt).min_scrolled_height(160.0).max_height(160.0).show(ui, |ui| { ui.set_width(ui.available_width()); ui.set_min_height(160.0); let current = d.fields.get("selected").and_then(Value::as_str).map(str::to_string); + let from = library_of(d).map(str::to_string); + let pick = |d: &mut Dialog, name: Option<&str>, library: Option<&str>| { + d.fields.insert("selected".into(), json!(name)); + d.fields.insert("library".into(), json!(library)); + }; if ui.selectable_label(current.is_none(), tl!("None")).clicked() { - d.fields.insert("selected".into(), Value::Null); + pick(d, None, None); } for n in names { - if ui.selectable_label(current.as_deref() == Some(n.as_str()), n.as_str()).clicked() { - d.fields.insert("selected".into(), json!(n)); + if ui.selectable_label(from.is_none() && current.as_deref() == Some(n.as_str()), n.as_str()).clicked() { + pick(d, Some(n), None); + } + } + for (id, library, designs) in libraries { + ui.add_space(4.0); + // The library's own name, not interface text. + widgets::dim_name(ui, library); + for n in designs { + let on = from.as_deref() == Some(id.as_str()) && current.as_deref() == Some(n.as_str()); + if ui.selectable_label(on, n.as_str()).clicked() { + pick(d, Some(n), Some(id)); + } } } }); }); } +/// The design Column or Marker has selected, with its library (`None`: the document's), when the +/// document or that library still has it. +fn shown_design(d: &Dialog, names: &[String], libraries: &[(String, String, Vec)]) -> Option<(Option, String)> { + let n = d.fields.get("selected").and_then(Value::as_str)?; + match library_of(d) { + None => names.iter().any(|x| x == n).then(|| (None, n.to_string())), + Some(id) => libraries.iter().any(|(l, _, designs)| l == id && designs.iter().any(|x| x == n)).then(|| (Some(id.to_string()), n.to_string())), + } +} + fn column_body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { let names = names(app).unwrap_or_default(); + let libraries = library_designs(app); ui.horizontal_top(|ui| { ui.vertical(|ui| { ui.set_width(220.0); - one_design_list(ui, d, &names, "graph-columns"); + one_design_list(ui, d, &names, &libraries, "graph-columns"); }); ui.add_space(10.0); let (r, _) = ui.allocate_exact_size(egui::vec2(PREVIEW, PREVIEW), egui::Sense::hover()); ui.painter().rect_stroke(r, 0.0, egui::Stroke::new(1.0, egui::Color32::from_gray(160)), egui::StrokeKind::Inside); - if let Some(n) = d.fields.get("selected").and_then(Value::as_str).filter(|n| names.iter().any(|x| x == n)) { - preview(ui, app, n, r.shrink(4.0)); + if let Some((library, n)) = shown_design(d, &names, &libraries) { + preview(ui, app, library.as_deref(), &n, r.shrink(4.0)); } }); ui.add_space(8.0); @@ -277,9 +339,10 @@ const EACH_RANGE: std::ops::RangeInclusive = 0.0001..=1_000_000_000.0; fn marker_body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { let names = names(app).unwrap_or_default(); + let libraries = library_designs(app); // A list as wide as Graph Design's, not the whole window. ui.set_width(220.0); - one_design_list(ui, d, &names, "graph-markers"); + one_design_list(ui, d, &names, &libraries, "graph-markers"); false } @@ -377,4 +440,33 @@ mod tests { (super::COLUMN_SPEC.confirm)(&mut app, &d).unwrap(); assert_eq!(app.session.execute("graph.column", &json!({})).unwrap()["design"], json!(null)); } + + #[test] + fn marker_lists_a_loaded_documents_designs_and_ok_copies_the_one_picked_in() { + // A document with design "New Design", loaded as a swatch library (Other Library…). + let src = app_with_design(); + let bytes = vectorcraft_format::save_file(&src.session.active().unwrap().doc); + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + let p = json!({"dataBase64": vectorcraft_format::base64_encode(&bytes), "name": "Dots.vectorcraft"}); + app.run("swatch.library.load", p).unwrap(); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let g = app.run("graph.create", json!({"type": "line", "x": 100, "y": 100, "width": 200, "height": 100})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [g]})).unwrap(); + let libraries = super::library_designs(&app); + assert_eq!(libraries.len(), 1); + let (id, _, designs) = &libraries[0]; + assert_eq!(designs, &["New Design".to_string()]); + crate::menus::invoke(&mut app, "graph.marker", json!({})); + frame(&mut app); + let mut d: Dialog = app.ui.dialog.take().unwrap(); + d.fields.insert("selected".into(), json!("New Design")); + d.fields.insert("library".into(), json!(id)); + app.ui.dialog = Some(d.clone()); + frame(&mut app); + (super::MARKER_SPEC.confirm)(&mut app, &d).unwrap(); + assert_eq!(app.session.execute("graph.marker", &json!({})).unwrap()["design"], "New Design"); + assert_eq!(super::names(&app).unwrap(), ["New Design"]); + // The document has it now, so the library lists it no more. + assert!(super::library_designs(&app).is_empty()); + } } diff --git a/crates/ui-egui/src/dialogs/hpgl_options.rs b/crates/ui-egui/src/dialogs/hpgl_options.rs index 5bbc6b3e6b..cf2e578855 100644 --- a/crates/ui-egui/src/dialogs/hpgl_options.rs +++ b/crates/ui-egui/src/dialogs/hpgl_options.rs @@ -8,7 +8,8 @@ //! an option or artboard choice the export refuses, or a save panel shown in line that is canceled, //! keeps the dialog open. A canceled save panel keeps the options remembered before. Opened by Export //! Selection, it checks and writes the selection alone. A typed Curve Tolerance is kept within 0.01 -//! to 10 points. +//! to 10 points. OK after another document has become the active one closes the dialog and writes +//! nothing. use serde_json::{Map, Value, json}; use vectorcraft_cad::hpgl::write::{DEFAULT_TOLERANCE, MAX_PENS, TOLERANCE_RANGE}; @@ -42,6 +43,9 @@ const SET_ASIDE: &str = "__pens"; /// Why Pen Table could not start from the art's pens, shown under the Pens row. const PEN_ERROR: &str = "__penError"; +/// The field that holds the uid of the document the dialog was opened for. +const DOC: &str = "__doc"; + /// The Origin menu's names, in [`Origin::ALL`] order. pub(crate) const ORIGIN_NAMES: [&str; 2] = ["Bottom Left", "Center"]; @@ -71,6 +75,7 @@ pub fn open(app: &mut VectorcraftApp, params: &Value) { } } fields.insert("format".into(), json!("hpgl")); + fields.insert(DOC.into(), json!(app.session.active().map(|st| st.uid))); app.ui.dialog = Some(Dialog::new(KIND, Value::Object(fields))); } @@ -236,8 +241,13 @@ fn rgb(hex: &str) -> Option<[u8; 3]> { Some([byte(0)?, byte(2)?, byte(4)?]) } -/// Check the options, remember them, and write the file(s). +/// Check the options, remember them, and write the file(s). When another document has become the +/// active one since the dialog opened, it closes as Cancel does and writes nothing. fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + if d.fields.get(DOC).and_then(Value::as_u64) != app.session.active().map(|st| st.uid) { + app.ui.dialog = None; + return Ok(json!({})); + } let params = super::form::params(d); let st = app.session.active().ok_or("no document")?; // A bad option or artboard choice, nothing selected, or no art to export keeps the dialog open. diff --git a/crates/ui-egui/src/dialogs/import_pdf.rs b/crates/ui-egui/src/dialogs/import_pdf.rs index 5be31baebd..b14cba49cd 100644 --- a/crates/ui-egui/src/dialogs/import_pdf.rs +++ b/crates/ui-egui/src/dialogs/import_pdf.rs @@ -6,7 +6,11 @@ //! a file read from a path and opened without a password; `null` until it is checked or cleared, //! when it follows the pages picked: on for All, off for a range; picking the other of All and //! Range sets it back to `null`; `__linkable` is false for a file `linkPages` does not take, such as -//! one over its size limit), `cropTo` and `password`. `__locked` is set +//! one over its size limit), `cropTo`, `textAs` (`text` | `outlines`; it starts from the `pdfTextAs` +//! preference for a PDF (`__pdf`; Editable for a `.ai` or `.ait` file), or from the `textAs` a place +//! gives (`__textAsGiven`), and OK keeps a PDF's choice there; a +//! linked place shows the file's own text, so placing linked leaves it as it is, and Outlines clears +//! Import PDF Pages as Links) and `password`. `__locked` is set //! until the password is accepted: OK then unlocks the file, and with `__passwordOnly` (Place with //! Show Import Options off) places its first page at once. `__place` keeps the other `file.place` //! params (Link, Template, `at`…). The file's bytes stay out of the fields, in @@ -17,7 +21,7 @@ use std::sync::atomic::{AtomicU64, Ordering}; use serde_json::{Value, json}; use vectorcraft_engine::cmd::fileio; -use vectorcraft_pdf::{Choice, CropTo, PdfError}; +use vectorcraft_pdf::{Choice, CropTo, PdfError, TextAs}; use super::DialogSpec; use crate::state::Dialog; @@ -149,6 +153,10 @@ pub fn offer(app: &mut VectorcraftApp, name: &str, bytes: &[u8], path: Option Option { Some(d.str("password")).filter(|p| !p.is_empty()) } -/// Can the pages open linked: the file was read from a path (a linked page is read from its +/// The labels of the Text choices, in the order of [`TextAs::ALL`]. +const TEXT_AS_LABELS: [&str; 2] = ["Editable", "Outlines"]; + +/// The `textAs` choice `id` (any case); anything else is editable text. +fn text_as_of(id: &str) -> TextAs { + TextAs::ALL.iter().zip(TextAs::IDS).find(|(_, i)| i.eq_ignore_ascii_case(id)).map(|(t, _)| *t).unwrap_or_default() +} + +/// What a PDF's text becomes when an open or place from the app does not say: the `pdfTextAs` +/// preference. +pub(crate) fn preferred_text_as(app: &VectorcraftApp) -> TextAs { + text_as_of(&app.session.prefs.pdf_text_as) +} + +/// The `document.open` options `p` for the file `name` holding `bytes`, with the `pdfTextAs` +/// preference as its `textAs` when it is a PDF opened as Outlines and `p` has no `textAs`. A `.ai` +/// or `.ait` file opens as it says: Outlines would open it from its PDF content, without its +/// editing data. So does an open with `linkPages`, which refuses Outlines: a linked page shows the +/// file's own text. +pub(crate) fn with_preferred_text_as(app: &VectorcraftApp, name: &str, bytes: &[u8], p: &Value) -> Value { + let given = p.get("textAs").is_some_and(|v| !v.is_null()); + let linked = p.get("linkPages").and_then(Value::as_bool) == Some(true); + let options = p.is_object() || p.is_null(); + if given || linked || !options || preferred_text_as(app) == TextAs::Text || fileio::detect(name, bytes).map(|f| f.id) != Some("pdf") { + return p.clone(); + } + let mut p = if p.is_object() { p.clone() } else { json!({}) }; + p["textAs"] = json!(TextAs::Outlines.id()); + p +} + +/// The `file.place` params `p` of a PDF the user places embedded (Link off, from bytes or with a +/// password) get the `pdfTextAs` preference as their `textAs` when it is Outlines and they have no +/// `textAs`. A linked page shows the file's own text, and a `.ai` or `.ait` file is placed as it +/// says. +pub(crate) fn place_with_preferred_text_as(app: &VectorcraftApp, p: &mut Value) { + let given = |k: &str| p.get(k).is_some_and(|v| !v.is_null()); + let path = p.get("path").and_then(Value::as_str); + let name = path.or_else(|| p.get("name").and_then(Value::as_str)).unwrap_or_default(); + let linked = path.is_some() && p.get("link").and_then(Value::as_bool) != Some(false) && !given("password"); + if given("textAs") || linked || preferred_text_as(app) == TextAs::Text || fileio::extension(name) != "pdf" { + return; + } + if let Some(o) = p.as_object_mut() { + o.insert("textAs".into(), json!(TextAs::Outlines.id())); + } +} + +fn text_as(d: &Dialog) -> TextAs { + text_as_of(&d.str("textAs")) +} + +/// A place that links the page: from a path, with Link on, without a password (`file.place` +/// embeds a page read with a password) and without a `textAs` given with the place (`__textAsGiven`: +/// the Text choice then decides, and Outlines embeds the page). A linked page shows the file's own +/// text, so the Text choice does not apply to it. +fn places_linked(d: &Dialog) -> bool { + d.str("mode") == "place" + && d.fields.get("path").and_then(Value::as_str).is_some() + && d.fields.get("__place").and_then(|p| p.get("link")).and_then(Value::as_bool) != Some(false) + && password(d).is_none() + && !d.bool("__textAsGiven") +} + +/// Can the file's pages open linked: it was read from a path (a linked page is read from its /// file again), `document.open`'s `linkPages` takes its size, and it opens without a password /// (`linkPages` refuses one). -fn can_link(d: &Dialog) -> bool { +fn file_can_link(d: &Dialog) -> bool { d.fields.get("path").and_then(Value::as_str).is_some() && d.bool("__linkable") && password(d).is_none() } +/// Can the pages open linked: [`file_can_link`], with the text kept editable (`linkPages` +/// refuses `textAs: outlines`). +fn can_link(d: &Dialog) -> bool { + file_can_link(d) && text_as(d) == TextAs::Text +} + +/// Keeps the Text choice OK confirmed in the `pdfTextAs` preference. +fn keep_text_as(app: &mut VectorcraftApp, text_as: TextAs) { + if preferred_text_as(app) != text_as { + // The open or place has already happened; a preference that can't be written only means + // the next dialog starts from the old choice. + let _ = app.run("prefs.set", json!({"key": "pdfTextAs", "value": text_as.id()})); + } +} + /// Import PDF Pages as Links as checked or cleared, or, when it is `null`, as the pages picked /// default it: on for All, off for a range. fn link_pages(d: &Dialog) -> bool { @@ -283,9 +378,13 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { if let Some(pw) = password(&d) { p["password"] = json!(pw); } + // A `textAs` left with the other params is one `file.place` refuses; null leaves it out. + if !places_linked(&d) && p.get("textAs").is_none_or(Value::is_null) { + p["textAs"] = json!(text_as(&d).id()); + } crate::place::run_for_user(app, &p).map(|_| ()) } else { - let mut p = json!({"cropTo": crop(&d).id(), "password": password(&d)}); + let mut p = json!({"cropTo": crop(&d).id(), "password": password(&d), "textAs": text_as(&d).id()}); let range = d.str("range"); if !d.bool("allPages") && !range.trim().is_empty() { p["pages"] = json!(range); @@ -297,6 +396,11 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { }; match r { Ok(()) => { + // Asked only for the password, the dialog showed no Text choice to keep; the choice + // for a `.ai` or `.ait` file is not kept for PDFs. + if !places_linked(&d) && !d.bool("__passwordOnly") && d.bool("__pdf") { + keep_text_as(app, text_as(&d)); + } // Opening may have asked something else (the profile of the document); only this // dialog closes. if app.ui.dialog.as_ref().is_some_and(|x| x.kind == KIND) { @@ -359,6 +463,18 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { d.fields.insert("cropTo".into(), json!(id)); } }); + ui.add_space(4.0); + let linked = places_linked(d); + widgets::label_row(ui, tl!("Text"), LABEL_WIDTH, |ui| { + let current = TextAs::ALL.iter().position(|t| *t == text_as(d)).and_then(|i| TEXT_AS_LABELS.get(i)).copied().unwrap_or_default(); + let picked = ui.add_enabled_ui(!linked, |ui| widgets::dropdown(ui, "pdf-text-as", current, &TEXT_AS_LABELS, 130.0)).inner; + if let Some(t) = picked.and_then(|i| TextAs::ALL.get(i)) { + d.fields.insert("textAs".into(), json!(t.id())); + } + }); + if linked { + widgets::dim_label(ui, tl!("Linked pages show the file's own text.")); + } if d.str("mode") != "place" { ui.add_space(10.0); ui.label(egui::RichText::new(tl!("Pages")).color(t.text)); @@ -379,6 +495,10 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { if widgets::check(ui, tl!("Import PDF pages as links"), links_on(d), can_link(d)) { d.fields.insert("linkPages".into(), json!(!link_pages(d))); } + // Outlines alone dims the box. + if text_as(d) == TextAs::Outlines && file_can_link(d) { + widgets::dim_label(ui, tl!("Linked pages show the file's own text.")); + } } }); }); @@ -399,12 +519,14 @@ fn password_row(ui: &mut egui::Ui, d: &mut Dialog) { }); } -/// Page `page` (1-based) cropped as the dialog says, rendered once per file, page and box. +/// Page `page` (1-based) cropped and with its text as the dialog says (a linked place: as +/// editable text, as before the choice), rendered once per file, page, box and text choice. fn preview(app: &mut VectorcraftApp, ctx: &egui::Context, d: &Dialog, page: usize) -> Option { let file = app.ui.dialog_file.clone()?; let crop = crop(d); - let key = egui::Id::unique(("pdf-preview", file.token, page, crop.id())); - let opts = fileio::LoadOptions { crop, password: password(d), ..Default::default() }; + let text_as = if places_linked(d) { TextAs::Text } else { text_as(d) }; + let key = egui::Id::unique(("pdf-preview", file.token, page, crop.id(), text_as.id())); + let opts = fileio::LoadOptions { crop, password: password(d), text_as, ..Default::default() }; // A page that can't be read shows an empty preview (and isn't read again). preview_texture(app, ctx, key, &format!("pdf-preview-{page}"), PREVIEW, || { fileio::page_document(&file.bytes, page - 1, &opts).ok().map(|(doc, _)| doc) diff --git a/crates/ui-egui/src/dialogs/pathfinder_options.rs b/crates/ui-egui/src/dialogs/pathfinder_options.rs index 5520d79695..fc32c31eee 100644 --- a/crates/ui-egui/src/dialogs/pathfinder_options.rs +++ b/crates/ui-egui/src/dialogs/pathfinder_options.rs @@ -21,6 +21,31 @@ pub fn open(app: &mut VectorcraftApp) { app.ui.dialog = Some(Dialog::new(KIND, json!(app.session.prefs.pathfinder))); } +/// The Pathfinder Options that `effect.apply` gives a new Pathfinder effect, as its params. +pub fn options_in_force(app: &VectorcraftApp) -> Value { + vectorcraft_engine::cmd::pathfinder_effect_options(&app.session).to_params() +} + +/// The params that an Effect › Pathfinder menu item with params `p` (`effect.apply`) runs with: its +/// `params` with the Pathfinder Options in force ([`options_in_force`]) added where they are +/// missing, as `effect.apply` journals them. Insert Menu Item stores the same params as the item's +/// step. Params of any other effect are returned unchanged. +pub fn menu_effect_params(app: &VectorcraftApp, mut p: Value) -> Value { + if !p.get("effect").and_then(Value::as_str).is_some_and(vectorcraft_effects::takes_pathfinder_options) { + return p; + } + let options = options_in_force(app); + if let Some(o) = p.as_object_mut() { + let params = o.entry("params").or_insert_with(|| json!({})); + if let (Some(params), Some(options)) = (params.as_object_mut(), options.as_object()) { + for (key, v) in options { + params.entry(key.clone()).or_insert_with(|| v.clone()); + } + } + } + p +} + fn check(ui: &mut egui::Ui, d: &mut Dialog, key: &str, text: &str) { let v = d.bool(key); if widgets::check(ui, text, v, true) { @@ -29,19 +54,28 @@ fn check(ui: &mut egui::Ui, d: &mut Dialog, key: &str, text: &str) { } fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { + fields(ui, d); + false +} + +/// Precision, Remove Redundant Points and Divide and Outline Will Remove Unpainted Artwork, editing +/// `precision`, `removeRedundantPoints` and `removeUnpainted` in `d` (this dialog's, and a +/// Pathfinder effect's in the effect dialog). +pub(super) fn fields(ui: &mut egui::Ui, d: &mut Dialog) { let range = vectorcraft_engine::cmd::PATHFINDER_PRECISION_RANGE; grid(ui, |ui| { label(ui, tl!("Precision:")); let v = d.f64("precision", vectorcraft_engine::PathfinderOptions::default().precision); if let Some(v) = widgets::range_field(ui, "pathfinder-precision", v, range, " pt", 3, 80.0) { d.fields.insert("precision".into(), json!(v)); + // An entered precision replaces a stored one out of range, the bound included. + d.fields.remove(super::effect::OPENED_PRECISION); } ui.end_row(); }); ui.add_space(8.0); check(ui, d, "removeRedundantPoints", tl!("Remove Redundant Points")); check(ui, d, "removeUnpainted", tl!("Divide and Outline Will Remove Unpainted Artwork")); - false } fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { diff --git a/crates/ui-egui/src/dialogs/revolve.rs b/crates/ui-egui/src/dialogs/revolve.rs index 1812f41d42..568acdb121 100644 --- a/crates/ui-egui/src/dialogs/revolve.rs +++ b/crates/ui-egui/src/dialogs/revolve.rs @@ -6,7 +6,7 @@ use egui::{Align2, FontId, Id, Pos2, Sense, Stroke, vec2}; use serde_json::{Value, json}; use vectorcraft_doc::Unit; -use vectorcraft_effects::{CLASSIC_EXTRUDE, CLASSIC_REVOLVE, EXTRUDE, INFLATE, REVOLVE, ROTATION_PRESETS}; +use vectorcraft_effects::{BEVEL_NAME, BEVEL_PROFILE, CLASSIC_EXTRUDE, CLASSIC_REVOLVE, EXTRUDE, INFLATE, REVOLVE, ROTATION_PRESETS}; use crate::state::Dialog; use crate::theme::Tokens; @@ -233,11 +233,11 @@ fn solid_controls(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, id: & } else if object && d.str("__tab") != "rotation" { let unit = app.session.general_unit(); if id == CLASSIC_EXTRUDE { - super::three_d_classic::object_controls(ui, d, unit); + super::three_d_classic::object_controls(app, ui, d, unit); } else if id == CLASSIC_REVOLVE { super::three_d_classic::revolve_controls(ui, d, unit); } else if id == EXTRUDE { - extrude_controls(ui, d, unit); + extrude_controls(app, ui, d, unit); } else { heading(ui, tl!("Object")); number(ui, d, "depth", tl!("Depth"), (0.0, 2000.0), "", 1, Some(unit)); @@ -252,8 +252,108 @@ fn solid_controls(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, id: & } } +/// A Bevel Shape menu entry: (shown label, value, the custom bevel's name and points). +pub(crate) type BevelChoice = (String, Value, Option<(String, Value)>); + +/// The entries of [`bevel_choice`]'s menu for form `fields`, and how many are built in. The +/// built-in labels are translated; custom bevels show their names as they are. The effect's own +/// custom bevel, the panel's [`OWN_BEVEL`] else the form's, is listed unless the file lists it by +/// name with the same points; while another entry has its label, " (document)" is added to it. +pub(crate) fn bevel_options(app: &VectorcraftApp, fields: &serde_json::Map, effect: &str) -> (Vec, usize) { + let mut options: Vec = super::effect::own_choices(effect, "bevel", false) + .unwrap_or_default() + .into_iter() + .map(|(label, value)| (tl!(label).to_string(), json!(value), None)) + .collect(); + let builtin = options.len(); + for b in app.session.bevels.bevels() { + options.push((b.name.clone(), json!("custom"), Some((b.name.clone(), b.profile_json())))); + } + let custom = fields.get("bevel").and_then(Value::as_str) == Some("custom"); + let own = match fields.get(OWN_BEVEL).and_then(Value::as_array).map(Vec::as_slice) { + Some([n, p]) => Some((n.as_str().unwrap_or_default().to_string(), p.clone())), + _ => fields + .get(BEVEL_PROFILE) + .filter(|p| custom && !p.is_null()) + .map(|p| (fields.get(BEVEL_NAME).and_then(Value::as_str).unwrap_or_default().to_string(), p.clone())), + }; + if let Some((n, p)) = own + && !options[builtin..].iter().any(|(_, _, c)| c.as_ref().is_some_and(|(cn, cp)| *cn == n && *cp == p)) + { + let mut shown = if n.is_empty() { tl!("Custom").to_string() } else { n.clone() }; + // Each pass makes the label longer, so this ends once no entry has it. + while options.iter().any(|(l, _, _)| *l == shown) { + shown = crate::i18n::fmt(tl!("{name} (document)"), &[("name", &shown)]); + } + options.push((shown, json!("custom"), Some((n, p)))); + } + (options, builtin) +} + +/// The form field where the 3D and Materials panel puts the first selected effect's custom bevel, +/// `[name, points]`, so Bevel Shape lists it while a mixed selection unsets the shown bevel. +pub(crate) const OWN_BEVEL: &str = "__ownBevel"; + +/// The Bevel Shape menu of Extrude & Bevel and Extrude & Bevel (Classic) (`effect`): None and the +/// built-in shapes, then the custom bevels of the bevels file, and the effect's own custom bevel +/// when the file does not list it (a document from elsewhere carries its points). Picking a +/// custom bevel stores its name and a copy of its points. In the 3D and Materials panel, Edit +/// Bevels… opens the bevels file (`__editBevels`, which the panel runs). +pub(super) fn bevel_choice(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, effect: &str) { + const KEY: &str = "bevel"; + let (options, builtin) = bevel_options(app, &d.fields, effect); + let name = d.fields.get(BEVEL_NAME).and_then(Value::as_str).unwrap_or_default().to_string(); + let points = d.fields.get(BEVEL_PROFILE).filter(|v| !v.is_null()).cloned(); + let custom = d.fields.get(KEY).and_then(Value::as_str) == Some("custom"); + let is = |c: &Option<(String, Value)>| c.as_ref().is_some_and(|(n, p)| *n == name && Some(p) == points.as_ref()); + let default = vectorcraft_effects::default_params(effect).and_then(|p| p.get(KEY).cloned()).unwrap_or(Value::Null); + let mixed = d.fields.get(KEY).is_some_and(Value::is_null); + let value = d.fields.get(KEY).filter(|v| !v.is_null()).cloned().unwrap_or_else(|| default.clone()); + let current = if custom { + options[builtin..].iter().position(|(_, _, c)| is(c)).map(|i| i + builtin) + } else { + options[..builtin].iter().position(|(_, v, _)| *v == value) + }; + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = 6.0; + label(ui, tl!("Bevel Shape")); + let labels: Vec<&str> = options.iter().map(|(l, _, _)| l.as_str()).collect(); + let shown = current.and_then(|i| labels.get(i)).copied().unwrap_or(""); + let width = VALUE_W + rail_width(ui) + 6.0; + // Marked by index, not label: a custom bevel's name can match another entry's label. + let picked = widgets::combo(ui, ("three-d-choice", KEY), shown, width, |ui| { + let mut chosen = None; + for (i, l) in labels.iter().enumerate() { + if ui.add(egui::Button::selectable(current == Some(i), *l)).clicked() { + chosen = Some(i); + } + } + chosen + }); + if let Some(k) = picked + && let Some((_, v, c)) = options.get(k) + { + d.fields.insert(KEY.into(), v.clone()); + if let Some((n, p)) = c { + d.fields.insert(BEVEL_NAME.into(), json!(n)); + d.fields.insert(BEVEL_PROFILE.into(), p.clone()); + } + } + let default_label = options.iter().find(|(_, v, _)| *v == default).map_or("", |(l, _, _)| l.as_str()); + if reset_dot(ui, KEY, mixed || value != default, default_label) { + d.fields.insert(KEY.into(), default.clone()); + } + }); + if d.bool("__panel") { + let enabled = app.session.bevels.path().is_some(); + if ui.add_enabled(enabled, egui::Button::new(tl!("Edit Bevels…"))).clicked() { + d.fields.insert("__editBevels".into(), json!(true)); + } + } +} + /// Extrude & Bevel's depth, twist, taper, cap and bevel. -fn extrude_controls(ui: &mut egui::Ui, d: &mut Dialog, unit: Unit) { +fn extrude_controls(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, unit: Unit) { heading(ui, tl!("Object")); number(ui, d, "depth", tl!("Depth"), (0.0, 2000.0), "", 1, Some(unit)); number(ui, d, "twist", tl!("Twist"), (0.0, 360.0), "°", 1, None); @@ -261,9 +361,7 @@ fn extrude_controls(ui: &mut egui::Ui, d: &mut Dialog, unit: Unit) { choice(ui, d, "cap", c3("Cap"), &[(json!(true), c3("Solid")), (json!(false), c3("Hollow"))]); ui.add_space(10.0); bevel_heading(ui, d); - let shapes: Vec<(Value, &str)> = - super::effect::own_choices(EXTRUDE, "bevel", false).unwrap_or_default().into_iter().map(|(label, value)| (json!(value), label)).collect(); - choice(ui, d, "bevel", tl!("Bevel Shape"), &shapes); + bevel_choice(app, ui, d, EXTRUDE); ui.add_enabled_ui(d.str("bevel") != "none", |ui| { number(ui, d, "bevelWidth", tl!("Width"), (0.0, 1000.0), "", 1, Some(unit)); number(ui, d, "bevelHeight", tl!("Height"), (0.0, 1000.0), "", 1, Some(unit)); diff --git a/crates/ui-egui/src/dialogs/symbolism_options.rs b/crates/ui-egui/src/dialogs/symbolism_options.rs index 43a37812b5..08866563fd 100644 --- a/crates/ui-egui/src/dialogs/symbolism_options.rs +++ b/crates/ui-egui/src/dialogs/symbolism_options.rs @@ -12,7 +12,7 @@ use serde_json::{Map, Value, json}; use vectorcraft_tools::settings::SYMBOLISM; -use super::{DialogResult, DialogSpec, form, set_tool_options_and_close}; +use super::{DialogResult, DialogSpec, form, modal, set_tool_options_and_close}; use crate::state::Dialog; use crate::{VectorcraftApp, widgets}; @@ -55,6 +55,13 @@ pub fn open(app: &mut VectorcraftApp, tool: &str) -> Value { } fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { + // The rows scroll when the window is shorter than they are, so the heading and the buttons + // stay in view. + modal::scrolled_rows(ui, "symbolism-options-rows", |ui| rows(app, ui, d)); + false +} + +fn rows(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { let unit = app.session.general_unit(); // The tool whose options show below (the eight tools share one toolbar icon, so they are listed // by name). @@ -107,10 +114,9 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { } ui.add_space(10.0); form::check(ui, d, "showBrush", tl!("Show Brush Size and Intensity")); - false } -/// The selected symbol sets that can be edited (not locked or hidden). +/// The selected symbol sets that can be edited (a locked or hidden one keeps its density). fn selected_sets(app: &VectorcraftApp) -> Vec { let Some(st) = app.session.active() else { return vec![] }; let editable = st.doc.editable(); @@ -123,39 +129,42 @@ fn selected_sets(app: &VectorcraftApp) -> Vec { } /// OK: set the brush the Symbolism tools share, after giving a new Symbol Set Density to the -/// selected symbol sets. Every option is checked first, so a value the tools refuse (a number out -/// of its range included) leaves the symbol sets and the options as they are. +/// selected symbol sets. A value outside its range is refused and changes nothing. fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> DialogResult { - let mut values: Map = - NUMBERS.iter().filter(|k| d.fields.contains_key(**k)).map(|k| (k.to_string(), json!(d.f64(k, 0.0)))).collect(); - // The checkboxes and choices as the fields hold them, so a value the tools do not have is refused. - values.extend(SWITCHES.iter().chain(&SPRAY).chain(&["method"]).filter_map(|k| Some((k.to_string(), d.fields.get(*k)?.clone())))); - // An option `tool.setOption` refuses leaves the symbol sets as they are too. + // Each value goes to the check as it is stored, so one of the wrong kind is refused rather than + // read as 0 or false. A number stored as text is read as the field reads it, and other text is + // refused. + let stored = |k: &str| match d.fields.get(k) { + Some(Value::String(s)) => Some(vectorcraft_doc::Unit::Points.parse(s).map_or_else(|| json!(s), |n| json!(n))), + v => v.cloned(), + }; + let mut values: Map = NUMBERS.iter().filter_map(|k| Some((k.to_string(), stored(k)?))).collect(); + values.extend(SWITCHES.iter().filter_map(|k| Some((k.to_string(), d.fields.get(*k)?.clone())))); + values.extend(SPRAY.iter().chain(&["method"]).filter(|k| d.fields.contains_key(**k)).map(|k| (k.to_string(), json!(d.str(k))))); + // A tool or a value `tool.setOption` refuses changes no density either: the values go through + // both of its checks, the kinds and then each option's range, before the density changes. let tool = d.str("tool"); if !SYMBOLISM.contains(&tool.as_str()) { return Err(format!("unknown tool `{tool}`")); } - // A number, or text that reads as one (a length with its unit for the diameter). - let readable = |v: &Value| match v { - Value::Number(_) => true, - Value::String(s) => vectorcraft_doc::Unit::Points.parse(s).is_some(), - _ => false, - }; - if let Some(k) = NUMBERS.iter().chain(&[DENSITY_WAS]).find(|k| d.fields.get(**k).is_some_and(|v| !readable(v))) { - return Err(format!("`{k}` must be a number")); - } vectorcraft_tools::symbolism::check_options(&tool, &values)?; + vectorcraft_tools::option_check::check_values(&vectorcraft_tools::symbolism::SymbolismTool::new(&tool), &values)?; + // The density the sets had when the dialog opened is read as a number too. + if stored(DENSITY_WAS).is_some_and(|v| !v.is_number()) { + return Err(format!("`{DENSITY_WAS}` must be a number")); + } let (from, to) = (d.f64(DENSITY_WAS, 0.0).clamp(1.0, 10.0), d.f64("density", 0.0).clamp(1.0, 10.0)); let sets = selected_sets(app); if d.fields.contains_key(DENSITY_WAS) && from != to && !sets.is_empty() { app.run("symbol.setDensity", json!({ "from": from, "to": to, "ids": sets }))?; } - set_tool_options_and_close(app, json!({ "tool": d.str("tool"), "values": values })) + set_tool_options_and_close(app, json!({ "tool": tool, "values": values })) } #[cfg(test)] mod tests { use super::*; + use egui_kittest::kittest::Queryable; use vectorcraft_engine::Session; fn app() -> VectorcraftApp { @@ -168,6 +177,39 @@ mod tests { crate::tests_labels::painted_text(app, |app, ui| super::super::show(app, ui.ctx())) } + /// In a short window the rows scroll, and the heading, OK and Cancel stay on the screen. + #[test] + fn the_buttons_stay_in_view_in_a_short_window() { + let mut app = app(); + app.run("tool.options", json!({"tool": "symbolSprayer"})).unwrap(); + let mut fonts = false; + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(900.0, 800.0)).build_ui_state( + move |ui, app: &mut VectorcraftApp| { + if !std::mem::replace(&mut fonts, true) { + crate::theme::install_fonts(ui.ctx()); + return; + } + super::super::show(app, ui.ctx()); + }, + app, + ); + h.run_steps(4); + for (physical, zoom) in [(egui::vec2(1366.0, 768.0), 1.5), (egui::vec2(1280.0, 720.0), 1.5), (egui::vec2(800.0, 600.0), 1.0)] { + h.ctx.set_zoom_factor(zoom); + for _ in 0..12 { + h.set_size(physical / zoom); + h.run_steps(1); + } + let screen = h.ctx.content_rect(); + let heading = h.get_by_role_and_label(egui::accesskit::Role::Label, "Symbolism Tools Options").rect(); + assert!(screen.contains_rect(heading), "{physical:?} at {zoom}: the heading {heading:?} in {screen:?}"); + for label in ["OK", "Cancel"] { + let rect = h.get_by_label(label).rect(); + assert!(screen.contains_rect(rect), "{physical:?} at {zoom}: {label} {rect:?} in {screen:?}"); + } + } + } + #[test] fn the_symbolism_tools_share_the_options_ok_sets() { let mut app = app(); @@ -280,6 +322,56 @@ mod tests { app.run("tool.options", json!({"tool": "symbolSprayer"})).unwrap(); super::super::confirm(&mut app).unwrap(); assert_eq!((width(&app), undo(&app)), (was, steps)); + // An option that `tool.setOption` refuses changes neither the density nor the set. + app.run("tool.options", json!({"tool": "symbolSprayer"})).unwrap(); + let fields = &mut app.ui.dialog.as_mut().unwrap().fields; + fields.insert("density".into(), json!(9)); + fields.insert("method".into(), json!("smooth")); + assert!(super::super::confirm(&mut app).is_err()); + assert_eq!((width(&app), undo(&app)), (was, steps)); + assert_eq!(app.session.tool_options_of("symbolSizer")["density"].as_f64(), Some(5.0)); + // So does a checkbox or a number stored as a value of the wrong kind, or a number outside its + // range. + for (k, v) in [ + ("diameter", json!(1)), + ("intensity", json!(11)), + ("usePressure", json!("invalid")), + ("proportional", json!(1)), + ("intensity", json!("strong")), + ("diameter", json!(true)), + ("tool", json!("pen")), + ("tool", json!(null)), + ] { + app.run("tool.options", json!({"tool": "symbolSprayer"})).unwrap(); + let fields = &mut app.ui.dialog.as_mut().unwrap().fields; + fields.insert("density".into(), json!(9)); + fields.insert(k.into(), v); + assert!(super::super::confirm(&mut app).is_err(), "{k}"); + assert_eq!((width(&app), undo(&app)), (was, steps), "{k}"); + let o = app.session.tool_options_of("symbolSizer"); + assert_eq!((o["density"].as_f64(), o["usePressure"].as_bool()), (Some(5.0), Some(false)), "{k}"); + } + // A selected set that is locked keeps its density, and OK still sets the options. + let lock = |app: &mut VectorcraftApp, on: bool| { + app.session + .edit("Lock", |d, _| { + d.node_mut(vectorcraft_doc::NodeId(set)).unwrap().locked = on; + Ok(()) + }) + .unwrap(); + }; + lock(&mut app, true); + let steps_locked = undo(&app); + app.run("tool.options", json!({"tool": "symbolSprayer"})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("density".into(), json!(8)); + super::super::confirm(&mut app).unwrap(); + assert_eq!((width(&app), undo(&app)), (was, steps_locked)); + assert_eq!(app.session.tool_options_of("symbolSizer")["density"].as_f64(), Some(8.0)); + lock(&mut app, false); + app.run("tool.options", json!({"tool": "symbolSprayer"})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("density".into(), json!(5)); + super::super::confirm(&mut app).unwrap(); + let steps = undo(&app); // A higher density packs the set closer, as one undo step. app.run("tool.options", json!({"tool": "symbolSprayer"})).unwrap(); app.ui.dialog.as_mut().unwrap().fields.insert("density".into(), json!(9)); diff --git a/crates/ui-egui/src/dialogs/tests_export.rs b/crates/ui-egui/src/dialogs/tests_export.rs index c0eccbc56d..6d388f7950 100644 --- a/crates/ui-egui/src/dialogs/tests_export.rs +++ b/crates/ui-egui/src/dialogs/tests_export.rs @@ -259,11 +259,12 @@ fn the_format_list_shows_its_scroll_bar_at_rest_and_opens_with_the_chosen_format _ => {} } } - let labels: Vec<&str> = export_as::formats().iter().map(|f| f.label).collect(); // A built-in format six from the end of the built-in ones: out of view when the list opens at // its top, and far enough from the end that a plug-in format another test adds after the - // built-in ones does not move the rows shown around it. + // built-in ones does not move the rows shown around it. The window is short enough that the + // list centered on it stops short of its end. let built_in: Vec<_> = fileio::FORMATS.iter().filter(|f| f.write && !matches!(f.id, "vectorcraft" | "ai")).collect(); + let labels: Vec<&str> = built_in.iter().map(|f| f.label).collect(); let chosen = built_in.len().checked_sub(6).and_then(|i| built_in.get(i)).copied().expect("Export As lists formats"); let (mut app, _) = app(1); app.run("file.exportAs", json!({"format": chosen.id})).unwrap(); @@ -272,31 +273,38 @@ fn the_format_list_shows_its_scroll_bar_at_rest_and_opens_with_the_chosen_format theme::apply(&ctx, Default::default()); // Every scroll area takes the bar at rest from the theme, whatever style the list sets itself. assert_eq!(ctx.global_style().spacing.scroll, crate::widgets::list_scroll_style()); - let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1024.0, 480.0))); + let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1024.0, 280.0))); let mut time = 0.0; + let popup = std::cell::RefCell::new(vec![]); + // The texts and bars painted on the open list (without the dialog under it), and every text. let mut run = |app: &mut VectorcraftApp, events: Vec| { time += 0.25; - let mut out = ctx.run_ui(egui::RawInput { screen_rect, events, time: Some(time), ..Default::default() }, |ui| show(app, ui.ctx())); + let mut out = ctx.run_ui(egui::RawInput { screen_rect, events, time: Some(time), ..Default::default() }, |ui| { + show(app, ui.ctx()); + popup.replace(crate::widgets::top_popup_shapes(ui.ctx())); + }); out.textures_delta.clear(); - let (mut texts, mut bars) = (vec![], vec![]); - out.shapes.iter().for_each(|c| walk(&c.shape, c.clip_rect, &mut texts, &mut bars)); - (texts, bars) + let (mut texts, mut bars, mut all) = (vec![], vec![], vec![]); + popup.take().iter().for_each(|c| walk(&c.shape, c.clip_rect, &mut texts, &mut bars)); + out.shapes.iter().for_each(|c| walk(&c.shape, c.clip_rect, &mut all, &mut vec![])); + (texts, bars, all) }; let away = egui::Event::PointerMoved(egui::pos2(1.0, 1.0)); run(&mut app, vec![away.clone()]); - let (texts, _) = run(&mut app, vec![]); + let (_, _, texts) = run(&mut app, vec![]); let field = texts.iter().find(|(s, ..)| s == chosen.label).map(|(_, r, _)| r.center()).expect("the Format field shows the chosen format"); let click_at = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; // Opens the list, moves the pointer away and returns the list's rect, the format names drawn in // it with their clip rects, and the bars drawn. - type Run<'r> = dyn FnMut(&mut VectorcraftApp, Vec) -> (Vec<(String, egui::Rect, egui::Rect)>, Vec) + 'r; + type Texts = Vec<(String, egui::Rect, egui::Rect)>; + type Run<'r> = dyn FnMut(&mut VectorcraftApp, Vec) -> (Texts, Vec, Texts) + 'r; let open = |run: &mut Run<'_>, app: &mut VectorcraftApp| { run(app, vec![egui::Event::PointerMoved(field), click_at(field, true)]); run(app, vec![click_at(field, false)]); run(app, vec![away.clone()]); let (mut texts, mut bars) = (vec![], vec![]); for _ in 0..4 { - (texts, bars) = run(app, vec![]); + (texts, bars, _) = run(app, vec![]); } let list = ctx .memory(|m| { @@ -334,11 +342,13 @@ fn the_format_list_shows_its_scroll_bar_at_rest_and_opens_with_the_chosen_format run(&mut app, vec![wheel]); let mut scrolled = vec![]; for _ in 0..4 { - (scrolled, _) = run(&mut app, vec![]); + (scrolled, ..) = run(&mut app, vec![]); } let scrolled: Vec<_> = scrolled.into_iter().filter(|(s, r, _)| labels.contains(&s.as_str()) && list.contains_rect(*r)).collect(); - run(&mut app, vec![egui::Event::PointerMoved(field), click_at(field, true)]); - run(&mut app, vec![click_at(field, false)]); + // Escape closes it: a list taller than the room beside its field covers the field. + let escape = |pressed| egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed, repeat: false, modifiers: Default::default() }; + run(&mut app, vec![escape(true)]); + run(&mut app, vec![escape(false)]); let (_, reopened, _) = open(&mut run, &mut app); if rows.len() < labels.len() { assert_ne!(tops(&scrolled), tops(&rows), "the wheel scrolled the list"); @@ -347,6 +357,83 @@ fn the_format_list_shows_its_scroll_bar_at_rest_and_opens_with_the_chosen_format assert!(whole(&reopened, chosen.label), "the chosen format shows whole: {:?}", tops(&reopened)); } +/// #5941: the Format list stopped at the room on one side of its field, so a window with room for +/// every format still cut the list short. In windows of 1280×900 and 1000×856 the list shows every +/// built-in format whole, the grayed-out DWG row after them included, inside the window, without a +/// scroll bar. A plug-in format that another test adds or removes meanwhile is not counted. +#[test] +fn the_format_list_shows_every_format_when_the_window_has_room() { + fn walk(shape: &egui::Shape, clip: egui::Rect, texts: &mut Vec<(String, egui::Rect, egui::Rect)>, bars: &mut Vec) { + match shape { + egui::Shape::Text(t) => texts.push((t.galley.text().into(), t.visual_bounding_rect(), clip)), + egui::Shape::Rect(r) if r.fill.a() > 0 && r.rect.width() <= 8.0 && r.rect.height() > 40.0 => bars.push(r.rect), + egui::Shape::Vec(v) => v.iter().for_each(|s| walk(s, clip, texts, bars)), + _ => {} + } + } + let labels: Vec<&str> = + fileio::FORMATS.iter().filter(|f| f.write && !matches!(f.id, "vectorcraft" | "ai")).map(|f| f.label).chain(["DWG (use DXF)"]).collect(); + for (width, height) in [(1280.0, 900.0), (1000.0, 856.0)] { + let case = format!("{width}×{height}"); + let (mut app, _) = app(1); + app.run("file.exportAs", json!({"format": "png"})).unwrap(); + let ctx = egui::Context::default(); + theme::install_fonts(&ctx); + theme::apply(&ctx, Default::default()); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(width, height)); + let mut time = 0.0; + let popup = std::cell::RefCell::new(vec![]); + // The texts and bars painted on the open list (without the dialog under it), and every text. + let mut run = |app: &mut VectorcraftApp, events: Vec| { + time += 0.25; + let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), events, time: Some(time), ..Default::default() }, |ui| { + show(app, ui.ctx()); + popup.replace(crate::widgets::top_popup_shapes(ui.ctx())); + }); + out.textures_delta.clear(); + let (mut texts, mut bars, mut all) = (vec![], vec![], vec![]); + popup.take().iter().for_each(|c| walk(&c.shape, c.clip_rect, &mut texts, &mut bars)); + out.shapes.iter().for_each(|c| walk(&c.shape, c.clip_rect, &mut all, &mut vec![])); + (texts, bars, all) + }; + let away = egui::Event::PointerMoved(egui::pos2(1.0, 1.0)); + run(&mut app, vec![away.clone()]); + let (_, _, all) = run(&mut app, vec![]); + let field = all.iter().find(|(s, ..)| s == "PNG").map(|(_, r, _)| r.center()).expect("the Format field shows PNG"); + let click = |pressed| egui::Event::PointerButton { pos: field, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + run(&mut app, vec![egui::Event::PointerMoved(field), click(true)]); + run(&mut app, vec![click(false)]); + run(&mut app, vec![away.clone()]); + let list_rect = || { + ctx.memory(|m| { + m.layer_ids().filter(|l| l.order == egui::Order::Foreground && m.areas().is_visible(l)).last().and_then(|l| m.area_rect(l.id)) + }) + }; + // A plug-in format that another test installs or removes changes the list's height, and the + // list is placed for its new height on the pass after. Read it once it keeps its rect. + let (mut texts, mut bars, mut list) = (vec![], vec![], None); + for _ in 0..12 { + (texts, bars, _) = run(&mut app, vec![]); + let now = list_rect(); + if now.is_some() && now == list { + break; + } + list = now; + } + let list = list.expect("the Format list is open"); + assert!(screen.contains_rect(list), "{case}: the list {list:?} is inside the window"); + let whole: Vec<&str> = labels + .iter() + .copied() + .filter(|name| { + texts.iter().any(|(s, r, clip)| s == name && list.contains_rect(*r) && r.top() >= clip.top() && r.bottom() <= clip.bottom()) + }) + .collect(); + assert_eq!(whole, labels, "{case}: every format shows whole in {list:?}"); + assert!(bars.is_empty(), "{case}: a list that shows every format draws no scroll bar: {bars:?}"); + } +} + #[test] fn svg_continues_in_svg_options() { let (mut app, written) = app(2); diff --git a/crates/ui-egui/src/dialogs/tests_hpgl.rs b/crates/ui-egui/src/dialogs/tests_hpgl.rs index 77e4071f74..45e1075260 100644 --- a/crates/ui-egui/src/dialogs/tests_hpgl.rs +++ b/crates/ui-egui/src/dialogs/tests_hpgl.rs @@ -258,6 +258,24 @@ fn pen_table_starts_from_the_pens_of_what_the_export_plots() { assert_eq!(seed(&app), on_board); } +/// OK after another document has become the active one closes HP-GL Options and writes nothing, so +/// the other document is not written to the path chosen for the first. +#[test] +fn hpgl_options_write_nothing_after_another_document_became_active() { + let (mut app, written) = app(1); + app.run("ui.hpglOptionsDialog", json!({"path": "/out/first.plt"})).unwrap(); + app.run("file.new", json!({"width": 60, "height": 40})).unwrap(); + assert_eq!(kind(&app), Some("hpglOptions")); + assert_eq!(confirm(&mut app).unwrap(), json!({})); + assert!(app.ui.dialog.is_none()); + assert!(written.borrow().is_empty(), "nothing is written over the first document's path"); + // Opened for the document that is active, OK writes it. + app.run("window.nextDocument", json!({})).unwrap(); + app.run("ui.hpglOptionsDialog", json!({"path": "/out/first.plt"})).unwrap(); + confirm(&mut app).unwrap(); + assert_eq!(names(&written), ["/out/first.plt"]); +} + #[test] fn the_hpgl_options_dialog_needs_a_document() { let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); diff --git a/crates/ui-egui/src/dialogs/tests_import_pdf.rs b/crates/ui-egui/src/dialogs/tests_import_pdf.rs index 5ecd7734cb..06bdf5e1b7 100644 --- a/crates/ui-egui/src/dialogs/tests_import_pdf.rs +++ b/crates/ui-egui/src/dialogs/tests_import_pdf.rs @@ -350,3 +350,144 @@ fn the_import_dialog_stays_where_there_is_something_to_ask() { assert!(import_pdf::offer(&mut app, "two.ai", &two_pages(true, None), None, Some(&json!({})))); assert_eq!(app.ui.dialog.as_ref().unwrap().str("mode"), "place"); } + +/// `pages` pages, each showing "AB" in a font the file names without embedding it. +fn text_pages(pages: usize) -> Vec { + let font = format!("/Font << /F1 {} 0 R >>", first_extra(pages)); + let page = PdfPage { resources: font, ..PdfPage::new(100.0, 100.0, "BT /F1 20 Tf 1 0 0 1 10 40 Tm (AB) Tj ET") }; + pdf_with(&vec![page; pages], &["<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>"], None) +} + +/// The type objects of the active document. +fn type_objects(app: &VectorcraftApp) -> usize { + let mut n = 0; + app.session.active().unwrap().doc.walk(|node| n += usize::from(matches!(node.kind, NodeKind::Text(_)))); + n +} + +fn set_pdf_text(app: &mut VectorcraftApp, value: &str) { + app.run("prefs.set", json!({"key": "pdfTextAs", "value": value})).unwrap(); +} + +/// The Import PDF dialog is closed; the Missing Fonts dialog an editable open asks with is +/// dismissed. +fn opened(app: &mut VectorcraftApp) { + assert!(!app.ui.dialog.as_ref().is_some_and(|d| d.kind == import_pdf::KIND), "the Import PDF dialog closed"); + app.ui.dialog = None; + app.ui.pending_fonts.clear(); +} + +/// The Text choice starts from the PDF Text preference (Editable by default), Outlines opens the +/// pages' text as outlines, and OK keeps the choice for the next PDF. Outlines clears and dims +/// Import PDF pages as links (`linkPages` refuses it). +#[test] +fn the_text_choice_opens_text_as_outlines_and_is_kept() { + let mut app = app(); + assert_eq!(app.session.prefs.pdf_text_as, "text"); + io::open_bytes(&mut app, "two.pdf", &text_pages(2), None).unwrap(); + assert_eq!(field(&app, "textAs"), "text", "Editable by default"); + frame(&mut app); + confirm(&mut app).unwrap(); + opened(&mut app); + assert_eq!(type_objects(&app), 2, "one type object per page"); + assert_eq!(app.session.prefs.pdf_text_as, "text"); + + io::open_bytes(&mut app, "two.pdf", &text_pages(2), None).unwrap(); + set(&mut app, "textAs", json!("outlines")); + frame(&mut app); + confirm(&mut app).unwrap(); + opened(&mut app); + assert_eq!(type_objects(&app), 0, "the text is outlines"); + assert_eq!(app.session.prefs.pdf_text_as, "outlines", "OK keeps the choice"); + + // The next PDF starts from Outlines; a file it could link opens unlinked while Outlines is picked. + io::open_bytes(&mut app, "/tmp/two.pdf", &text_pages(2), Some("/tmp/two.pdf".into())).unwrap(); + assert_eq!(field(&app, "textAs"), "outlines"); + assert!(!import_pdf::links_on(app.ui.dialog.as_ref().unwrap()), "Outlines: not linked"); + frame(&mut app); + set(&mut app, "textAs", json!("text")); + assert!(import_pdf::links_on(app.ui.dialog.as_ref().unwrap()), "Editable: All links the pages again"); +} + +/// A PDF that opens without the dialog (one page) takes the PDF Text preference, unless the open +/// gives `textAs`; a `.ai` file opens as it says. +#[test] +fn a_pdf_opened_without_the_dialog_takes_the_pdf_text_preference() { + let mut app = app(); + let one = text_pages(1); + io::open_bytes(&mut app, "one.pdf", &one, None).unwrap(); + opened(&mut app); + assert_eq!(type_objects(&app), 1, "Editable by default"); + set_pdf_text(&mut app, "outlines"); + io::open_bytes(&mut app, "one.pdf", &one, None).unwrap(); + opened(&mut app); + assert_eq!(type_objects(&app), 0, "Outlines"); + io::open_document(&mut app, "one.pdf", &one, None, &json!({"textAs": "text"})).unwrap(); + opened(&mut app); + assert_eq!(type_objects(&app), 1, "an open that gives textAs keeps it"); + let p = import_pdf::with_preferred_text_as(&app, "one.ai", &one, &serde_json::Value::Null); + assert!(p.is_null(), "a .ai file opens as it says: {p}"); + // In the dialog too, a .ai file starts from Editable, and its choice is not kept for PDFs. + assert!(import_pdf::offer(&mut app, "two.ai", &two_pages(false, None), None, None)); + assert_eq!(field(&app, "textAs"), "text", "a .ai file starts from Editable"); + frame(&mut app); + confirm(&mut app).unwrap(); + opened(&mut app); + assert_eq!(app.session.prefs.pdf_text_as, "outlines", "the preference stays"); + // An open with linkPages keeps the file's own text, which linked pages show. + let dir = vectorcraft_testkit::TempDir::new("import-pdf-text-link-pages"); + let path = dir.join("one.pdf").to_string_lossy().into_owned(); + std::fs::write(&path, &one).unwrap(); + io::open_document(&mut app, &path, &one, Some(path.clone()), &json!({"linkPages": true})).unwrap(); + opened(&mut app); + assert_eq!(placed_pages(&app), [true], "opened linked"); +} + +/// Placing a page embedded takes the Text choice (and the preference when no dialog asks); a +/// linked place shows the file's own text, so the choice is dimmed and not sent. +#[test] +fn the_text_choice_applies_to_embedded_places_only() { + let mut app = app(); + // `textAs: null` leaves the param out: the dialog's choice is sent. + place(&mut app, &text_pages(2), json!({"link": false, "textAs": null})).unwrap(); + assert_eq!(field(&app, "textAs"), "text"); + set(&mut app, "textAs", json!("outlines")); + frame(&mut app); + confirm(&mut app).unwrap(); + opened(&mut app); + assert_eq!(type_objects(&app), 0, "placed as outlines"); + assert_eq!(app.session.prefs.pdf_text_as, "outlines"); + // One page asks nothing: placed by the user, it takes the preference. + let one = json!({"name": "one.pdf", "dataBase64": vectorcraft_format::base64_encode(&text_pages(1))}); + crate::place::run_for_user(&mut app, &one).unwrap(); + assert_eq!(type_objects(&app), 0, "the preference"); + set_pdf_text(&mut app, "text"); + crate::place::run_for_user(&mut app, &one).unwrap(); + assert_eq!(type_objects(&app), 1); + + // Linked: the choice is not sent, and OK leaves the preference as it is. + set_pdf_text(&mut app, "outlines"); + let dir = vectorcraft_testkit::TempDir::new("import-pdf-text-linked"); + let path = dir.join("two.pdf").to_string_lossy().into_owned(); + std::fs::write(&path, text_pages(2)).unwrap(); + assert!(import_pdf::offer(&mut app, &path, &text_pages(2), Some(path.clone()), Some(&json!({"link": true})))); + frame(&mut app); + confirm(&mut app).unwrap(); + let st = app.session.active().unwrap(); + let placed = st.doc.node(st.selection.objects[0]).unwrap(); + assert!(matches!(placed.kind, NodeKind::PlacedDocument(_)), "linked: {:?}", placed.kind); + assert_eq!(app.session.prefs.pdf_text_as, "outlines"); + + // A place that gives `textAs: "outlines"` with Link on is embedded as outlines, as without the dialog. + set_pdf_text(&mut app, "text"); + assert!(import_pdf::offer(&mut app, &path, &text_pages(2), Some(path.clone()), Some(&json!({"link": true, "textAs": "outlines"})))); + assert_eq!(field(&app, "textAs"), "outlines"); + frame(&mut app); + let before = type_objects(&app); + confirm(&mut app).unwrap(); + opened(&mut app); + let st = app.session.active().unwrap(); + let placed = st.doc.node(st.selection.objects[0]).unwrap(); + assert!(!matches!(placed.kind, NodeKind::PlacedDocument(_)), "embedded: {:?}", placed.kind); + assert_eq!(type_objects(&app), before, "placed as outlines"); +} diff --git a/crates/ui-egui/src/dialogs/three_d_classic.rs b/crates/ui-egui/src/dialogs/three_d_classic.rs index b3f1ebd3d9..f25251f574 100644 --- a/crates/ui-egui/src/dialogs/three_d_classic.rs +++ b/crates/ui-egui/src/dialogs/three_d_classic.rs @@ -13,15 +13,15 @@ use super::revolve::{c3, choice, heading, label, light_list, light_record, numbe use crate::state::Dialog; use crate::theme::Tokens; -/// Depth and cap, then the bevel: its shape, its height and whether it is added around the shape -/// or carved into it. -pub(super) fn object_controls(ui: &mut egui::Ui, d: &mut Dialog, unit: Unit) { +/// Depth and cap, then the bevel: its shape (a custom one included), its height and whether it is +/// added around the shape or carved into it. +pub(super) fn object_controls(app: &crate::VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, unit: Unit) { heading(ui, tl!("Object")); number(ui, d, "depth", tl!("Depth"), (0.0, 2000.0), "", 1, Some(unit)); choice(ui, d, "cap", c3("Cap"), &[(json!(true), c3("Solid")), (json!(false), c3("Hollow"))]); ui.add_space(10.0); heading(ui, c3("Bevel")); - choice(ui, d, "bevel", tl!("Bevel Shape"), &options("bevel")); + super::revolve::bevel_choice(app, ui, d, CLASSIC_EXTRUDE); ui.add_enabled_ui(d.str("bevel") != "none", |ui| { number(ui, d, "bevelHeight", tl!("Height"), (1.0, 100.0), "", 1, Some(unit)); toggle(ui, d, "bevelInside", tl!("Bevel Inside"), false); @@ -438,11 +438,6 @@ pub(super) fn surface_controls(ui: &mut egui::Ui, d: &mut Dialog) { } } -/// The values of Extrude & Bevel (Classic)'s `key` as the dropdowns list them, (value, label). -fn options(key: &str) -> Vec<(Value, &'static str)> { - options_of(CLASSIC_EXTRUDE, key) -} - /// The values of classic 3D effect `effect`'s `key` as the dropdowns list them, (value, label). fn options_of(effect: &str, key: &str) -> Vec<(Value, &'static str)> { super::effect::own_choices(effect, key, false).unwrap_or_default().into_iter().map(|(label, value)| (json!(value), label)).collect() diff --git a/crates/ui-egui/src/dialogs/tracing_presets.rs b/crates/ui-egui/src/dialogs/tracing_presets.rs new file mode 100644 index 0000000000..52c075c09b --- /dev/null +++ b/crates/ui-egui/src/dialogs/tracing_presets.rs @@ -0,0 +1,519 @@ +//! Edit → Tracing Presets: every tracing preset in a list (built-in ones in brackets, protected, +//! then the saved ones) with the selected one's settings beside it; New… (a preset starting from +//! the selected one), Edit… and Delete (saved presets), Import… and Export… (every saved preset) +//! under the list. New… and Edit… open the preset editor (kind `tracingPreset`): its OK saves the +//! preset with `imageTrace.presets.save` and comes back here on it, and its Cancel comes back with +//! nothing saved. An import whose file holds presets with the names of saved ones asks whether to +//! replace them (kind `tracingPresetsReplace`); Cancel keeps the saved ones. The saved presets are +//! the ones the Image Trace panel, the Control bar and Properties list. +//! +//! Fields: `selected` (a preset's name). The editor's: `name`, `params` (the tracing settings, as +//! `imageTrace.presets.save` takes them) and `editing` (the saved preset it edits; empty for a new +//! one). The question's: `names` (the presets the import skipped) and `file` (the file, as +//! `imageTrace.presets.import` takes it: `{path}` or `{dataBase64}`). Opening a `.vctracepresets` +//! file (File › Open, a drop, the web's Import… pick) imports it the same way. + +use serde_json::{Value, json}; +use vectorcraft_engine::cmd::swatchlib::DOCUMENT_SWATCHES; +use vectorcraft_engine::cmd::{TRACE_PRESET_EXTS, TRACE_PRESET_FORMAT, TRACE_PRESET_MAX_BYTES}; + +use super::{DialogSpec, form}; +use crate::panels::image_trace::{self, MODES, PALETTES, Preset}; +use crate::panels::swatches; +use crate::state::Dialog; +use crate::theme::Tokens; +use crate::{VectorcraftApp, widgets}; + +/// The dialog kind of Tracing Presets. +pub const KIND: &str = "tracingPresets"; + +/// The dialog kind of the tracing preset editor. +pub const PRESET_KIND: &str = "tracingPreset"; + +/// The dialog kind of the question whether an import replaces saved presets of the same names. +pub const REPLACE_KIND: &str = "tracingPresetsReplace"; + +/// The editor's field naming the saved preset it edits. +const EDITING: &str = "editing"; + +/// The tallest the tracing settings draw, in the manager and the editor, before they scroll (the +/// height of the manager's preset list), so the dialog's buttons stay on short screens. +const SETTINGS_HEIGHT: f32 = 300.0; + +pub(super) const SPEC: DialogSpec = DialogSpec { + heading: |_| tl!("Tracing Presets").into(), + body, + confirm: |app, _| { + app.ui.dialog = None; + Ok(Value::Null) + }, + ok: None, + min_width: 620.0, + ..DialogSpec::FORM +}; + +pub(super) const PRESET_SPEC: DialogSpec = DialogSpec { + heading: |_| tl!("Save Preset").into(), + body: preset_body, + confirm: confirm_preset, + ok_enabled: Some(|_, d| !d.str("name").trim().is_empty()), + min_width: 380.0, + ..DialogSpec::FORM +}; + +pub(super) const REPLACE_SPEC: DialogSpec = DialogSpec { + heading: |_| tl!("Replace the saved presets that have these names?").into(), + body: |_, ui, d| { + let names: Vec<&str> = d.fields.get("names").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str).collect(); + // A long list scrolls, so Replace and Cancel stay on screen. + super::modal::scrolled_rows(ui, "tracing-replace-names", |ui| { + ui.label(egui::RichText::new(names.join("\n")).color(Tokens::get(ui.ctx()).text_dim)); + }); + false + }, + confirm: confirm_replace, + ok: Some("Replace"), + max_width: Some(420.0), + ..DialogSpec::FORM +}; + +/// Open the presets manager on `selected` (default: the first preset, Default). +pub fn open(app: &mut VectorcraftApp, selected: Option<&str>) { + app.ui.dialog = Some(Dialog::new(KIND, json!({ "selected": selected.unwrap_or("Default") }))); +} + +/// The index in `all` of the preset `selected` names, found as the engine finds presets (the first +/// when none). +fn shown(all: &[Preset], selected: &str) -> usize { + image_trace::find_preset(all, selected).and_then(|p| all.iter().position(|q| std::ptr::eq(p, q))).unwrap_or(0) +} + +/// A preset's name as the list shows it: a built-in one translated and in brackets, a saved one as +/// the user named it. +fn list_label(p: &Preset) -> String { + if p.3 { format!("[{}]", image_trace::preset_label(&p.0)) } else { p.0.clone() } +} + +/// What a button asked for, done once the list and the settings are drawn. +enum Action { + Select(String), + New, + Edit, + Delete, + Import, + Export, +} + +fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { + let t = Tokens::get(ui.ctx()); + let all = image_trace::presets(app, ui.ctx()); + let i = shown(&all, &d.str("selected")); + let Some(preset) = all.get(i).cloned() else { return false }; + let builtin = preset.3; + let any_saved = all.iter().any(|p| !p.3); + let mut act = None; + ui.horizontal_top(|ui| { + ui.vertical(|ui| { + ui.set_width(260.0); + widgets::dim_label(ui, tl!("Presets:")); + widgets::list_box(ui, |ui| { + egui::ScrollArea::vertical().id_salt("tracing-presets").min_scrolled_height(300.0).max_height(300.0).show(ui, |ui| { + ui.set_width(ui.available_width()); + ui.set_min_height(300.0); + for (k, p) in all.iter().enumerate() { + if ui.selectable_label(k == i, list_label(p)).clicked() { + act = Some(Action::Select(p.0.clone())); + } + } + }); + }); + ui.add_space(6.0); + ui.horizontal(|ui| { + ui.spacing_mut().item_spacing.x = 4.0; + if widgets::flat_button(ui, tl!("New…"), 48.0).on_hover_text(tl!("A new preset starting from the selected one")).clicked() { + act = Some(Action::New); + } + if ui.add_enabled_ui(!builtin, |ui| widgets::flat_button(ui, tl!("Edit…"), 48.0)).inner.clicked() { + act = Some(Action::Edit); + } + if ui.add_enabled_ui(!builtin, |ui| widgets::flat_button(ui, tl!("Delete"), 52.0)).inner.clicked() { + act = Some(Action::Delete); + } + if widgets::flat_button(ui, tl!("Import…"), 60.0).clicked() { + act = Some(Action::Import); + } + if ui.add_enabled_ui(any_saved, |ui| widgets::flat_button(ui, tl!("Export…"), 60.0)).inner.clicked() { + act = Some(Action::Export); + } + }); + }); + ui.add_space(18.0); + ui.vertical(|ui| { + ui.set_width(320.0); + ui.label(egui::RichText::new(list_label(&preset)).color(t.text_strong).strong()); + ui.add_space(8.0); + // The selected preset's settings, as the editor shows them, to read only. They scroll + // past the height of the preset list. + let mut params = preset.1.clone(); + egui::ScrollArea::vertical().id_salt("tracing-preset-details").max_height(SETTINGS_HEIGHT).show(ui, |ui| { + ui.add_enabled_ui(false, |ui| settings_editor(app, ui, "tracing-presets", &mut params)); + }); + if builtin { + ui.add_space(6.0); + ui.label(egui::RichText::new(tl!("Built-in presets don't change: New makes a copy you can edit.")).color(t.text_dim).size(11.5)); + } + }); + }); + if let Some(a) = act { + let r = match a { + // Their file dialogs, shown off the UI thread, import into or export from the dialog + // as it is then. + Action::Import | Action::Export => { + let export = matches!(a, Action::Export); + crate::picks::in_app_dialog(app, d, move |app, d| run(app, d, if export { Action::Export } else { Action::Import }, "")) + } + a => run(app, d, a, &preset.0), + }; + if let Err(e) = r { + app.status(e); + } + } + false +} + +fn select(d: &mut Dialog, name: &str) { + d.fields.insert("selected".into(), json!(name)); +} + +fn run(app: &mut VectorcraftApp, d: &mut Dialog, act: Action, current: &str) -> Result<(), String> { + match act { + Action::Select(name) => select(d, &name), + // The editor replaces this dialog; its OK and its Cancel come back here. + Action::New => *d = editor(app, d, current, false)?, + Action::Edit => *d = editor(app, d, current, true)?, + Action::Delete => { + let i = app.session.prefs.trace_presets.iter().position(|p| p.name == current); + app.run("imageTrace.presets.delete", json!({ "name": current }))?; + // The saved preset below it takes its place, else the one above it, else Default. + let saved = &app.session.prefs.trace_presets; + let next = i.and_then(|i| saved.get(i).or_else(|| i.checked_sub(1).and_then(|k| saved.get(k)))).map(|p| p.name.clone()); + select(d, next.as_deref().unwrap_or("Default")); + } + Action::Import => { + // On the web the picked file arrives later and imports through `io::open_bytes`. + if crate::picks::open_async(app) { + return Ok(()); + } + let pick = crate::FilePick { filters: vec![crate::FilePick::filter("Tracing presets", TRACE_PRESET_EXTS)], ..Default::default() }; + let path = crate::picks::open(app, &pick).ok_or("cancelled")?; + import(app, d, json!({ "path": path }))?; + } + Action::Export => { + crate::io::save_command_output(app, "imageTrace.presets.export", TRACE_PRESET_FORMAT, json!({}))?; + } + } + Ok(()) +} + +/// Import the tracing presets file `file` (`{path}` or `{dataBase64}`) into the saved presets, +/// keeping saved presets of the same names → the presets the file added and the names it skipped. +fn import_file(app: &mut VectorcraftApp, file: &Value) -> Result<(Value, Vec), String> { + let r = crate::io::import_presets(app, "imageTrace.presets.import", "tracing presets", file.clone())?; + let skipped = r["skipped"].as_array().cloned().unwrap_or_default(); + Ok((r["imported"].clone(), skipped)) +} + +/// The question whether the import of `file` replaces the saved presets `skipped` kept, over the +/// dialog `under` (Cancel shows it again). +fn ask_replace(under: Option<&Dialog>, skipped: Vec, file: Value) -> Dialog { + let under = under.and_then(|d| serde_json::to_value(d).ok()).unwrap_or(Value::Null); + Dialog::new(REPLACE_KIND, json!({ "names": skipped, "file": file, super::PARENT: under })) +} + +/// The error for a tracing presets file over the size limit. +fn too_big() -> String { + format!("the tracing presets file is larger than {} MiB", TRACE_PRESET_MAX_BYTES >> 20) +} + +/// The tracing presets file `file` as `{dataBase64}`: a `{path}` is read here, once, so the +/// question and its Replace act on the contents the first import checked. +fn file_contents(app: &VectorcraftApp, file: Value) -> Result { + let Some(path) = file.get("path").and_then(Value::as_str) else { return Ok(file) }; + vectorcraft_engine::file_access::check_read(path)?; + if std::fs::metadata(path).is_ok_and(|m| m.len() > TRACE_PRESET_MAX_BYTES as u64) { + return Err(too_big()); + } + // One byte past the limit tells a larger file apart without reading all of it. + let bytes = match (&app.services.read_head, &app.services.read) { + (Some(read_head), _) => read_head(path, TRACE_PRESET_MAX_BYTES + 1)?, + (None, Some(read)) => read(path)?, + (None, None) => return Err("no file reader".into()), + }; + if bytes.len() > TRACE_PRESET_MAX_BYTES { + return Err(too_big()); + } + Ok(json!({ "dataBase64": vectorcraft_format::base64_encode(&bytes) })) +} + +/// Import… on the manager `d`: the import of `file` ([`import_file`]) selects the first preset it +/// added, and when it kept saved presets of the file's names, `d` goes under the question whether +/// to replace them. +fn import(app: &mut VectorcraftApp, d: &mut Dialog, file: Value) -> Result<(), String> { + let file = file_contents(app, file)?; + let (imported, skipped) = import_file(app, &file)?; + if let Some(first) = imported.get(0).and_then(Value::as_str) { + select(d, first); + } + if !skipped.is_empty() { + *d = ask_replace(Some(d), skipped, file); + } + Ok(()) +} + +/// A tracing presets file opened (File › Open, a drop, or the file picked for Import… on the web): +/// it imports as Import… does, over the dialog open now (the manager selects the first preset it +/// added), and asks whether to replace saved presets of the file's names. +pub(crate) fn open_file(app: &mut VectorcraftApp, bytes: &[u8]) -> Result<(), String> { + if bytes.len() > TRACE_PRESET_MAX_BYTES { + return Err(too_big()); + } + open_import(app, json!({ "dataBase64": vectorcraft_format::base64_encode(bytes) })) +} + +/// [`open_file`] for the tracing presets file at `path` (File › Open, a drop): the file is read no +/// further than one byte past the size limit, as Import… reads it. +pub(crate) fn open_path(app: &mut VectorcraftApp, path: &str) -> Result<(), String> { + let file = file_contents(app, json!({ "path": path }))?; + open_import(app, file) +} + +/// The import of an opened tracing presets file `file` (`{dataBase64}`), over the dialog open now. +fn open_import(app: &mut VectorcraftApp, file: Value) -> Result<(), String> { + let (imported, skipped) = import_file(app, &file)?; + let mut under = app.ui.dialog.take(); + if let (Some(d), Some(first)) = (under.as_mut().filter(|d| d.kind == KIND), imported.get(0).and_then(Value::as_str)) { + select(d, first); + } + app.ui.dialog = if skipped.is_empty() { under } else { Some(ask_replace(under.as_ref(), skipped, file)) }; + Ok(()) +} + +/// Replace (the question's OK): the file imports again, replacing the saved presets of its names, +/// and the dialog it was asked over shows again (the manager on the first of them). +fn confirm_replace(app: &mut VectorcraftApp, d: &Dialog) -> Result { + let mut p = d.fields.get("file").cloned().filter(Value::is_object).ok_or("no tracing presets file")?; + p["replace"] = json!(true); + let r = app.run("imageTrace.presets.import", p)?; + let mut back = super::parent(d); + if let (Some(b), Some(first)) = (back.as_mut().filter(|b| b.kind == KIND), d.fields.get("names").and_then(|n| n.get(0)).and_then(Value::as_str)) { + select(b, first); + } + app.ui.dialog = back; + Ok(r) +} + +/// The preset editor over the manager `d`: on the saved preset `name` (`edit`), else on a new +/// preset starting from the preset `name`, under the first free "Tracing Preset N". +fn editor(app: &mut VectorcraftApp, d: &Dialog, name: &str, edit: bool) -> Result { + let (editing, new_name, params) = if edit { + let saved = app.session.trace_preset(name).ok_or_else(|| format!("no saved preset named `{name}`"))?; + (saved.name.clone(), saved.name.clone(), serde_json::to_value(&saved.params).map_err(|e| e.to_string())?) + } else { + let params = app.session.execute("imageTrace.presets", &json!({})).map_err(|e| e.to_string())?["presets"] + .as_array() + .and_then(|all| { + let found = |p: &&Value| p["name"].as_str().is_some_and(|n| n.eq_ignore_ascii_case(name)); + all.iter().find(|p| p["builtIn"] != false && found(p)).or_else(|| all.iter().find(found)).map(|p| p["params"].clone()) + }) + .ok_or_else(|| format!("no preset named `{name}`"))?; + (String::new(), app.session.new_trace_preset_name(), params) + }; + let under = serde_json::to_value(d).map_err(|e| e.to_string())?; + Ok(Dialog::new(PRESET_KIND, json!({ "name": new_name, "params": params, EDITING: editing, super::PARENT: under }))) +} + +fn preset_body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { + ui.horizontal(|ui| { + widgets::dim_label(ui, tl!("Name:")); + form::text(ui, d, "name", 240.0); + }); + ui.add_space(8.0); + let mut params = d.fields.get("params").cloned().filter(Value::is_object).unwrap_or_else(|| json!({})); + let changed = egui::ScrollArea::vertical() + .id_salt("tracing-preset-settings") + .max_height(SETTINGS_HEIGHT) + .show(ui, |ui| settings_editor(app, ui, "tracing-preset", &mut params)) + .inner; + if changed { + d.fields.insert("params".into(), params); + } + false +} + +/// Save Preset (the editor's OK): `imageTrace.presets.save`, then back to the manager on the +/// preset. A preset may not take the name of a built-in preset, of Custom or of another saved +/// preset: the editor stays open to change it. +fn confirm_preset(app: &mut VectorcraftApp, d: &Dialog) -> Result { + let (name, editing) = (d.str("name"), d.str(EDITING)); + let name = name.trim(); + let params = d.fields.get("params").cloned().unwrap_or(Value::Null); + let p = if editing.is_empty() { + if app.session.trace_preset(name).is_some() { + return Err(format!("a preset named `{name}` exists")); + } + // The settings are whole: a new preset starts from none of the saved ones. + json!({ "name": name, "preset": "Default", "params": params }) + } else { + json!({ "name": editing, "newName": name, "params": params }) + }; + let r = app.run("imageTrace.presets.save", p)?; + let mut back = super::parent(d).filter(|p| p.kind == KIND).unwrap_or_else(|| Dialog::new(KIND, json!({}))); + select(&mut back, r["name"].as_str().unwrap_or_default()); + app.ui.dialog = Some(back); + Ok(r) +} + +/// The tracing settings `params` as the Image Trace panel shows them (mode, palette, the count or +/// threshold, Document Library's library and colors, and the Advanced settings), changed by the user +/// → whether they changed. +fn settings_editor(app: &VectorcraftApp, ui: &mut egui::Ui, id: &str, params: &mut Value) -> bool { + let mut changed = false; + let mode = params["mode"].as_str().unwrap_or("blackAndWhite").to_string(); + ui.horizontal(|ui| { + widgets::dim_label(ui, tl!("Mode:")); + let label = MODES.iter().find(|m| m.0 == mode).map_or("Black and White", |m| m.1); + let labels: Vec<&str> = MODES.iter().map(|m| m.1).collect(); + if let Some(i) = widgets::dropdown(ui, (id, "mode"), label, &labels, 170.0) { + if MODES[i].0 != "color" { + params["colorGroup"] = Value::Null; + } + params["mode"] = json!(MODES[i].0); + changed = true; + } + }); + let palette = params["palette"].as_str().unwrap_or("limited").to_string(); + if mode == "color" { + ui.horizontal(|ui| { + widgets::dim_label(ui, tl!("Palette:")); + let labels = PALETTES.map(image_trace::palette_label); + if let Some(p) = + widgets::dropdown_names(ui, (id, "palette"), image_trace::palette_label(&palette), &labels, 170.0).and_then(|i| PALETTES.get(i)) + { + if *p != "documentLibrary" { + params["colorGroup"] = Value::Null; + } + params["palette"] = json!(p); + changed = true; + } + }); + if palette == "documentLibrary" { + let key = params["library"].as_str().unwrap_or(DOCUMENT_SWATCHES).to_string(); + ui.horizontal(|ui| { + widgets::dim_label(ui, tl!("Library:")); + let label = swatches::library_label(app, &key); + if let Some(k) = widgets::combo(ui, (id, "library"), &label, 170.0, |ui| swatches::library_list(app, ui, &key)) { + if k != DOCUMENT_SWATCHES { + params["colorGroup"] = Value::Null; + } + params["library"] = json!(k); + changed = true; + } + }); + // The document's swatches: every one, or one color group's (kept by name, so a preset + // names a group the open document may not have). + if key == DOCUMENT_SWATCHES { + ui.horizontal(|ui| { + widgets::dim_label(ui, tl!("Colors:")); + let group = params["colorGroup"].as_str().filter(|g| !g.is_empty()).map(str::to_string); + let label = group.clone().unwrap_or_else(|| tl!("All").to_string()); + if let Some(g) = + widgets::combo(ui, (id, "color-group"), &label, 170.0, |ui| image_trace::color_group_list(app, ui, group.as_deref())) + { + params["colorGroup"] = json!(g); + changed = true; + } + }); + } + } + } + let (key, label, range, suffix) = match mode.as_str() { + "blackAndWhite" => ("threshold", tl!("Threshold"), 0.0..=255.0, ""), + "grayscale" => ("colors", tl!("Grays"), 2.0..=256.0, ""), + "logo" => ("colors", tl!("Colors"), 2.0..=10.0, ""), + _ if matches!(palette.as_str(), "fullTone" | "automatic") => ("colorDetail", tl!("Colors"), 0.0..=100.0, "%"), + _ => ("colors", tl!("Colors"), 2.0..=256.0, ""), + }; + let mut slider = |params: &mut Value, key: &str, label: &str, range: std::ops::RangeInclusive, suffix: &str, whole: bool| { + let mut v = params[key].as_f64().unwrap_or(0.0); + if image_trace::slider(ui, label, &mut v, range, suffix).0 { + params[key] = if whole { json!(v.round() as u64) } else { json!(v.round()) }; + changed = true; + } + }; + slider(params, key, label, range, suffix, key != "colorDetail"); + for (key, label, range, suffix) in + [("paths", tl!("Paths"), 0.0..=100.0, "%"), ("corners", tl!("Corners"), 0.0..=100.0, "%"), ("noise", tl!("Noise"), 1.0..=100.0, " px")] + { + slider(params, key, label, range, suffix, key == "noise"); + } + if mode != "logo" { + ui.horizontal(|ui| { + widgets::dim_label(ui, tl!("Method:")); + for (m, l) in [("abutting", tl!("Abutting")), ("overlapping", tl!("Overlapping"))] { + if ui.selectable_label(params["method"] == m, l).clicked() && params["method"] != m { + params["method"] = json!(m); + changed = true; + } + } + }); + // Create: Fills and/or Strokes (one of them stays on), and the widest line stroked. + let create = |p: &Value, key: &str| p[key].as_bool().unwrap_or(key == "fills"); + ui.horizontal(|ui| { + widgets::dim_label(ui, tl!("Create:")); + for (key, other, label) in [("fills", "strokes", tl!("Fills")), ("strokes", "fills", tl!("Strokes"))] { + let on = create(params, key); + if widgets::check(ui, label, on, !on || create(params, other)) { + params[key] = json!(!on); + changed = true; + } + } + }); + let mut v = params["strokeWidth"].as_f64().unwrap_or(10.0); + let strokes = create(params, "strokes"); + if ui.add_enabled_ui(strokes, |ui| image_trace::slider(ui, tl!("Stroke"), &mut v, 1.0..=100.0, " px")).inner.0 { + params["strokeWidth"] = json!(v.round()); + changed = true; + } + } + let gradients = mode == "grayscale" || mode == "color"; + for (key, label, enabled) in [ + ("snapCurvesToLines", tl!("Snap Curves To Lines"), true), + ("shapes", tl!("Shapes"), true), + ("autoGrouping", tl!("Auto Grouping"), true), + ("gradients", tl!("Gradients"), gradients), + ] { + let on = params[key].as_bool().unwrap_or(false); + if widgets::check(ui, label, on, enabled) { + params[key] = json!(!on); + changed = true; + } + } + ui.horizontal(|ui| { + let on = params["ignoreWhite"].as_bool().unwrap_or(false); + if widgets::check(ui, tl!("Ignore Color"), on, true) { + params["ignoreWhite"] = json!(!on); + changed = true; + } + if on { + let mut rgb = image_trace::ignore_color(params); + if ui.color_edit_button_srgb(&mut rgb).changed() { + params["ignoreColor"] = json!(format!("#{:02x}{:02x}{:02x}", rgb[0], rgb[1], rgb[2])); + changed = true; + } + } + }); + changed +} + +#[cfg(test)] +mod tests; diff --git a/crates/ui-egui/src/dialogs/tracing_presets/tests.rs b/crates/ui-egui/src/dialogs/tracing_presets/tests.rs new file mode 100644 index 0000000000..7176efbbc8 --- /dev/null +++ b/crates/ui-egui/src/dialogs/tracing_presets/tests.rs @@ -0,0 +1,441 @@ +//! Edit → Tracing Presets: the menu item, New… and Edit… through the preset editor, Delete, +//! Import… (with the question about saved presets of the same names) and Export…. + +use serde_json::{Value, json}; +use vectorcraft_engine::Session; + +use super::*; + +fn frame(app: &mut VectorcraftApp) { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| super::super::show(app, ui.ctx())); + out.textures_delta.clear(); +} + +/// Press a manager button on the preset `current`, as the body does. +fn press(app: &mut VectorcraftApp, act: Action, current: &str) -> Result<(), String> { + let mut d = app.ui.dialog.take().expect("a dialog is open"); + let r = run(app, &mut d, act, current); + app.ui.dialog = Some(d); + frame(app); + r +} + +/// The texts the dialog paints on a 1200 × 900 window, once it has taken its sizing frame and +/// faded in (each frame is a quarter second on). +fn frame_texts(app: &mut VectorcraftApp) -> Vec { + fn walk(s: &egui::Shape, out: &mut Vec) { + match s { + egui::Shape::Text(t) => out.push(t.galley.text().to_string()), + egui::Shape::Vec(v) => v.iter().for_each(|s| walk(s, out)), + _ => {} + } + } + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 900.0)); + let mut texts = vec![]; + for k in 0..4 { + let raw = egui::RawInput { screen_rect: Some(screen), time: Some(f64::from(k) * 0.25), ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| super::super::show(app, ui.ctx())); + out.textures_delta.clear(); + texts.clear(); + out.shapes.iter().for_each(|c| walk(&c.shape, &mut texts)); + } + texts +} + +fn kind(app: &VectorcraftApp) -> Option<&str> { + app.ui.dialog.as_ref().map(|d| d.kind.as_str()) +} + +fn field(app: &VectorcraftApp, k: &str) -> Value { + app.ui.dialog.as_ref().and_then(|d| d.fields.get(k).cloned()).unwrap_or_default() +} + +fn set(app: &mut VectorcraftApp, k: &str, v: Value) { + app.ui.dialog.as_mut().expect("a dialog is open").fields.insert(k.into(), v); +} + +/// The tracing settings of the preset `name` as `imageTrace.presets` lists them. +fn listed(app: &mut VectorcraftApp, name: &str) -> Value { + let all = app.session.execute("imageTrace.presets", &json!({})).unwrap(); + all["presets"].as_array().unwrap().iter().find(|p| p["name"] == name).map(|p| p["params"].clone()).unwrap_or_default() +} + +fn saved_names(app: &VectorcraftApp) -> Vec<&str> { + app.session.prefs.trace_presets.iter().map(|p| p.name.as_str()).collect() +} + +#[test] +fn edit_menu_opens_the_manager_without_a_document() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let entries = crate::menus::menu_entries(&app); + let item = entries.iter().find(|e| e.command.as_deref() == Some("ui.tracingPresetsDialog")).expect("Edit → Tracing Presets…"); + assert!(item.path == ["Edit"] && item.label == "Tracing Presets…" && item.enabled); + app.run("ui.tracingPresetsDialog", json!({})).unwrap(); + frame(&mut app); + assert_eq!((kind(&app), field(&app, "selected")), (Some(KIND), json!("Default"))); + app.run("ui.tracingPresetsDialog", json!({"selected": "[6 Colors]"})).unwrap(); + frame(&mut app); + assert_eq!(field(&app, "selected"), json!("[6 Colors]")); + // Built-in presets can't be edited or deleted. + assert!(press(&mut app, Action::Edit, "6 Colors").is_err()); + assert!(press(&mut app, Action::Delete, "6 Colors").is_err()); + assert!(app.session.prefs.trace_presets.is_empty()); + super::super::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none(), "Close"); +} + +#[test] +fn new_and_edit_save_through_the_editor_and_cancel_saves_nothing() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let revision = app.session.trace_presets_revision(); + app.run("ui.tracingPresetsDialog", json!({"selected": "6 Colors"})).unwrap(); + frame(&mut app); + // New… starts from the selected built-in preset; Cancel comes back with nothing saved. + press(&mut app, Action::New, "6 Colors").unwrap(); + assert_eq!((kind(&app), field(&app, "name")), (Some(PRESET_KIND), json!("Tracing Preset 1"))); + let six = listed(&mut app, "6 Colors"); + assert_eq!(field(&app, "params"), six); + set(&mut app, "name", json!("Poster")); + super::super::cancel(&mut app); + assert_eq!((kind(&app), field(&app, "selected")), (Some(KIND), json!("6 Colors")), "back to the manager"); + assert!(app.session.prefs.trace_presets.is_empty()); + assert_eq!(app.session.trace_presets_revision(), revision); + // OK saves the preset with the editor's settings and selects it. + press(&mut app, Action::New, "6 Colors").unwrap(); + set(&mut app, "name", json!(" Poster ")); + let mut params = field(&app, "params"); + params["noise"] = json!(40); + set(&mut app, "params", params); + frame(&mut app); + super::super::confirm(&mut app).unwrap(); + assert_eq!((kind(&app), field(&app, "selected")), (Some(KIND), json!("Poster"))); + assert_eq!(saved_names(&app), ["Poster"]); + let poster = listed(&mut app, "Poster"); + assert_eq!((poster["noise"].clone(), poster["colors"].clone()), (json!(40), six["colors"].clone())); + // The Image Trace panel's list (also the Control bar's and Properties') has it. + let ctx = egui::Context::default(); + let all = crate::panels::image_trace::presets(&mut app, &ctx); + assert!(all.iter().any(|p| p.0 == "Poster" && !p.3)); + // Edit… changes the saved preset; Cancel leaves it as it was. + frame(&mut app); + press(&mut app, Action::Edit, "Poster").unwrap(); + assert_eq!((kind(&app), field(&app, "name"), field(&app, "params")), (Some(PRESET_KIND), json!("Poster"), poster.clone())); + let mut params = field(&app, "params"); + params["noise"] = json!(3); + set(&mut app, "params", params); + super::super::cancel(&mut app); + assert_eq!(listed(&mut app, "Poster"), poster); + press(&mut app, Action::Edit, "Poster").unwrap(); + let mut params = field(&app, "params"); + params["noise"] = json!(3); + params["mode"] = json!("grayscale"); + set(&mut app, "params", params); + set(&mut app, "name", json!("Posters")); + frame(&mut app); + super::super::confirm(&mut app).unwrap(); + assert_eq!((kind(&app), field(&app, "selected")), (Some(KIND), json!("Posters"))); + assert_eq!(saved_names(&app), ["Posters"]); + let edited = listed(&mut app, "Posters"); + assert_eq!((edited["noise"].clone(), edited["mode"].clone()), (json!(3), json!("grayscale"))); + // New… from a saved preset starts from its settings. + press(&mut app, Action::New, "Posters").unwrap(); + assert_eq!((field(&app, "name"), field(&app, "params")), (json!("Tracing Preset 1"), edited)); +} + +#[test] +fn the_editor_shows_document_library_s_library_and_colors() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("ui.tracingPresetsDialog", json!({})).unwrap(); + frame(&mut app); + press(&mut app, Action::New, "Default").unwrap(); + let mut params = field(&app, "params"); + params["mode"] = json!("color"); + params["palette"] = json!("documentLibrary"); + params["colorGroup"] = json!("Brand Colors"); + set(&mut app, "params", params.clone()); + let texts = frame_texts(&mut app); + for t in ["Library:", "Colors:", "Brand Colors"] { + assert!(texts.iter().any(|s| s == t), "{t}: {texts:?}"); + } + // Another library's colors are all its swatches: no Colors menu. + params["library"] = json!("lib:Other"); + params["colorGroup"] = Value::Null; + set(&mut app, "params", params.clone()); + let texts = frame_texts(&mut app); + assert!(texts.iter().any(|s| s == "Library:") && !texts.iter().any(|s| s == "Colors:"), "{texts:?}"); + // Other palettes show neither. + params["palette"] = json!("limited"); + set(&mut app, "params", params); + let texts = frame_texts(&mut app); + assert!(!texts.iter().any(|s| s == "Library:" || s == "Colors:"), "{texts:?}"); +} + +#[test] +fn a_taken_or_protected_name_keeps_the_editor_open() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("imageTrace.presets.save", json!({"name": "Ink", "params": {"threshold": 90}})).unwrap(); + app.run("imageTrace.presets.save", json!({"name": "Poster", "params": {"noise": 40}})).unwrap(); + let saved = app.session.prefs.trace_presets.clone(); + app.run("ui.tracingPresetsDialog", json!({"selected": "Ink"})).unwrap(); + frame(&mut app); + press(&mut app, Action::New, "Ink").unwrap(); + for name in ["Default", "[6 Colors]", "custom", "poster"] { + set(&mut app, "name", json!(name)); + assert!(super::super::confirm(&mut app).is_err(), "{name}"); + assert_eq!((kind(&app), field(&app, "name")), (Some(PRESET_KIND), json!(name)), "{name}: stays open"); + } + super::super::cancel(&mut app); + press(&mut app, Action::Edit, "Ink").unwrap(); + for name in ["Poster", "Default", "Custom"] { + set(&mut app, "name", json!(name)); + assert!(super::super::confirm(&mut app).is_err(), "{name}"); + assert_eq!(kind(&app), Some(PRESET_KIND), "{name}: stays open"); + } + assert_eq!(app.session.prefs.trace_presets, saved, "nothing changed"); +} + +#[test] +fn delete_selects_the_next_saved_preset_then_default() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + for name in ["A", "B", "C"] { + app.run("imageTrace.presets.save", json!({ "name": name })).unwrap(); + } + app.run("ui.tracingPresetsDialog", json!({"selected": "B"})).unwrap(); + frame(&mut app); + press(&mut app, Action::Delete, "B").unwrap(); + assert_eq!((saved_names(&app), field(&app, "selected")), (vec!["A", "C"], json!("C"))); + press(&mut app, Action::Delete, "C").unwrap(); + assert_eq!((saved_names(&app), field(&app, "selected")), (vec!["A"], json!("A"))); + press(&mut app, Action::Delete, "A").unwrap(); + assert!(app.session.prefs.trace_presets.is_empty()); + assert_eq!(field(&app, "selected"), json!("Default")); +} + +#[test] +fn import_asks_before_replacing_saved_presets_and_export_writes_every_saved_one() { + let dir = std::env::temp_dir().join(format!("vc-tracing-presets-ui-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let file = dir.join("mine.vctracepresets").to_string_lossy().to_string(); + let picked = file.clone(); + let services = crate::Services { + pick_save: Some(Box::new(move |_: &crate::FilePick| Some(picked.clone()))), + write: Some(Box::new(|p: &str, b: &[u8]| std::fs::write(p, b).map_err(|e| e.to_string()))), + read: Some(Box::new(|p: &str| std::fs::read(p).map_err(|e| e.to_string()))), + ..Default::default() + }; + let mut app = VectorcraftApp::new(Session::new(), services); + app.run("imageTrace.presets.save", json!({"name": "Poster", "params": {"noise": 40}})).unwrap(); + app.run("imageTrace.presets.save", json!({"name": "Ink", "params": {"threshold": 90}})).unwrap(); + app.run("ui.tracingPresetsDialog", json!({"selected": "Default"})).unwrap(); + frame(&mut app); + press(&mut app, Action::Export, "").unwrap(); + let text = std::fs::read_to_string(&file).unwrap(); + let written: Value = serde_json::from_str(&text).unwrap(); + let names: Vec<&str> = written["presets"].as_array().unwrap().iter().filter_map(|p| p["name"].as_str()).collect(); + assert_eq!((written["format"].as_str(), names), (Some(TRACE_PRESET_FORMAT), vec!["Poster", "Ink"])); + // Saved presets of the same names stay unless the question's Replace is pressed. + app.run("imageTrace.presets.save", json!({"name": "Poster", "params": {"noise": 7}})).unwrap(); + app.run("imageTrace.presets.delete", json!({"name": "Ink"})).unwrap(); + let mut d = app.ui.dialog.take().unwrap(); + import(&mut app, &mut d, json!({ "path": file })).unwrap(); + app.ui.dialog = Some(d); + frame(&mut app); + assert_eq!((kind(&app), field(&app, "names")), (Some(REPLACE_KIND), json!(["Poster"]))); + assert_eq!(saved_names(&app), ["Poster", "Ink"], "Ink came in"); + super::super::cancel(&mut app); + assert_eq!((kind(&app), field(&app, "selected")), (Some(KIND), json!("Ink")), "Cancel keeps the saved one"); + assert_eq!(app.session.trace_preset("Poster").unwrap().params.noise, 7); + let mut d = app.ui.dialog.take().unwrap(); + import(&mut app, &mut d, json!({ "path": file })).unwrap(); + app.ui.dialog = Some(d); + // Replace acts on the contents the question was asked about, though the file changed since. + let changed = + r#"{"format": "vctracepresets", "version": 1, "presets": [{"name": "Poster", "params": {"noise": 3}}, {"name": "Extra", "params": {}}]}"#; + std::fs::write(&file, changed).unwrap(); + super::super::confirm(&mut app).unwrap(); + std::fs::write(&file, &text).unwrap(); + assert_eq!((kind(&app), field(&app, "selected")), (Some(KIND), json!("Poster"))); + assert_eq!(app.session.trace_preset("Poster").unwrap().params.noise, 40); + assert_eq!(saved_names(&app), ["Poster", "Ink"]); + // Opening the file imports it, and asks the same question over the manager (also how the web's + // picked file arrives). + app.run("imageTrace.presets.save", json!({"name": "Poster", "params": {"noise": 7}})).unwrap(); + app.run("imageTrace.presets.delete", json!({"name": "Ink"})).unwrap(); + let bytes = std::fs::read(&file).unwrap(); + crate::io::open_bytes(&mut app, &file, &bytes, Some(file.clone())).unwrap(); + assert_eq!(saved_names(&app), ["Poster", "Ink"]); + assert!(app.ui.status.contains("tracing presets"), "{}", app.ui.status); + assert_eq!((kind(&app), field(&app, "names")), (Some(REPLACE_KIND), json!(["Poster"]))); + frame(&mut app); + super::super::confirm(&mut app).unwrap(); + assert_eq!((kind(&app), field(&app, "selected")), (Some(KIND), json!("Poster"))); + assert_eq!(app.session.trace_preset("Poster").unwrap().params.noise, 40); + // With no dialog open, Cancel keeps the saved preset and leaves no dialog. + app.ui.dialog = None; + app.run("imageTrace.presets.save", json!({"name": "Poster", "params": {"noise": 7}})).unwrap(); + crate::io::open_bytes(&mut app, &file, &bytes, Some(file.clone())).unwrap(); + assert_eq!(kind(&app), Some(REPLACE_KIND)); + super::super::cancel(&mut app); + assert!(app.ui.dialog.is_none()); + assert_eq!(app.session.trace_preset("Poster").unwrap().params.noise, 7); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn a_file_with_a_fault_changes_nothing() { + let dir = std::env::temp_dir().join(format!("vc-tracing-presets-bad-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let file = dir.join("bad.vctracepresets"); + std::fs::write( + &file, + r#"{"format": "vctracepresets", "version": 1, "presets": [{"name": "Fine", "params": {}}, {"name": "Default", "params": {}}]}"#, + ) + .unwrap(); + // The file is read no further than one byte past the limit. + let read_head = |p: &str, max: usize| { + use std::io::Read as _; + assert_eq!(max, TRACE_PRESET_MAX_BYTES + 1); + let mut bytes = vec![]; + std::fs::File::open(p).and_then(|f| f.take(max as u64).read_to_end(&mut bytes)).map_err(|e| e.to_string())?; + Ok(bytes) + }; + let services = crate::Services { read_head: Some(Box::new(read_head)), ..Default::default() }; + let mut app = VectorcraftApp::new(Session::new(), services); + app.run("ui.tracingPresetsDialog", json!({})).unwrap(); + frame(&mut app); + let mut d = app.ui.dialog.take().unwrap(); + let e = import(&mut app, &mut d, json!({ "path": file.to_string_lossy() })).unwrap_err(); + assert!(e.contains("built-in preset"), "{e}"); + assert_eq!(d.kind, KIND, "no question"); + assert!(app.session.prefs.trace_presets.is_empty()); + app.ui.dialog = Some(d); + // An opened file over the size limit is refused before its bytes are encoded for the import. + let big = vec![b' '; TRACE_PRESET_MAX_BYTES + 1]; + let e = open_file(&mut app, &big).unwrap_err(); + assert!(e.contains("tracing presets file is larger than 4 MiB"), "{e}"); + assert_eq!(kind(&app), Some(KIND), "the manager stays open"); + let big_file = dir.join("big.vctracepresets"); + std::fs::write(&big_file, &big).unwrap(); + let mut d = app.ui.dialog.take().unwrap(); + let e = import(&mut app, &mut d, json!({ "path": big_file.to_string_lossy() })).unwrap_err(); + assert!(e.contains("tracing presets file is larger than 4 MiB"), "{e}"); + app.ui.dialog = Some(d); + assert!(app.session.prefs.trace_presets.is_empty()); + let _ = std::fs::remove_dir_all(dir); +} + +/// File › Open reads a tracing presets file no further than one byte past the size limit, and +/// refuses a larger one, without the whole-file reader. +#[test] +fn an_opened_file_is_read_no_further_than_the_limit() { + let dir = std::env::temp_dir().join(format!("vc-tracing-presets-open-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let fine = dir.join("fine.vctracepresets"); + std::fs::write(&fine, r#"{"format": "vctracepresets", "version": 1, "presets": [{"name": "Fine", "params": {}}]}"#).unwrap(); + let big = dir.join("big.vctracepresets"); + std::fs::write(&big, vec![b' '; TRACE_PRESET_MAX_BYTES + 1]).unwrap(); + let read_head = |p: &str, max: usize| { + use std::io::Read as _; + assert_eq!(max, TRACE_PRESET_MAX_BYTES + 1); + let mut bytes = vec![]; + std::fs::File::open(p).and_then(|f| f.take(max as u64).read_to_end(&mut bytes)).map_err(|e| e.to_string())?; + Ok(bytes) + }; + let read = |p: &str| -> Result, String> { Err(format!("`{p}` was read in full")) }; + let services = crate::Services { read_head: Some(Box::new(read_head)), read: Some(Box::new(read)), ..Default::default() }; + let mut app = VectorcraftApp::new(Session::new(), services); + crate::io::open_path(&mut app, &fine.to_string_lossy()).unwrap(); + assert_eq!(saved_names(&app), ["Fine"]); + let e = crate::io::open_path(&mut app, &big.to_string_lossy()).unwrap_err(); + assert!(e.contains("tracing presets file is larger than 4 MiB"), "{e}"); + assert_eq!(saved_names(&app), ["Fine"]); + let _ = std::fs::remove_dir_all(dir); +} + +/// The question's list of names scrolls, so a long one keeps Replace and Cancel on a small screen. +#[test] +fn a_long_list_of_names_keeps_replace_on_screen() { + fn walk(s: &egui::Shape, out: &mut Vec<(String, egui::Rect)>) { + match s { + egui::Shape::Text(t) => out.push((t.galley.text().to_string(), t.visual_bounding_rect())), + egui::Shape::Vec(v) => v.iter().for_each(|s| walk(s, out)), + _ => {} + } + } + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let names: Vec = (0..200).map(|i| json!(format!("Tracing Preset {i}"))).collect(); + app.ui.dialog = Some(ask_replace(None, names, json!({ "dataBase64": "" }))); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1000.0, 600.0)); + let mut texts = vec![]; + for k in 0..6 { + let raw = egui::RawInput { screen_rect: Some(screen), time: Some(f64::from(k) * 0.25), ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| super::super::show(&mut app, ui.ctx())); + out.textures_delta.clear(); + texts.clear(); + out.shapes.iter().for_each(|c| walk(&c.shape, &mut texts)); + } + for button in ["Replace", "Cancel"] { + let rect = texts.iter().find(|(t, _)| t == button).map(|(_, r)| *r); + assert!(rect.is_some_and(|r| screen.contains_rect(r)), "{button} is drawn on screen: {rect:?}"); + } +} + +/// The tracing settings scroll past the height of the preset list, in the manager and in the +/// editor: a preset with every row shown (Color, Document Library, Ignore Color) makes neither +/// dialog taller than a Black and White one does. +#[test] +fn tall_settings_scroll_instead_of_growing_the_dialog() { + fn walk(s: &egui::Shape, out: &mut Vec<(String, egui::Rect)>) { + match s { + egui::Shape::Text(t) => out.push((t.galley.text().to_string(), t.visual_bounding_rect())), + egui::Shape::Vec(v) => v.iter().for_each(|s| walk(s, out)), + _ => {} + } + } + /// The height from the dialog's heading to the bottom of its button `button`. + fn height(app: &mut VectorcraftApp, heading: &str, button: &str) -> f32 { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 2000.0)); + let mut texts = vec![]; + for k in 0..6 { + let raw = egui::RawInput { screen_rect: Some(screen), time: Some(f64::from(k) * 0.25), ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| super::super::show(app, ui.ctx())); + out.textures_delta.clear(); + texts.clear(); + out.shapes.iter().for_each(|c| walk(&c.shape, &mut texts)); + } + let at = |t: &str| texts.iter().find(|(s, _)| s == t).map(|(_, r)| *r).unwrap_or_else(|| panic!("{t}: {texts:?}")); + at(button).max.y - at(heading).min.y + } + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let short = listed(&mut app, "Default"); + let mut tall = short.clone(); + tall["mode"] = json!("color"); + tall["palette"] = json!("documentLibrary"); + tall["colorGroup"] = json!("Brand Colors"); + tall["ignoreWhite"] = json!(true); + for (name, params) in [("Short", &short), ("Tall", &tall)] { + app.run("imageTrace.presets.save", json!({ "name": name, "preset": "Default", "params": params })).unwrap(); + } + app.run("ui.tracingPresetsDialog", json!({})).unwrap(); + let mut heights = vec![]; + for name in ["Short", "Tall"] { + set(&mut app, "selected", json!(name)); + let manager = height(&mut app, "Tracing Presets", "Close"); + press(&mut app, Action::Edit, name).unwrap(); + assert_eq!(kind(&app), Some(PRESET_KIND)); + let editor = height(&mut app, "Save Preset", "OK"); + app.ui.dialog = super::super::parent(app.ui.dialog.as_ref().unwrap()); + heights.push((manager, editor)); + } + let [(manager, editor), (tall_manager, tall_editor)] = heights[..] else { panic!("{heights:?}") }; + assert!(tall_manager <= manager + 0.5, "the manager grows from {manager} to {tall_manager}"); + assert!(tall_editor <= editor + 0.5, "the editor grows from {editor} to {tall_editor}"); +} diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index b31a839139..1ffb352a36 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -489,6 +489,10 @@ font-technology Variable Променливи Circle Кръг Circle Tool Инструмент Кръг Circle too large Кръгът е твърде голям + Show Radii Показване на радиуси + Show Diameter Показване на диаметър + Anchors at Standard Positions Опорни точки в стандартни позиции + Third Point by Dragging Трета точка чрез плъзгане Classic Defaults Класически по подразбиране Clean Up… Почистване… Clear Изчистване @@ -586,9 +590,14 @@ font-technology Variable Променливи {name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2} Wheel View Изглед „Колело“ Box View Изглед „Квадрат“ + Show Out-of-Gamut Colors Показване на цветовете извън цветовата гама Box Channel Канал на квадрата Color box Цветови квадрат Color Wheel Options Опции на цветното колело + Show Document Colors Показване на цветовете на документа + Document Colors Цветове на документа + Selection Colors Цветове на селекцията +@plural Used {n} time|Used {n} times Използван {n} път|Използван {n} пъти Show Harmony Показване на хармонията Harmony Rule Правило за хармония Harmony color Цвят от хармонията @@ -632,6 +641,8 @@ font-technology Variable Променливи Contextual Task Bar Контекстна лента със задачи Pin Bar Position Закачане на позицията на лентата Reset Bar Position Нулиране на позицията на лентата + Bar Actions Действия на лентата + Reset Bar Actions Нулиране на действията на лентата Resize Преоразмеряване Contrast Контраст Control Контрол @@ -1828,6 +1839,10 @@ font-technology Variable Променливи Rename Preset Преименуване на предварителна настройка Save Image Trace Preset Запази предварителна настройка за трасиране на изображения Delete Image Trace Preset Изтриване на предварителна настройка за трасиране на изображения + Tracing Presets… Предварителни настройки за трасиране… + Import Image Trace Presets Импортиране на предварителни настройки за трасиране на изображения + Export Image Trace Presets Експортиране на предварителни настройки за трасиране на изображения + Replace the saved presets that have these names? Да се заменят ли запазените предварителни настройки с тези имена? Image Trace Presets Предварителни настройки за трасиране на изображения Image: Изображение: Images: Изображения: @@ -1958,6 +1973,11 @@ font-technology Variable Променливи Knife Нож Knockout Group Група с изрязване Lab Lab + OKLCH Sliders Плъзгачи OKLCH + HSL Sliders Плъзгачи HSL + Chroma Хрома + The largest chroma sRGB holds at this lightness and hue Най-голямата хрома, която sRGB побира при тази светлина и този оттенък + OKLCH needs sRGB as the working RGB space OKLCH изисква sRGB като работно RGB пространство Lab Spot Colors: Спот цветове по Lab: Lab Values Стойности по Lab Landscape Пейзаж @@ -2694,6 +2714,13 @@ font-technology Variable Променливи Pen Tool Инструмент „Перо“ Quick Pen Tool Инструмент „Бързо перо“ Quick Pen Бързо перо + Quick Pen Toolbar Лента на бързото перо + Continuous Arc Непрекъсната дъга + Sharp Corner Arc Дъга с остър ъгъл + Flip Arc Обръщане на дъгата + Hide Toolbar Скриване на лентата с инструменти + Pin Toolbar Position Закачане на позицията на лентата с инструменти + Reset Toolbar Position Нулиране на позицията на лентата с инструменти Pencil Молив Pencil Tool Инструмент „Молив“ per slice на отрязък @@ -3134,6 +3161,11 @@ digits Malayalam Малаялам Edit Arrowheads Редактиране на върхове на стрелки Edit Arrowheads… Редактиране на върхове на стрелки… Reload Arrowheads Презареждане на върхове на стрелки + Bevels Фаски + Edit Bevels Редактиране на фаски + Edit Bevels… Редактиране на фаски… + {name} (document) {name} (документ) + Reload Bevels Презареждане на фаски Reset Rotate View Нулиране на изгледа на завъртане Rotate View to Selection Завъртане на изгледа спрямо селекцията Reset the rows to the artwork's colors Нулиране на редовете към цветовете на илюстрацията @@ -3271,9 +3303,14 @@ digits Malayalam Малаялам Edit type set in fonts that aren't available? Да се редактира ли текст с шрифтове, които не са налични? Shows each slice's number in a box at its top left on the canvas; off, the slice outlines still show. Показва номера на всяка отрязана част в каре в горния ѝ ляв ъгъл върху платното; когато е изключено, контурите на отрязаните части остават видими. The color of user and object slice outlines and their number boxes; auto slices use a dimmer shade of it. Цветът на контурите на потребителските и обектните отрязани части и на каретата с номерата им; автоматичните отрязани части използват по-блед нюанс на този цвят. + New type takes this language while Document Setup's language is English: USA and [Normal Character Style] sets none; type already in a document keeps its own language. Новият текст получава този език, докато езикът в Настройка на документ е Английски: САЩ и [Нормален стил на знак] не задава език; текстът, който вече е в документа, запазва своя език. + In paragraphs with Hyphenate on, a listed word is hyphenated only at the hyphens typed in it, or never when it has none, whatever its language or case. В абзаците с включено Пренасяне на думи изброената дума получава пренос само при въведените в нея тирета или никога, ако няма такива, независимо от езика и регистъра ѝ. + On the desktop, this folder's .wasm plug-ins load at startup and when OK sets a new folder, except in Safe Mode; one that asks for permissions loads only after you grant them. The web version loads none. В настолната версия .wasm приставките от тази папка се зареждат при стартиране и когато ОК зададе нова папка, освен в Безопасен режим; приставка, която иска разрешения, се зарежда едва след като ги дадете. Уеб версията не зарежда нито една. + Large gives each filter or command plug-in run at least 250 million instructions, with the same time limit; Normal keeps the plug-in's own budget. Live effects, exporters and importers keep theirs. Голям дава на всяко изпълнение на приставка за филтър или команда поне 250 милиона инструкции при същия лимит на време; Нормално запазва собствения бюджет на приставката. Живите ефекти, експортерите и импортерите запазват своя. New type takes this language while Document Setup's language is English: USA; type already in a document keeps its own language. Новият текст получава този език, докато езикът в Настройка на документ е Английски: САЩ; текстът, който вече е в документа, запазва своя език. In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its language or case. В абзаците с включено Пренасяне на думи изброената дума се пренася само при въведените в нея тирета или никъде, ако няма такива, независимо от езика и регистъра ѝ. On the desktop, the .wasm plug-ins in this folder load at startup and when you click OK with a new folder here, except in Safe Mode; the web version does not load them. В настолната версия .wasm приставките в тази папка се зареждат при стартиране и когато щракнете върху ОК с нова папка тук, освен в Безопасен режим; уеб версията не ги зарежда. + Normal keeps each plug-in's own limits; with Large, a plug-in filter or command may run at least 250 million instructions besides those for its input. The time limit stays the same. „Нормално“ запазва собствените ограничения на всеки плъгин; с „Голям“ филтър или команда на плъгин може да изпълни поне 250 милиона инструкции освен тези за входните си данни. Ограничението по време остава същото. How many instructions each run of a plug-in object filter may use; Large allows more than Normal with the same 60-second limit. Heavy filters keep their own budget. Колко инструкции може да използва всяко изпълнение на филтър за обекти от плъгин; „Голям“ позволява повече от „Нормално“ при същия лимит от 60 секунди. Тежките филтри запазват своя бюджет. The first scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. Първият избор на временен диск: Startup, None или път до папка; VectorCraft го запазва, но все още не използва временни дискове. The second scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. Вторият избор на временен диск: Startup, None или път до папка; VectorCraft го запазва, но все още не използва временни дискове. @@ -3285,13 +3322,15 @@ digits Malayalam Малаялам Shows each tool group's name above its tools in the toolbar; off, the groups follow one another with nothing between them. Показва името на всяка група инструменти над инструментите ѝ в лентата с инструменти; изключено, групите следват една след друга без нищо между тях. From now on, documents you open or create open as tabs; off, each opens in a floating window. Documents already open stay where they are. Отсега нататък документите, които отваряте или създавате, се отварят като подпрозорци; изключено, всеки се отваря в плаващ прозорец. Вече отворените документи остават на мястото си. Makes the document tabs taller and their names larger. Прави подпрозорците на документите по-високи, а имената им по-големи. - From the next start, the system draws the window's title bar where VectorCraft would otherwise draw its own. От следващото стартиране системата изчертава заглавната лента на прозореца там, където иначе VectorCraft би изчертал своя. - From the next start, VectorCraft draws the window's title bar even where the desktop would draw it, unless System Title Bar is on. От следващото стартиране VectorCraft изчертава заглавната лента на прозореца дори там, където работният плот би я изчертал, освен ако Заглавна лента на системата е включена. + From the next start, the system draws the window's title bar where VectorCraft would otherwise draw its own; on Linux and the BSDs, the VECTORCRAFT_TITLEBAR variable takes precedence. От следващото стартиране системата изчертава заглавната лента на прозореца там, където иначе VectorCraft би изчертал своя; в Linux и BSD системите променливата VECTORCRAFT_TITLEBAR има предимство. + From the next start, VectorCraft draws the window's title bar even where the desktop would draw it, unless System Title Bar is on or the VECTORCRAFT_TITLEBAR variable chooses it. От следващото стартиране VectorCraft изчертава заглавната лента на прозореца дори там, където работният плот би я изчертал, освен ако Заглавна лента на системата е включена или променливата VECTORCRAFT_TITLEBAR я избира. Makes the interface larger or smaller; art on the canvas keeps its size at the same zoom. Уголемява или смалява интерфейса; рисунката в платното запазва размера си при същия мащаб. The tool pointers VectorCraft draws grow and shrink with UI Scaling; off, they keep their size. Показалците на инструментите, които VectorCraft изчертава, растат и се смаляват с Мащабиране на потребителския интерфейс; изключено, запазват размера си. The language of the interface; Auto uses the system's language. The dialog switches language as soon as you choose one. Езикът на интерфейса; Автоматично използва езика на системата. Диалоговият прозорец сменя езика веднага щом изберете някой. Animated Zoom works only while this is on; off, Animated Zoom is dimmed and zooming does not animate. „Анимирано мащабиране“ работи само докато това е включено; изключено, „Анимирано мащабиране“ е затъмнено и мащабирането не е анимирано. The wheel's zoom glides in, and the Zoom tool zooms as you drag sideways or hold it down; off, the Zoom tool zooms to the area you drag across. Мащабирането с колелцето се плъзга плавно, а инструментът „Мащаб“ мащабира, докато плъзгате настрани или го задържите; изключено, той мащабира до областта, през която плъзнете. + From the next start, the desktop version shows the canvas through this kind of graphics processor; the artwork is drawn on the CPU either way. Automatic prefers the integrated one on Windows and macOS. The web version does not use it. От следващото стартиране настолната версия показва платното чрез този вид графичен процесор; графиката винаги се рисува от централния процесор. „Автоматично“ предпочита интегрирания под Windows и macOS. Уеб версията не го използва. + From the next start, the window shows each frame without waiting for the display's refresh where the graphics driver allows, at most 240 frames a second. От следващото стартиране прозорецът показва всеки кадър, без да чака опресняването на дисплея, където графичният драйвер позволява, най-много 240 кадъра в секунда. From the next start, the desktop version draws with this kind of graphics processor; Automatic prefers the one that drives the display. The web version does not use it. От следващото стартиране настолната версия рисува с този вид графичен процесор; „Автоматично“ предпочита този, който управлява дисплея. Уеб версията не го използва. From the next start, the window shows frames without waiting for the display to refresh, at most 240 a second; off, the display paces them. A present mode set at launch overrides it. От следващото стартиране прозорецът показва кадрите, без да чака опресняването на дисплея, най-много 240 в секунда; изключено, темпото задава дисплеят. Режим на представяне, зададен при стартиране, има предимство. The most undo steps each document keeps; lowering it drops the oldest steps when you click OK. Steps can also go sooner when they use too much memory. Най-многото стъпки за отмяна, които всеки документ пази; по-малко число премахва най-старите стъпки, когато щракнете върху ОК. Стъпки може да отпаднат и по-рано, ако заемат твърде много памет. @@ -3310,6 +3349,9 @@ digits Malayalam Малаялам Open Recent Files and the Home screen list at most this many recent files; 0 lists none, and VectorCraft still remembers up to 30. „Скорошни файлове“ и екранът „Начало“ показват най-много толкова скорошни файла; 0 не показва нито един, а VectorCraft пак помни до 30. When a document opens, a linked EPS image that shows its saved preview keeps it instead of reading the EPS file again; changed files still follow Update Links. При отваряне на документ свързано EPS изображение, което показва запазения си преглед, го запазва, вместо да чете EPS файла отново; променените файлове пак следват „Актуализиране на връзките“. In Pixel Preview, images are drawn smoothed; off, their pixels show with hard edges. Outside Pixel Preview, images are always smoothed. В „Пикселен преглед“ изображенията се рисуват изгладени; изключено, пикселите им имат остри ръбове. Извън „Пикселен преглед“ изображенията винаги се изглаждат. + PDF Text Текст на PDF + The text of a PDF you open or embed comes in as editable type, or as outlines that look the same on a computer without its fonts. Текстът на PDF, който отваряте или вграждате, идва като редактируем текст или като контури, които изглеждат същите на компютър без шрифтовете му. + Linked pages show the file's own text. Свързаните страници показват собствения текст на файла. When a linked file changes, Automatically reads it again, Ask When Modified asks you first, and Manually leaves it and shows a note in the status bar. Когато свързан файл се промени, „Автоматично“ го прочита отново, „Питане при промяна“ първо ви пита, а „Ръчно“ го оставя както е и показва бележка в лентата на състоянието. On the desktop, the folder New from Template… and Save as Template… start in; leave it blank for VectorCraft Templates in your documents folder. В настолната версия папката, в която започват „Нов от шаблон…“ и „Запази като шаблон…“; оставете я празна за VectorCraft Templates в папката ви с документи. Edit Original opens a linked file in the system's default app for its type; off, a linked raster image opens in PhotoCraft where it is installed. „Редактиране на оригинал“ отваря свързан файл в стандартното приложение на системата за неговия тип; изключено, свързано растерно изображение се отваря в PhotoCraft, ако е инсталиран. @@ -3324,7 +3366,6 @@ digits Malayalam Малаялам Output All Blacks as Rich Black draws pure CMYK black as RGB black in RGB and grayscale raster exports and Print as Bitmap; it does not change vector exports, CMYK JPEG, TIFF and PSD, or other printing. „Изход на чисто черно като наситено черно“ рисува чистото CMYK черно като RGB черно в растерните RGB и черно-бели експорти и при „Печат като растерно изображение“; не променя векторните експорти, CMYK JPEG, TIFF и PSD и другия печат. On a touch screen, switches to the Touch workspace; turning this off, or losing the touch screen, goes back to the workspace it switched from. На сензорен екран превключва към работното пространство за докосване; изключването на настройката или изчезването на сензорния екран връща работното пространство отпреди това. A two-finger tap on the canvas undoes, or switches between selection and drawing tools in the Touch workspace, and a three-finger tap redoes; neither works in Presentation Mode. Докосване с два пръста върху платното отменя, а в работното пространство за докосване превключва между инструментите за селекция и за рисуване; докосване с три пръста повтаря. Нито едното не действа в режим на презентация. - New type takes this language while Document Setup's language is English: USA and [Normal Character Style] sets none; type already in a document keeps its own language. Новият текст получава този език, докато езикът в Настройка на документ е Английски: САЩ и [Нормален стил на знак] не задава език; текстът, който вече е в документа, запазва своя език. In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its case; Korean words take no hyphen, and Indian-language words do not break inside a character cluster. В абзаците с включено Пренасяне на думи изброената дума се пренася само при въведените в нея тирета или никъде, ако няма такива, независимо от регистъра ѝ; корейските думи не получават тире, а думите на индийски езици не се пренасят вътре в група от знаци. Reset all preferences to their defaults? Да се нулират ли всички настройки до стойностите по подразбиране? The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. Стойностите по подразбиране се прилагат, когато щракнете върху ОК в Настройки. Отказ там запазва текущите ви настройки. @@ -3555,6 +3596,7 @@ digits Malayalam Малаялам Recent Commands Последни команди No recent commands Няма последни команди Type to search commands, tools, panels and effects Въведете текст, за да търсите команди, инструменти, панели и ефекти + Clear Recent Commands Изчистване на последните команди Search commands Търсене на команди Search Commands… Търсене на команди… Secondary Вторичен @@ -4753,6 +4795,8 @@ axis Both И двете @msg `aspect` must be a number (%) `aspect` трябва да бъде число (%) @msg `at` must be [x, y] `at` трябва да бъде [x, y] @msg `color` must be a colour `color` трябва да бъде цвят +@msg `sliders` must be none, oklch or hsl `sliders` трябва да бъде none, oklch или hsl +@msg OKLCH needs sRGB as the working RGB space OKLCH изисква sRGB като работно RGB пространство @msg `command` must be a command whose menu item opens a dialog (see ui.menuDialog) `command` трябва да бъде команда, чийто елемент от менюто отваря диалогов прозорец (вижте ui.menuDialog) @msg `freeform.points` must be an array `freeform.points` трябва да бъде масив @msg `freeform.lines` must be an array `freeform.lines` трябва да бъде масив @@ -7886,6 +7930,20 @@ breakText Glyphs Глифи @msg A joint does not close by {gap} pt. Една връзка не се затваря с {gap} pt. @msg Two panels pass through each other. Два панела минават един през друг. @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer трябва да е "singleLine", "everyLine", "standardSingleLine" или "standardEveryLine" + Vector Packs Векторни пакети + Compass Rose Роза на компаса + Botanical Sprig Ботаническо клонче + Facet Diamond Фасетиран ромб + Tide Crest Гребен на вълна + Leaf Vine Листна лоза + Blossom Chain Цветна верига + Pennant Garland Гирлянд от знаменца + Lantern String Низ от фенери + Orbit Lines Орбитални линии + Petal Garland Гирлянд от венчелистчета + Lattice Braid Решетъчна плетка + Facet Sweep Фасетен щрих + Artistic Brushes Художествени четки Paint Боя Flat Sweep Плосък замах Dry Drag Сухо влачене diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index c67844f521..712106379f 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -797,6 +797,8 @@ Contextual Task Bar Kontekstna traka zadataka Pin Bar Position Položaj prikvačene trake Reset Bar Position Vrati položaj trake na početno + Bar Actions Radnje trake + Reset Bar Actions Vrati radnje trake na početno Resize Promijeni veličinu Tools Alati Toolbars Trake s alatima @@ -817,9 +819,14 @@ {name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2} Wheel View Prikaz kotača Box View Prikaz kvadrata + Show Out-of-Gamut Colors Prikaži boje izvan gamuta Box Channel Kanal kvadrata Color box Kvadrat boje Color Wheel Options Opcije kotača boja + Show Document Colors Prikaži boje dokumenta + Document Colors Boje dokumenta + Selection Colors Boje odabira +@plural Used {n} time|Used {n} times Korišteno {n} put|Korišteno {n} puta|Korišteno {n} puta Show Harmony Prikaži harmoniju Harmony Rule Pravilo harmonije Harmony color Boja harmonije @@ -2051,6 +2058,10 @@ digits Malayalam Malajalam Rename Preset Preimenuj unaprijed postavljeno Save Image Trace Preset Sačuvaj unaprijed postavljeno praćenje slike Delete Image Trace Preset Izbriši unaprijed postavljeno praćenje slike + Tracing Presets… Predlošci praćenja… + Import Image Trace Presets Uvezi predloške praćenja slike + Export Image Trace Presets Izvezi predloške praćenja slike + Replace the saved presets that have these names? Zamijeniti sačuvane predloške s ovim imenima? Method: Metoda: Pad Produži Repeats Broj ponavljanja @@ -4208,6 +4219,13 @@ theme Appearance Izgled Pen Tool Alat pero Quick Pen Tool Alat brzo pero Quick Pen Brzo pero + Quick Pen Toolbar Traka Brzog pera + Continuous Arc Neprekidni luk + Sharp Corner Arc Luk s oštrim uglom + Flip Arc Preokreni luk + Hide Toolbar Sakrij traku s alatima + Pin Toolbar Position Prikvači položaj trake s alatima + Reset Toolbar Position Vrati položaj trake s alatima na početno Picas Pice Portuguese Portugalski Preserve Appearance and Overprints Očuvaj izgled i pretiske @@ -4321,6 +4339,11 @@ theme Appearance Izgled Edit Arrowheads Uredi vrhove strelica Edit Arrowheads… Uredi vrhove strelica… Reload Arrowheads Ponovo učitaj vrhove strelica + Bevels Zakošenja + Edit Bevels Uredi zakošenja + Edit Bevels… Uredi zakošenja… + {name} (document) {name} (dokument) + Reload Bevels Ponovo učitaj zakošenja Stroke Options Opcije poteza Width Profiles Profili širine Apply Graphic Style Primijeni grafički stil @@ -4549,6 +4572,11 @@ axis Both Obje Image Slika Ink Tinta Lab Lab + OKLCH Sliders OKLCH klizači + HSL Sliders HSL klizači + Chroma Hroma + The largest chroma sRGB holds at this lightness and hue Najveća hroma koju sRGB obuhvata pri ovoj svjetloći i nijansi + OKLCH needs sRGB as the working RGB space OKLCH zahtijeva sRGB kao radni RGB prostor Medium Srednje Name Naziv None Ništa @@ -4642,6 +4670,7 @@ font-technology Variable Varijabilni Recent Commands Nedavne naredbe No recent commands Nema nedavnih naredbi Type to search commands, tools, panels and effects Upišite za pretragu naredbi, alata, panela i efekata + Clear Recent Commands Očisti nedavne naredbe Dashed Line Isprekidana linija Panel menu Meni panela Unembed… Poništi ugrađivanje… @@ -4761,9 +4790,13 @@ font-technology Variable Varijabilni Edit type set in fonts that aren't available? Urediti tekst u fontovima koji nisu dostupni? Shows each slice's number in a box at its top left on the canvas; off, the slice outlines still show. Prikazuje broj svakog isječka u okviru u njegovom gornjem lijevom uglu na platnu; kada je isključeno, obrisi isječaka i dalje se prikazuju. The color of user and object slice outlines and their number boxes; auto slices use a dimmer shade of it. Boja obrisa korisničkih i objektnih isječaka i okvira s njihovim brojevima; automatski isječci koriste blijeđu nijansu te boje. + In paragraphs with Hyphenate on, a listed word is hyphenated only at the hyphens typed in it, or never when it has none, whatever its language or case. U pasusima s uključenom opcijom Rastavljaj riječi navedena riječ dobija crticu za rastavljanje samo na crticama upisanim u nju, ili nikad ako ih nema, bez obzira na jezik i velika ili mala slova. + On the desktop, this folder's .wasm plug-ins load at startup and when OK sets a new folder, except in Safe Mode; one that asks for permissions loads only after you grant them. The web version loads none. U desktop verziji .wasm dodaci iz ove mape učitavaju se pri pokretanju i kada U redu postavi novu mapu, osim u sigurnom načinu rada; dodatak koji traži dozvole učitava se tek kada ih odobrite. Web verzija ne učitava nijedan. + Large gives each filter or command plug-in run at least 250 million instructions, with the same time limit; Normal keeps the plug-in's own budget. Live effects, exporters and importers keep theirs. Veliko daje svakom pokretanju dodatka za filter ili naredbu najmanje 250 miliona instrukcija uz isto vremensko ograničenje; Normalno zadržava vlastiti budžet dodatka. Živi efekti, izvoznici i uvoznici zadržavaju svoj. New type takes this language while Document Setup's language is English: USA; type already in a document keeps its own language. Novi tekst dobija ovaj jezik dok je jezik u Postavkama dokumenta Engleski: SAD; tekst koji je već u dokumentu zadržava svoj jezik. In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its language or case. U pasusima s uključenom opcijom Rastavljaj riječi navedena riječ se rastavlja samo na crticama upisanim u nju, ili nigdje ako ih nema, bez obzira na jezik i velika ili mala slova. On the desktop, the .wasm plug-ins in this folder load at startup and when you click OK with a new folder here, except in Safe Mode; the web version does not load them. U desktop verziji .wasm dodaci iz ove mape učitavaju se pri pokretanju i kada kliknete U redu s novom mapom ovdje, osim u sigurnom načinu rada; web verzija ih ne učitava. + Normal keeps each plug-in's own limits; with Large, a plug-in filter or command may run at least 250 million instructions besides those for its input. The time limit stays the same. Normalno zadržava vlastita ograničenja svakog dodatka; uz Veliko filter ili naredba dodatka može izvršiti najmanje 250 miliona instrukcija pored onih za svoj ulaz. Vremensko ograničenje ostaje isto. How many instructions each run of a plug-in object filter may use; Large allows more than Normal with the same 60-second limit. Heavy filters keep their own budget. Koliko instrukcija smije koristiti svako pokretanje filtera objekata iz dodatka; Veliko dopušta više od Normalno uz isto ograničenje od 60 sekundi. Teški filteri zadržavaju svoj budžet. The first scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. Prvi izbor radnog diska: Startup, None ili putanja do mape; VectorCraft ga sprema, ali još ne koristi radne diskove. The second scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. Drugi izbor radnog diska: Startup, None ili putanja do mape; VectorCraft ga sprema, ali još ne koristi radne diskove. @@ -4775,13 +4808,15 @@ font-technology Variable Varijabilni Shows each tool group's name above its tools in the toolbar; off, the groups follow one another with nothing between them. Prikazuje naziv svake grupe alata iznad njenih alata na traci s alatima; isključeno, grupe slijede jedna za drugom bez ičega između njih. From now on, documents you open or create open as tabs; off, each opens in a floating window. Documents already open stay where they are. Od sada se dokumenti koje otvorite ili kreirate otvaraju kao kartice; isključeno, svaki se otvara u plutajućem prozoru. Već otvoreni dokumenti ostaju gdje jesu. Makes the document tabs taller and their names larger. Kartice dokumenata čini višim, a njihove nazive većim. - From the next start, the system draws the window's title bar where VectorCraft would otherwise draw its own. Od sljedećeg pokretanja sistem iscrtava naslovnu traku prozora tamo gdje bi VectorCraft inače iscrtao svoju. - From the next start, VectorCraft draws the window's title bar even where the desktop would draw it, unless System Title Bar is on. Od sljedećeg pokretanja VectorCraft iscrtava naslovnu traku prozora čak i tamo gdje bi je iscrtala radna površina, osim ako je Sistemska naslovna traka uključena. + From the next start, the system draws the window's title bar where VectorCraft would otherwise draw its own; on Linux and the BSDs, the VECTORCRAFT_TITLEBAR variable takes precedence. Od sljedećeg pokretanja sistem iscrtava naslovnu traku prozora tamo gdje bi VectorCraft inače iscrtao svoju; na Linuxu i BSD sistemima prednost ima varijabla VECTORCRAFT_TITLEBAR. + From the next start, VectorCraft draws the window's title bar even where the desktop would draw it, unless System Title Bar is on or the VECTORCRAFT_TITLEBAR variable chooses it. Od sljedećeg pokretanja VectorCraft iscrtava naslovnu traku prozora čak i tamo gdje bi je iscrtala radna površina, osim ako je Sistemska naslovna traka uključena ili je bira varijabla VECTORCRAFT_TITLEBAR. Makes the interface larger or smaller; art on the canvas keeps its size at the same zoom. Povećava ili smanjuje interfejs; crtež na platnu zadržava veličinu pri istom zumu. The tool pointers VectorCraft draws grow and shrink with UI Scaling; off, they keep their size. Pokazivači alata koje VectorCraft iscrtava rastu i smanjuju se sa Skaliranjem interfejsa; isključeno, zadržavaju svoju veličinu. The language of the interface; Auto uses the system's language. The dialog switches language as soon as you choose one. Jezik interfejsa; Automatski koristi jezik sistema. Dijalog mijenja jezik čim ga odaberete. Animated Zoom works only while this is on; off, Animated Zoom is dimmed and zooming does not animate. Animirano zumiranje radi samo dok je ovo uključeno; isključeno, Animirano zumiranje je zatamnjeno i zumiranje nije animirano. The wheel's zoom glides in, and the Zoom tool zooms as you drag sideways or hold it down; off, the Zoom tool zooms to the area you drag across. Zumiranje točkićem glatko klizi, a Alat za zumiranje zumira dok vučete ustranu ili ga držite; isključeno, Alat za zumiranje zumira na područje preko kojeg prevučete. + From the next start, the desktop version shows the canvas through this kind of graphics processor; the artwork is drawn on the CPU either way. Automatic prefers the integrated one on Windows and macOS. The web version does not use it. Od sljedećeg pokretanja desktop verzija prikazuje platno preko ove vrste grafičkog procesora; crtež se u svakom slučaju iscrtava na CPU-u. Automatski daje prednost integrisanom na Windowsu i macOS-u. Web verzija ga ne koristi. + From the next start, the window shows each frame without waiting for the display's refresh where the graphics driver allows, at most 240 frames a second. Od sljedećeg pokretanja prozor prikazuje svaki kadar bez čekanja na osvježavanje ekrana gdje grafički drajver to dozvoljava, najviše 240 kadrova u sekundi. From the next start, the desktop version draws with this kind of graphics processor; Automatic prefers the one that drives the display. The web version does not use it. Od sljedećeg pokretanja desktop verzija crta ovom vrstom grafičkog procesora; Automatski daje prednost onom koji pokreće ekran. Web verzija ga ne koristi. From the next start, the window shows frames without waiting for the display to refresh, at most 240 a second; off, the display paces them. A present mode set at launch overrides it. Od sljedećeg pokretanja prozor prikazuje kadrove bez čekanja na osvježavanje ekrana, najviše 240 u sekundi; isključeno, ritam određuje ekran. Način prikaza zadan pri pokretanju ima prednost. The most undo steps each document keeps; lowering it drops the oldest steps when you click OK. Steps can also go sooner when they use too much memory. Najveći broj koraka poništavanja koje svaki dokument čuva; manji broj uklanja najstarije korake kada kliknete U redu. Koraci mogu nestati i ranije kada zauzimaju previše memorije. @@ -4800,6 +4835,9 @@ font-technology Variable Varijabilni Open Recent Files and the Home screen list at most this many recent files; 0 lists none, and VectorCraft still remembers up to 30. Otvori nedavne datoteke i ekran Početna prikazuju najviše ovoliko nedavnih datoteka; 0 ne prikazuje nijednu, a VectorCraft i dalje pamti do 30. When a document opens, a linked EPS image that shows its saved preview keeps it instead of reading the EPS file again; changed files still follow Update Links. Pri otvaranju dokumenta povezana EPS slika koja prikazuje svoj sačuvani pregled zadržava ga umjesto ponovnog čitanja EPS datoteke; izmijenjene datoteke i dalje slijede Ažuriraj veze. In Pixel Preview, images are drawn smoothed; off, their pixels show with hard edges. Outside Pixel Preview, images are always smoothed. U Pregledu piksela slike se crtaju zaglađene; isključeno, njihovi pikseli imaju oštre ivice. Izvan Pregleda piksela slike su uvijek zaglađene. + PDF Text Tekst PDF-a + The text of a PDF you open or embed comes in as editable type, or as outlines that look the same on a computer without its fonts. Tekst PDF-a koji otvorite ili ugradite dolazi kao tekst koji se može uređivati ili kao obrisi koji izgledaju isto na računaru bez njegovih fontova. + Linked pages show the file's own text. Povezane stranice prikazuju vlastiti tekst datoteke. When a linked file changes, Automatically reads it again, Ask When Modified asks you first, and Manually leaves it and shows a note in the status bar. Kada se povezana datoteka promijeni, Automatski je ponovo čita, Pitaj kad je izmijenjeno vas prvo pita, a Ručno je ostavlja kakva jeste i prikazuje napomenu na statusnoj traci. On the desktop, the folder New from Template… and Save as Template… start in; leave it blank for VectorCraft Templates in your documents folder. U desktop verziji folder u kojem počinju Novo iz predloška… i Sačuvaj kao predložak…; ostavite prazno za VectorCraft Templates u vašem folderu dokumenata. Edit Original opens a linked file in the system's default app for its type; off, a linked raster image opens in PhotoCraft where it is installed. Uredi original otvara povezanu datoteku u zadanoj aplikaciji sistema za njen tip; isključeno, povezana rasterska slika otvara se u PhotoCraftu ako je instaliran. @@ -4837,6 +4875,10 @@ font-technology Variable Varijabilni Circle Krug Circle Tool Alat za krug Circle too large Krug je prevelik + Show Radii Prikaži poluprečnike + Show Diameter Prikaži prečnik + Anchors at Standard Positions Sidrene tačke na standardnim položajima + Third Point by Dragging Treća tačka povlačenjem Clip to Art Isijeci prema crtežu Colorize Oboji Gamma Gama @@ -5201,6 +5243,8 @@ imageTrace Outline Obris @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` mora biti grayscale, rgb, hsb, cmyk ili websafe @msg `view` must be wheel or box `view` mora biti wheel ili box @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` mora biti hue, saturation, brightness, red, green ili blue +@msg `sliders` must be none, oklch or hsl `sliders` mora biti none, oklch ili hsl +@msg OKLCH needs sRGB as the working RGB space OKLCH zahtijeva sRGB kao radni RGB prostor @msg `{k}` must be [x, y] `{k}` mora biti [x, y] @msg `{name}` has no options `{name}` nema opcija @msg `{name}` is a built-in workspace; choose another name `{name}` je ugrađeni radni prostor; odaberite drugi naziv @@ -7941,6 +7985,20 @@ shape Open Otvoren @msg A joint does not close by {gap} pt. Spoj se ne zatvara za {gap} pt. @msg Two panels pass through each other. Dva panela prolaze jedan kroz drugi. @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer mora biti "singleLine", "everyLine", "standardSingleLine" ili "standardEveryLine" + Vector Packs Vektorski paketi + Compass Rose Ruža kompasa + Botanical Sprig Botanička grančica + Facet Diamond Fasetirani romb + Tide Crest Vrh vala + Leaf Vine Lisnata loza + Blossom Chain Cvjetni lanac + Pennant Garland Girlanda zastavica + Lantern String Niz lampiona + Orbit Lines Orbitalne linije + Petal Garland Vijenac od latica + Lattice Braid Rešetkasti preplet + Facet Sweep Fasetni potez + Artistic Brushes Umjetničke četke Paint Boja Flat Sweep Ravni potez Dry Drag Suhi potez diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index a697cfeaad..a431a69ae7 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -734,6 +734,10 @@ arrowhead Target Diana Cusp Punta Straight segment Segment recte Circle too large El cercle és massa gran + Show Radii Mostra els radis + Show Diameter Mostra el diàmetre + Anchors at Standard Positions Punts d’ancoratge en posicions estàndard + Third Point by Dragging Tercer punt arrossegant Circle (open) Cercle (obert) Classic Clàssic Classic Defaults Valors predeterminats clàssics @@ -887,9 +891,14 @@ arrowhead Target Diana {name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2} Wheel View Visualització de roda Box View Visualització de quadre + Show Out-of-Gamut Colors Mostra els colors fora de gama Box Channel Canal del quadre Color box Quadre de color Color Wheel Options Opcions de la roda de colors + Show Document Colors Mostra els colors del document + Document Colors Colors del document + Selection Colors Colors de la selecció +@plural Used {n} time|Used {n} times Utilitzat {n} vegada|Utilitzat {n} vegades Show Harmony Mostra l’harmonia Harmony Rule Regla d’harmonia Harmony color Color de l’harmonia @@ -1221,6 +1230,10 @@ arrowhead Target Diana Delete Guide Suprimeix la guia Delete Guides Suprimeix les guies Delete Image Trace Preset Suprimeix el preajust de traçat d’imatge + Tracing Presets… Preajustos de traçat… + Import Image Trace Presets Importa preajustos de traçat d’imatge + Export Image Trace Presets Exporta els preajustos de traçat d’imatge + Replace the saved presets that have these names? Voleu substituir els preajustos desats que tenen aquests noms? Delete Layer Suprimeix la capa Delete Library Suprimeix la biblioteca Delete Library Group Suprimeix el grup de biblioteca @@ -2499,6 +2512,11 @@ digits Malayalam Malaiàlam Knife Ganivet Knockout Group Grup knockout Lab Lab + OKLCH Sliders Controls lliscants OKLCH + HSL Sliders Controls lliscants HSL + Chroma Croma + The largest chroma sRGB holds at this lightness and hue El croma més gran que sRGB admet amb aquesta lluminositat i aquest to + OKLCH needs sRGB as the working RGB space OKLCH necessita sRGB com a espai RGB de treball Lab Spot Colors Colors directes Lab Lab Spot Colors: Colors directes Lab: Lab Values Valors Lab @@ -3452,6 +3470,13 @@ digits Malayalam Malaiàlam Pen Tool Eina de ploma Quick Pen Tool Eina de ploma ràpida Quick Pen Ploma ràpida + Quick Pen Toolbar Barra d’eines de la ploma ràpida + Continuous Arc Arc continu + Sharp Corner Arc Arc de cantonada aguda + Flip Arc Inverteix l’arc + Hide Toolbar Amaga la barra d’eines + Pin Toolbar Position Fixa la posició de la barra d’eines + Reset Toolbar Position Restableix la posició de la barra d’eines Pencil Llapis Pencil Tool Eina de llapis Pentagram Pentagrama @@ -3949,6 +3974,8 @@ digits Malayalam Malaiàlam Reset all Revolve settings to their defaults. Restableix tots els paràmetres de revolució als valors predeterminats. Reset Automation Restableix Automation Reset Bar Position Restableix la posició de la barra + Bar Actions Accions de la barra + Reset Bar Actions Restableix les accions de la barra Reset Bounding Box Restableix el quadre delimitador Rotate Bounding Box Gira el quadre delimitador Rotate Bounding Box… Gira el quadre delimitador… @@ -3977,6 +4004,11 @@ digits Malayalam Malaiàlam Edit Arrowheads Edita les puntes de fletxa Edit Arrowheads… Edita les puntes de fletxa… Reload Arrowheads Torna a carregar les puntes de fletxa + Bevels Bisells + Edit Bevels Edita els bisells + Edit Bevels… Edita els bisells… + {name} (document) {name} (document) + Reload Bevels Torna a carregar els bisells Reset Rotate View Restableix la rotació de la vista Reset Ruler Origin Restableix l’origen de les regles Reset the rows to the artwork's colors Restableix les files als colors de l’obra @@ -4129,9 +4161,14 @@ digits Malayalam Malaiàlam Edit type set in fonts that aren't available? Voleu editar el text en tipus de lletra que no estan disponibles? Shows each slice's number in a box at its top left on the canvas; off, the slice outlines still show. Mostra al llenç el número de cada tall en un requadre a la seva cantonada superior esquerra; si està desactivat, els contorns dels talls continuen visibles. The color of user and object slice outlines and their number boxes; auto slices use a dimmer shade of it. El color dels contorns dels talls d’usuari i d’objecte i dels requadres amb el seu número; els talls automàtics fan servir un to més apagat d’aquest color. + New type takes this language while Document Setup's language is English: USA and [Normal Character Style] sets none; type already in a document keeps its own language. El text nou pren aquest idioma mentre l’idioma de Configuració del document sigui Anglès: EUA i [Estil de caràcter normal] no en defineixi cap; el text que ja és en un document conserva el seu idioma. + In paragraphs with Hyphenate on, a listed word is hyphenated only at the hyphens typed in it, or never when it has none, whatever its language or case. En els paràgrafs amb Particiona activat, una paraula de la llista només rep guionet de partició als guionets que s’hi han escrit, o mai si no en té, sigui quin sigui el seu idioma o l’ús de majúscules. + On the desktop, this folder's .wasm plug-ins load at startup and when OK sets a new folder, except in Safe Mode; one that asks for permissions loads only after you grant them. The web version loads none. A la versió d’escriptori, els complements .wasm d’aquesta carpeta es carreguen en iniciar i quan D’acord estableix una carpeta nova, excepte en Mode segur; un que demana permisos només es carrega després que els concediu. La versió web no en carrega cap. + Large gives each filter or command plug-in run at least 250 million instructions, with the same time limit; Normal keeps the plug-in's own budget. Live effects, exporters and importers keep theirs. Gran dona a cada execució d’un complement de filtre o d’ordre almenys 250 milions d’instruccions, amb el mateix límit de temps; Normal manté el pressupost propi del complement. Els efectes en viu, els exportadors i els importadors mantenen el seu. New type takes this language while Document Setup's language is English: USA; type already in a document keeps its own language. El text nou pren aquest idioma mentre l’idioma de Configuració del document sigui Anglès: EUA; el text que ja és en un document conserva el seu idioma. In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its language or case. En els paràgrafs amb Particiona activat, una paraula de la llista es parteix només als guionets que s’hi han escrit, o enlloc si no en té, sigui quin sigui el seu idioma o l’ús de majúscules. On the desktop, the .wasm plug-ins in this folder load at startup and when you click OK with a new folder here, except in Safe Mode; the web version does not load them. A la versió d’escriptori, els complements .wasm d’aquesta carpeta es carreguen en iniciar i quan feu clic a D’acord amb una carpeta nova aquí, excepte en Mode segur; la versió web no els carrega. + Normal keeps each plug-in's own limits; with Large, a plug-in filter or command may run at least 250 million instructions besides those for its input. The time limit stays the same. Normal manté els límits propis de cada complement; amb Gran, un filtre o una ordre d’un complement pot executar com a mínim 250 milions d’instruccions a més de les de la seva entrada. El límit de temps no canvia. How many instructions each run of a plug-in object filter may use; Large allows more than Normal with the same 60-second limit. Heavy filters keep their own budget. Quantes instruccions pot fer servir cada execució d’un filtre d’objectes d’un complement; Gran en permet més que Normal amb el mateix límit de 60 segons. Els filtres pesants conserven el seu pressupost. The first scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. La primera opció de disc d’intercanvi: Startup, None o el camí d’una carpeta; VectorCraft la desa, però encara no fa servir discs d’intercanvi. The second scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. La segona opció de disc d’intercanvi: Startup, None o el camí d’una carpeta; VectorCraft la desa, però encara no fa servir discs d’intercanvi. @@ -4143,13 +4180,15 @@ digits Malayalam Malaiàlam Shows each tool group's name above its tools in the toolbar; off, the groups follow one another with nothing between them. Mostra el nom de cada grup d’eines damunt de les seves eines a la barra d’eines; desactivat, els grups se succeeixen sense res entre ells. From now on, documents you open or create open as tabs; off, each opens in a floating window. Documents already open stay where they are. A partir d’ara, els documents que obriu o creeu s’obren com a pestanyes; desactivat, cadascun s’obre en una finestra flotant. Els documents ja oberts es queden on són. Makes the document tabs taller and their names larger. Fa les pestanyes dels documents més altes i els seus noms més grans. - From the next start, the system draws the window's title bar where VectorCraft would otherwise draw its own. A partir del pròxim inici, el sistema dibuixa la barra de títol de la finestra on VectorCraft, si no, dibuixaria la seva. - From the next start, VectorCraft draws the window's title bar even where the desktop would draw it, unless System Title Bar is on. A partir del pròxim inici, VectorCraft dibuixa la barra de títol de la finestra fins i tot on l’escriptori la dibuixaria, tret que Barra de títol del sistema estigui activada. + From the next start, the system draws the window's title bar where VectorCraft would otherwise draw its own; on Linux and the BSDs, the VECTORCRAFT_TITLEBAR variable takes precedence. A partir del pròxim inici, el sistema dibuixa la barra de títol de la finestra on VectorCraft, si no, dibuixaria la seva; a Linux i als BSD, la variable VECTORCRAFT_TITLEBAR té prioritat. + From the next start, VectorCraft draws the window's title bar even where the desktop would draw it, unless System Title Bar is on or the VECTORCRAFT_TITLEBAR variable chooses it. A partir del pròxim inici, VectorCraft dibuixa la barra de títol de la finestra fins i tot on l’escriptori la dibuixaria, tret que Barra de títol del sistema estigui activada o la variable VECTORCRAFT_TITLEBAR la triï. Makes the interface larger or smaller; art on the canvas keeps its size at the same zoom. Fa la interfície més gran o més petita; l’art del llenç conserva la mida amb el mateix zoom. The tool pointers VectorCraft draws grow and shrink with UI Scaling; off, they keep their size. Els punters d’eina que dibuixa VectorCraft creixen i s’encongeixen amb l’Escalat de la interfície; desactivat, conserven la mida. The language of the interface; Auto uses the system's language. The dialog switches language as soon as you choose one. La llengua de la interfície; Automàtic fa servir la llengua del sistema. El diàleg canvia de llengua tan bon punt en trieu una. Animated Zoom works only while this is on; off, Animated Zoom is dimmed and zooming does not animate. El Zoom animat només funciona mentre això està activat; desactivat, el Zoom animat apareix atenuat i el zoom no s’anima. The wheel's zoom glides in, and the Zoom tool zooms as you drag sideways or hold it down; off, the Zoom tool zooms to the area you drag across. El zoom amb la roda llisca suaument, i l’Eina de zoom fa zoom mentre arrossegueu de costat o la manteniu premuda; desactivat, l’Eina de zoom fa zoom a l’àrea que arrossegueu. + From the next start, the desktop version shows the canvas through this kind of graphics processor; the artwork is drawn on the CPU either way. Automatic prefers the integrated one on Windows and macOS. The web version does not use it. A partir del pròxim inici, la versió d’escriptori mostra el llenç a través d’aquest tipus de processador gràfic; la il·lustració sempre es dibuixa a la CPU. Automàtic prefereix l’integrat a Windows i macOS. La versió web no l’utilitza. + From the next start, the window shows each frame without waiting for the display's refresh where the graphics driver allows, at most 240 frames a second. A partir del pròxim inici, la finestra mostra cada fotograma sense esperar el refresc de la pantalla quan el controlador gràfic ho permet, com a màxim 240 fotogrames per segon. From the next start, the desktop version draws with this kind of graphics processor; Automatic prefers the one that drives the display. The web version does not use it. A partir del pròxim inici, la versió d’escriptori dibuixa amb aquest tipus de processador gràfic; Automàtic prefereix el que controla la pantalla. La versió web no l’utilitza. From the next start, the window shows frames without waiting for the display to refresh, at most 240 a second; off, the display paces them. A present mode set at launch overrides it. A partir del pròxim inici, la finestra mostra els fotogrames sense esperar que la pantalla es refresqui, com a màxim 240 per segon; desactivat, la pantalla marca el ritme. Un mode de presentació definit en iniciar té prioritat. The most undo steps each document keeps; lowering it drops the oldest steps when you click OK. Steps can also go sooner when they use too much memory. El màxim de passos de desfer que conserva cada document; un nombre més baix elimina els passos més antics quan feu clic a D’acord. Els passos també poden desaparèixer abans si ocupen massa memòria. @@ -4168,6 +4207,9 @@ digits Malayalam Malaiàlam Open Recent Files and the Home screen list at most this many recent files; 0 lists none, and VectorCraft still remembers up to 30. Obre fitxers recents i la pantalla d’Inici mostren com a màxim aquest nombre de fitxers recents; 0 no en mostra cap, i VectorCraft continua recordant-ne fins a 30. When a document opens, a linked EPS image that shows its saved preview keeps it instead of reading the EPS file again; changed files still follow Update Links. En obrir un document, una imatge EPS enllaçada que mostra la seva previsualització desada la conserva en lloc de tornar a llegir el fitxer EPS; els fitxers modificats segueixen Actualitza els enllaços. In Pixel Preview, images are drawn smoothed; off, their pixels show with hard edges. Outside Pixel Preview, images are always smoothed. A Previsualització de píxels, les imatges es dibuixen suavitzades; desactivat, els seus píxels mostren vores dures. Fora de Previsualització de píxels, les imatges sempre se suavitzen. + PDF Text Text del PDF + The text of a PDF you open or embed comes in as editable type, or as outlines that look the same on a computer without its fonts. El text d’un PDF que obriu o incrusteu entra com a text editable o com a contorns que es veuen igual en un ordinador sense les seves fonts. + Linked pages show the file's own text. Les pàgines enllaçades mostren el text propi del fitxer. When a linked file changes, Automatically reads it again, Ask When Modified asks you first, and Manually leaves it and shows a note in the status bar. Quan un fitxer enllaçat canvia, Automàticament el torna a llegir, Pregunta quan es modifiqui us ho pregunta abans, i Manualment el deixa com està i mostra un avís a la barra d’estat. On the desktop, the folder New from Template… and Save as Template… start in; leave it blank for VectorCraft Templates in your documents folder. A la versió d’escriptori, la carpeta on comencen Nou a partir d’una plantilla… i Desa com a plantilla…; deixeu-la buida per a VectorCraft Templates a la vostra carpeta de documents. Edit Original opens a linked file in the system's default app for its type; off, a linked raster image opens in PhotoCraft where it is installed. Edita l’original obre un fitxer enllaçat amb l’aplicació per defecte del sistema per al seu tipus; desactivat, una imatge ràster enllaçada s’obre a PhotoCraft si està instal·lat. @@ -4182,7 +4224,6 @@ digits Malayalam Malaiàlam Output All Blacks as Rich Black draws pure CMYK black as RGB black in RGB and grayscale raster exports and Print as Bitmap; it does not change vector exports, CMYK JPEG, TIFF and PSD, or other printing. Genera tots els negres com a negre ric dibuixa el negre CMYK pur com a negre RGB a les exportacions ràster RGB i en escala de grisos i amb Imprimeix com a mapa de bits; no canvia les exportacions vectorials, els JPEG, TIFF i PSD CMYK ni la resta d’impressions. On a touch screen, switches to the Touch workspace; turning this off, or losing the touch screen, goes back to the workspace it switched from. En una pantalla tàctil, canvia a l’espai de treball tàctil; si es desactiva o es perd la pantalla tàctil, torna a l’espai de treball d’abans del canvi. A two-finger tap on the canvas undoes, or switches between selection and drawing tools in the Touch workspace, and a three-finger tap redoes; neither works in Presentation Mode. Un toc amb dos dits al llenç desfà o, a l’espai de treball tàctil, alterna entre les eines de selecció i de dibuix, i un toc amb tres dits refà; cap dels dos funciona en el mode de presentació. - New type takes this language while Document Setup's language is English: USA and [Normal Character Style] sets none; type already in a document keeps its own language. El text nou pren aquest idioma mentre l’idioma de Configuració del document sigui Anglès: EUA i [Estil de caràcter normal] no en defineixi cap; el text que ja és en un document conserva el seu idioma. In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its case; Korean words take no hyphen, and Indian-language words do not break inside a character cluster. En els paràgrafs amb Particiona activat, una paraula de la llista es parteix només als guionets que s’hi han escrit, o enlloc si no en té, sigui quin sigui l’ús de majúscules; les paraules coreanes no prenen guionet, i les paraules en llengües índies no es parteixen dins d’un grup de caràcters. Reset all preferences to their defaults? Voleu restablir totes les preferències als valors predeterminats? The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. Els valors predeterminats s’apliquen quan feu clic a D’acord a Preferències. Cancel·la allà conserva les preferències actuals. @@ -4770,6 +4811,7 @@ digits Malayalam Malaiàlam Recent Commands Ordres recents No recent commands No hi ha ordres recents Type to search commands, tools, panels and effects Escriviu per cercar ordres, eines, panells i efectes + Clear Recent Commands Esborra les ordres recents Search commands Cerca ordres Search Commands… Cerca ordres… Search Fonts Folder Cerca a la carpeta de tipus de lletra @@ -6144,6 +6186,8 @@ digits Malayalam Malaiàlam @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` ha de ser grayscale, rgb, hsb, cmyk o websafe @msg `view` must be wheel or box `view` ha de ser wheel o box @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` ha de ser hue, saturation, brightness, red, green o blue +@msg `sliders` must be none, oklch or hsl `sliders` ha de ser none, oklch o hsl +@msg OKLCH needs sRGB as the working RGB space OKLCH necessita sRGB com a espai RGB de treball @msg `name` is empty `name` és buit @msg `newName` is empty `newName` és buit @msg `pathfinder` must be an object `pathfinder` ha de ser un objecte @@ -7133,6 +7177,10 @@ liquify-list-end {0}, {1} {0} i {1} @msg exit isolation mode first surt primer del mode d’aïllament @msg select an envelope selecciona un embolcall @msg select an image selecciona una imatge +@msg object {_1} is an image changed by Perspective Distort or Free Distort, which this command does not work on l'objecte {_1} és una imatge modificada amb Distorsió de perspectiva o Distorsió lliure, amb la qual aquesta ordre no funciona +@msg image {_1} cannot be distorted this way: its corners would not make a convex shape la imatge {_1} no es pot distorsionar així: les seves cantonades no formarien una forma convexa +@msg image {_1} cannot be distorted this way: its corners would cross the warp's horizon la imatge {_1} no es pot distorsionar així: les seves cantonades creuarien l'horitzó de la distorsió +@msg image {_1} cannot be distorted this way: its corners would be too close together for a perspective map la imatge {_1} no es pot distorsionar així: les seves cantonades estarien massa juntes per a una projecció en perspectiva @msg `background` must be edges, corners or colors `background` ha de ser edges, corners o colors @msg `match` must be distance or channels `match` ha de ser distance o channels @msg `{key}` must be from 0 to 100 `{key}` ha d’estar entre 0 i 100 @@ -7240,7 +7288,10 @@ liquify-list-end {0}, {1} {0} i {1} @msg the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate) l’objecte no té cap efecte 3D (Extrudeix i bisella, Revoluciona, Infla o Gira) @msg `render` must be an object holding only `mode`, set to shaded or wireframe `render` ha de ser un objecte que només contingui `mode`, amb el valor shaded o wireframe @msg its 3D effect builds no solid el seu efecte 3D no construeix cap sòlid -@msg bevel must be none or one of {_1} bevel ha de ser none o un de {_1} +@msg bevel must be none or one of {_1}, or custom with {BEVEL_PROFILE} bevel ha de ser none, un de {_1}, o custom amb {BEVEL_PROFILE} +@msg bevel custom needs {BEVEL_PROFILE}, the bevel's points bevel custom necessita {BEVEL_PROFILE}, els punts del bisell +@msg {BEVEL_NAME} must be a string {BEVEL_NAME} ha de ser una cadena +@msg {BEVEL_PROFILE} must be 2 to {most} [x, y] points, each share between 0 and 1, from [0, 0] (the cap's edge) to [1, 1] (the side wall) {BEVEL_PROFILE} ha de tenir de 2 a {most} punts [x, y], cada proporció entre 0 i 1, des de [0, 0] (la vora de la tapa) fins a [1, 1] (la paret lateral) @msg {_1} can't build solids from this art: its symbol instances, blends and clipping groups hold too many objects {_1} no pot construir sòlids a partir d’aquesta il·lustració: les seves instàncies de símbol, fusions i grups de retall contenen massa objectes @msg {label} can't build a solid from the instance of symbol "{symbol}": the symbol's art isn't available {label} no pot construir un sòlid a partir de la instància del símbol «{symbol}»: la il·lustració del símbol no està disponible @msg {_1}: the clipping path is too complex to cut the art with {_1}: el traçat de retall és massa complex per retallar-hi la il·lustració @@ -8924,6 +8975,20 @@ breakText Glyphs Glifs @msg A joint does not close by {gap} pt. Una unió no es tanca per {gap} pt. @msg Two panels pass through each other. Dos panells es travessen l’un a l’altre. @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer ha de ser "singleLine", "everyLine", "standardSingleLine" o "standardEveryLine" + Vector Packs Paquets vectorials + Compass Rose Rosa dels vents + Botanical Sprig Branqueta botànica + Facet Diamond Diamant facetat + Tide Crest Cresta de l'onada + Leaf Vine Enfiladissa de fulles + Blossom Chain Cadena de flors + Pennant Garland Garlanda de banderins + Lantern String Filera de fanalets + Orbit Lines Línies orbitals + Petal Garland Garlanda de pètals + Lattice Braid Trena reticular + Facet Sweep Traç facetat + Artistic Brushes Pinzells artístics Paint Pintura Flat Sweep Traç pla Dry Drag Arrossegament sec diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 1cb79fa6de..ce1a3db865 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -809,6 +809,8 @@ Contextual Task Bar Kontextový panel úloh Pin Bar Position Připnout polohu panelu Reset Bar Position Obnovit polohu panelu + Bar Actions Akce panelu + Reset Bar Actions Obnovit akce panelu Resize Změnit velikost Tools Nástroje Toolbars Panely nástrojů @@ -829,9 +831,14 @@ {name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2} Wheel View Zobrazení kola Box View Zobrazení čtverce + Show Out-of-Gamut Colors Zobrazit barvy mimo gamut Box Channel Kanál čtverce Color box Barevný čtverec Color Wheel Options Možnosti barevného kola + Show Document Colors Zobrazit barvy dokumentu + Document Colors Barvy dokumentu + Selection Colors Barvy výběru +@plural Used {n} time|Used {n} times Použito {n}krát|Použito {n}krát|Použito {n}krát Show Harmony Zobrazit harmonii Harmony Rule Pravidlo harmonie Harmony color Barva harmonie @@ -2123,6 +2130,10 @@ digits Malayalam Malajálamské Rename Preset Přejmenovat přednastavení Save Image Trace Preset Uložit přednastavení vektorizace obrazu Delete Image Trace Preset Odstranit přednastavení vektorizace obrazu + Tracing Presets… Přednastavení vektorizace… + Import Image Trace Presets Importovat přednastavení vektorizace obrazu + Export Image Trace Presets Exportovat přednastavení vektorizace obrazu + Replace the saved presets that have these names? Nahradit uložená přednastavení s těmito názvy? Method: Metoda: Pad Prodloužit Repeats Počet opakování @@ -4315,6 +4326,13 @@ theme Appearance Motiv Pen Tool Nástroj Pero Quick Pen Tool Nástroj Rychlé pero Quick Pen Rychlé pero + Quick Pen Toolbar Panel nástrojů rychlého pera + Continuous Arc Plynulý oblouk + Sharp Corner Arc Oblouk s ostrým rohem + Flip Arc Překlopit oblouk + Hide Toolbar Skrýt panel nástrojů + Pin Toolbar Position Připnout polohu panelu nástrojů + Reset Toolbar Position Obnovit polohu panelu nástrojů Picas Pica Portuguese Portugalština Preserve Appearance and Overprints Zachovat vzhled a přetisky @@ -4430,6 +4448,11 @@ theme Appearance Motiv Edit Arrowheads Upravit šipky Edit Arrowheads… Upravit šipky… Reload Arrowheads Znovu načíst šipky + Bevels Zkosení + Edit Bevels Upravit zkosení + Edit Bevels… Upravit zkosení… + {name} (document) {name} (dokument) + Reload Bevels Znovu načíst zkosení Stroke Options Možnosti tahu Width Profiles Profily šířky Apply Graphic Style Použít grafický styl @@ -4658,6 +4681,11 @@ axis Both Obě Image Obraz Ink Inkoust Lab Lab + OKLCH Sliders Posuvníky OKLCH + HSL Sliders Posuvníky HSL + Chroma Chroma + The largest chroma sRGB holds at this lightness and hue Největší chroma, kterou sRGB obsáhne při této světlosti a odstínu + OKLCH needs sRGB as the working RGB space OKLCH vyžaduje sRGB jako pracovní prostor RGB Medium Střední Name Název None Žádné @@ -4751,6 +4779,7 @@ font-technology Variable Variabilní Recent Commands Nedávné příkazy No recent commands Žádné nedávné příkazy Type to search commands, tools, panels and effects Pište pro hledání příkazů, nástrojů, panelů a efektů + Clear Recent Commands Vymazat seznam nedávných příkazů Dashed Line Čárkovaná čára Panel menu Nabídka panelu Unembed… Zrušit vložení… @@ -4870,9 +4899,13 @@ font-technology Variable Variabilní Edit type set in fonts that aren't available? Upravit text v písmech, která nejsou k dispozici? Shows each slice's number in a box at its top left on the canvas; off, the slice outlines still show. Zobrazí na plátně číslo každého řezu v rámečku v jeho levém horním rohu; když je vypnuto, obrysy řezů zůstanou zobrazené. The color of user and object slice outlines and their number boxes; auto slices use a dimmer shade of it. Barva obrysů uživatelských a objektových řezů a rámečků s jejich čísly; automatické řezy používají tlumenější odstín této barvy. + In paragraphs with Hyphenate on, a listed word is hyphenated only at the hyphens typed in it, or never when it has none, whatever its language or case. V odstavcích se zapnutou volbou Dělit slova dostane uvedené slovo dělicí spojovník jen u spojovníků, které v něm napíšete, nebo nikdy, pokud žádné nemá, bez ohledu na jazyk a velikost písmen. + On the desktop, this folder's .wasm plug-ins load at startup and when OK sets a new folder, except in Safe Mode; one that asks for permissions loads only after you grant them. The web version loads none. V desktopové verzi se zásuvné moduly .wasm z této složky načtou při spuštění a když OK nastaví novou složku, kromě nouzového režimu; modul, který žádá o oprávnění, se načte až po jejich udělení. Webová verze nenačte žádný. + Large gives each filter or command plug-in run at least 250 million instructions, with the same time limit; Normal keeps the plug-in's own budget. Live effects, exporters and importers keep theirs. Velké dá každému běhu zásuvného modulu filtru nebo příkazu nejméně 250 milionů instrukcí se stejným časovým limitem; Normální ponechá vlastní rozpočet modulu. Živé efekty, exportéry a importéry si ponechají svůj. New type takes this language while Document Setup's language is English: USA; type already in a document keeps its own language. Nový text dostane tento jazyk, dokud je jazyk v Nastavení dokumentu Angličtina: USA; text, který už v dokumentu je, si ponechá svůj jazyk. In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its language or case. V odstavcích se zapnutou volbou Dělit slova se uvedené slovo dělí jen u spojovníků, které v něm napíšete, nebo nikde, pokud žádné nemá, bez ohledu na jazyk a velikost písmen. On the desktop, the .wasm plug-ins in this folder load at startup and when you click OK with a new folder here, except in Safe Mode; the web version does not load them. V desktopové verzi se zásuvné moduly .wasm z této složky načtou při spuštění a po klepnutí na OK s novou složkou zde, kromě nouzového režimu; webová verze je nenačítá. + Normal keeps each plug-in's own limits; with Large, a plug-in filter or command may run at least 250 million instructions besides those for its input. The time limit stays the same. Normální zachová vlastní limity každého zásuvného modulu; s volbou Velké může filtr nebo příkaz zásuvného modulu provést nejméně 250 milionů instrukcí navíc k těm pro svůj vstup. Časový limit zůstává stejný. How many instructions each run of a plug-in object filter may use; Large allows more than Normal with the same 60-second limit. Heavy filters keep their own budget. Kolik instrukcí smí použít každé spuštění filtru objektů ze zásuvného modulu; Velké povoluje víc než Normální při stejném limitu 60 sekund. Náročné filtry si ponechají vlastní rozpočet. The first scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. První volba odkládacího disku: Startup, None nebo cesta ke složce; VectorCraft ji uloží, ale odkládací disky zatím nepoužívá. The second scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. Druhá volba odkládacího disku: Startup, None nebo cesta ke složce; VectorCraft ji uloží, ale odkládací disky zatím nepoužívá. @@ -4884,13 +4917,15 @@ font-technology Variable Variabilní Shows each tool group's name above its tools in the toolbar; off, the groups follow one another with nothing between them. Zobrazuje název každé skupiny nástrojů nad jejími nástroji v panelu nástrojů; při vypnutí skupiny následují jedna za druhou bez ničeho mezi nimi. From now on, documents you open or create open as tabs; off, each opens in a floating window. Documents already open stay where they are. Dokumenty, které od teď otevřete nebo vytvoříte, se otevírají jako karty; při vypnutí se každý otevře v plovoucím okně. Už otevřené dokumenty zůstanou, kde jsou. Makes the document tabs taller and their names larger. Karty dokumentů budou vyšší a jejich názvy větší. - From the next start, the system draws the window's title bar where VectorCraft would otherwise draw its own. Od příštího spuštění kreslí záhlaví okna systém tam, kde by jinak VectorCraft kreslil své vlastní. - From the next start, VectorCraft draws the window's title bar even where the desktop would draw it, unless System Title Bar is on. Od příštího spuštění kreslí VectorCraft záhlaví okna i tam, kde by ho kreslilo pracovní prostředí, pokud není zapnuté Systémové záhlaví okna. + From the next start, the system draws the window's title bar where VectorCraft would otherwise draw its own; on Linux and the BSDs, the VECTORCRAFT_TITLEBAR variable takes precedence. Od příštího spuštění kreslí záhlaví okna systém tam, kde by jinak VectorCraft kreslil své vlastní; v Linuxu a systémech BSD má přednost proměnná VECTORCRAFT_TITLEBAR. + From the next start, VectorCraft draws the window's title bar even where the desktop would draw it, unless System Title Bar is on or the VECTORCRAFT_TITLEBAR variable chooses it. Od příštího spuštění kreslí VectorCraft záhlaví okna i tam, kde by ho kreslilo pracovní prostředí, pokud není zapnuté Systémové záhlaví okna nebo ho nevolí proměnná VECTORCRAFT_TITLEBAR. Makes the interface larger or smaller; art on the canvas keeps its size at the same zoom. Zvětší nebo zmenší rozhraní; kresba na plátně si při stejném zvětšení zachová velikost. The tool pointers VectorCraft draws grow and shrink with UI Scaling; off, they keep their size. Ukazatele nástrojů, které kreslí VectorCraft, se zvětšují a zmenšují s Měřítkem rozhraní; při vypnutí si zachovají velikost. The language of the interface; Auto uses the system's language. The dialog switches language as soon as you choose one. Jazyk rozhraní; Automaticky použije jazyk systému. Dialog přepne jazyk, jakmile nějaký zvolíte. Animated Zoom works only while this is on; off, Animated Zoom is dimmed and zooming does not animate. Animované zvětšení funguje, jen když je toto zapnuto; při vypnutí je Animované zvětšení zašedlé a zvětšování není animované. The wheel's zoom glides in, and the Zoom tool zooms as you drag sideways or hold it down; off, the Zoom tool zooms to the area you drag across. Zvětšení kolečkem plynule dojede a Nástroj Lupa zvětšuje, když táhnete do strany nebo ho podržíte; při vypnutí Nástroj Lupa zvětší oblast, přes kterou táhnete. + From the next start, the desktop version shows the canvas through this kind of graphics processor; the artwork is drawn on the CPU either way. Automatic prefers the integrated one on Windows and macOS. The web version does not use it. Od příštího spuštění zobrazuje desktopová verze plátno přes tento druh grafického procesoru; kresba se v každém případě vykresluje na CPU. Automaticky dává ve Windows a macOS přednost integrovanému. Webová verze ho nepoužívá. + From the next start, the window shows each frame without waiting for the display's refresh where the graphics driver allows, at most 240 frames a second. Od příštího spuštění okno zobrazuje každý snímek bez čekání na obnovení displeje, kde to grafický ovladač dovolí, nejvýše 240 snímků za sekundu. From the next start, the desktop version draws with this kind of graphics processor; Automatic prefers the one that drives the display. The web version does not use it. Od příštího spuštění kreslí desktopová verze tímto druhem grafického procesoru; Automaticky dává přednost tomu, který řídí displej. Webová verze ho nepoužívá. From the next start, the window shows frames without waiting for the display to refresh, at most 240 a second; off, the display paces them. A present mode set at launch overrides it. Od příštího spuštění okno zobrazuje snímky bez čekání na obnovení displeje, nejvýše 240 za sekundu; vypnuto, tempo určuje displej. Režim zobrazení nastavený při spuštění má přednost. The most undo steps each document keeps; lowering it drops the oldest steps when you click OK. Steps can also go sooner when they use too much memory. Nejvyšší počet kroků zpět, které si každý dokument ponechá; nižší číslo po klepnutí na OK odstraní nejstarší kroky. Kroky mohou zmizet i dříve, když zabírají příliš paměti. @@ -4909,6 +4944,9 @@ font-technology Variable Variabilní Open Recent Files and the Home screen list at most this many recent files; 0 lists none, and VectorCraft still remembers up to 30. Otevřít nedávné soubory a obrazovka Domů uvádějí nejvýše tolik nedávných souborů; 0 neuvádí žádný a VectorCraft si i tak pamatuje až 30. When a document opens, a linked EPS image that shows its saved preview keeps it instead of reading the EPS file again; changed files still follow Update Links. Při otevření dokumentu si propojený obraz EPS, který ukazuje svůj uložený náhled, tento náhled ponechá a soubor EPS znovu nečte; změněné soubory se dál řídí volbou Aktualizovat propojení. In Pixel Preview, images are drawn smoothed; off, their pixels show with hard edges. Outside Pixel Preview, images are always smoothed. V Náhledu obrazových bodů se obrazy kreslí vyhlazené; při vypnutí mají jejich obrazové body ostré hrany. Mimo Náhled obrazových bodů se obrazy vyhlazují vždy. + PDF Text Text PDF + The text of a PDF you open or embed comes in as editable type, or as outlines that look the same on a computer without its fonts. Text PDF, který otevřete nebo vložíte, se načte jako upravitelný text nebo jako obrysy, které vypadají stejně i na počítači bez jeho písem. + Linked pages show the file's own text. Propojené stránky zobrazují vlastní text souboru. When a linked file changes, Automatically reads it again, Ask When Modified asks you first, and Manually leaves it and shows a note in the status bar. Když se propojený soubor změní, Automaticky ho načte znovu, Při změně se zeptat se vás nejdřív zeptá a Ručně ho nechá být a zobrazí upozornění ve stavovém řádku. On the desktop, the folder New from Template… and Save as Template… start in; leave it blank for VectorCraft Templates in your documents folder. V desktopové verzi složka, ve které začínají Nový ze šablony… a Uložit jako šablonu…; nechte ji prázdnou pro VectorCraft Templates ve vaší složce dokumentů. Edit Original opens a linked file in the system's default app for its type; off, a linked raster image opens in PhotoCraft where it is installed. Upravit originál otevře propojený soubor ve výchozí aplikaci systému pro jeho typ; při vypnutí se propojený rastrový obraz otevře v PhotoCraftu, pokud je nainstalován. @@ -4946,6 +4984,10 @@ font-technology Variable Variabilní Cusp Hrot Straight segment Přímý segment Circle too large Kruh je příliš velký + Show Radii Zobrazit poloměry + Show Diameter Zobrazit průměr + Anchors at Standard Positions Kotevní body ve standardních polohách + Third Point by Dragging Třetí bod tažením Clip to Art Oříznout podle kresby Colorize Obarvit Gamma Gama @@ -5496,6 +5538,8 @@ liquify-list-end {0}, {1} {0} a {1} @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` musí být grayscale, rgb, hsb, cmyk nebo websafe @msg `view` must be wheel or box `view` musí být wheel nebo box @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` musí být hue, saturation, brightness, red, green nebo blue +@msg `sliders` must be none, oklch or hsl `sliders` musí být none, oklch nebo hsl +@msg OKLCH needs sRGB as the working RGB space OKLCH vyžaduje sRGB jako pracovní prostor RGB @msg `{k}` must be [x, y] `{k}` musí být [x, y] @msg `{name}` has no options `{name}` nemá žádné možnosti @msg `{name}` is a built-in workspace; choose another name `{name}` je vestavěný pracovní prostor; zvolte jiný název @@ -5905,6 +5949,10 @@ liquify-list-end {0}, {1} {0} a {1} @msg this trace would make more than {max} anchor points, more than the document can show smoothly: raise Noise, lower Paths or Colors, or pick a lower-fidelity preset tato vektorizace by vytvořila více než {max} kotevních bodů, víc, než dokument plynule zobrazí: zvyšte Šum, snižte Cesty nebo Barvy, nebo zvolte přednastavení s nižší věrností @msg select an envelope vyberte obálku @msg select an image vyberte obraz +@msg object {_1} is an image changed by Perspective Distort or Free Distort, which this command does not work on objekt {_1} je obraz změněný příkazem Perspektivní deformace nebo Volná deformace, se kterým tento příkaz nepracuje +@msg image {_1} cannot be distorted this way: its corners would not make a convex shape obraz {_1} nelze takto deformovat: jeho rohy by netvořily konvexní tvar +@msg image {_1} cannot be distorted this way: its corners would cross the warp's horizon obraz {_1} nelze takto deformovat: jeho rohy by překročily horizont deformace +@msg image {_1} cannot be distorted this way: its corners would be too close together for a perspective map obraz {_1} nelze takto deformovat: jeho rohy by byly příliš blízko sebe pro perspektivní zobrazení @msg `background` must be edges, corners or colors `background` musí být edges, corners nebo colors @msg `match` must be distance or channels `match` musí být distance nebo channels @msg `{key}` must be from 0 to 100 `{key}` musí být od 0 do 100 @@ -6830,7 +6878,10 @@ mark-style Japanese Japonské @msg the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate) objekt nemá žádný 3D efekt (Vysunutí a zkosení, Rotační těleso, Nafouknutí ani Otočit) @msg `render` must be an object holding only `mode`, set to shaded or wireframe `render` musí být objekt obsahující pouze `mode` s hodnotou shaded nebo wireframe @msg its 3D effect builds no solid jeho 3D efekt nevytváří žádné těleso -@msg bevel must be none or one of {_1} bevel musí být none nebo jedno z {_1} +@msg bevel must be none or one of {_1}, or custom with {BEVEL_PROFILE} bevel musí být none, jedno z {_1} nebo custom s {BEVEL_PROFILE} +@msg bevel custom needs {BEVEL_PROFILE}, the bevel's points bevel custom vyžaduje {BEVEL_PROFILE}, body zkosení +@msg {BEVEL_NAME} must be a string {BEVEL_NAME} musí být řetězec +@msg {BEVEL_PROFILE} must be 2 to {most} [x, y] points, each share between 0 and 1, from [0, 0] (the cap's edge) to [1, 1] (the side wall) {BEVEL_PROFILE} musí mít 2 až {most} bodů [x, y], každý podíl mezi 0 a 1, od [0, 0] (hrana čelní plochy) do [1, 1] (boční stěna) @msg {_1} can't build solids from this art: its symbol instances, blends and clipping groups hold too many objects {_1} nemůže z této kresby vytvořit tělesa: její instance symbolů, prolnutí a ořezové skupiny obsahují příliš mnoho objektů @msg {label} can't build a solid from the instance of symbol "{symbol}": the symbol's art isn't available {label} nemůže vytvořit těleso z instance symbolu „{symbol}“: kresba symbolu není k dispozici @msg {_1}: the clipping path is too complex to cut the art with {_1}: ořezová cesta je příliš složitá na oříznutí kresby @@ -10748,6 +10799,20 @@ breakText Glyphs Glyfy @msg A panel is not joined to the rest by a crease. Panel není se zbytkem spojen žádnou linií bigu. @msg A fold line is on a non-printing layer. Linie skladu je na netisknutelné vrstvě. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Panely: {panels}, panty: {hinges}, chyby: {errors}, upozornění: {warnings} + Vector Packs Vektorové balíčky + Compass Rose Směrová růžice + Botanical Sprig Botanická větvička + Facet Diamond Fazetový diamant + Tide Crest Hřeben vlny + Leaf Vine Listová liána + Blossom Chain Květinový řetěz + Pennant Garland Girlanda praporků + Lantern String Řetěz luceren + Orbit Lines Orbitální čáry + Petal Garland Okvětní girlanda + Lattice Braid Mřížkový cop + Facet Sweep Fazetový tah + Artistic Brushes Umělecké štětce Paint Malba Flat Sweep Plochý tah Dry Drag Suchý tah diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 38d2bea825..efccd17560 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -432,7 +432,10 @@ liquify-list-end {0}, {1} {0} og {1} @msg the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate) objektet har ingen 3D-effekt (Ekstrudér og facet, Omdrej, Pust op eller Rotér) @msg `render` must be an object holding only `mode`, set to shaded or wireframe `render` skal være et objekt, der kun indeholder `mode` med værdien shaded eller wireframe @msg its 3D effect builds no solid dens 3D-effekt danner intet legeme -@msg bevel must be none or one of {_1} bevel skal være none eller en af {_1} +@msg bevel must be none or one of {_1}, or custom with {BEVEL_PROFILE} bevel skal være none, en af {_1} eller custom med {BEVEL_PROFILE} +@msg bevel custom needs {BEVEL_PROFILE}, the bevel's points bevel custom kræver {BEVEL_PROFILE}, facettens punkter +@msg {BEVEL_NAME} must be a string {BEVEL_NAME} skal være en streng +@msg {BEVEL_PROFILE} must be 2 to {most} [x, y] points, each share between 0 and 1, from [0, 0] (the cap's edge) to [1, 1] (the side wall) {BEVEL_PROFILE} skal være 2 til {most} punkter [x, y], hver andel mellem 0 og 1, fra [0, 0] (dækfladens kant) til [1, 1] (sidevæggen) @msg {_1} can't build solids from this art: its symbol instances, blends and clipping groups hold too many objects {_1} kan ikke danne legemer af denne grafik: dens symbolforekomster, blandinger og beskæringsgrupper indeholder for mange objekter @msg {label} can't build a solid from the instance of symbol "{symbol}": the symbol's art isn't available {label} kan ikke danne et legeme af forekomsten af symbolet "{symbol}": symbolets grafik er ikke tilgængelig @msg {_1}: the clipping path is too complex to cut the art with {_1}: beskæringskurven er for kompleks til at skære grafikken med @@ -3509,6 +3512,8 @@ liquify-list-end {0}, {1} {0} og {1} Contextual Task Bar Kontekstuel opgavelinje Pin Bar Position Fastgør linjens placering Reset Bar Position Nulstil linjens placering + Bar Actions Linjens handlinger + Reset Bar Actions Nulstil linjens handlinger Tools Værktøjer Toolbars Værktøjslinjer Advanced Avanceret @@ -3528,9 +3533,14 @@ liquify-list-end {0}, {1} {0} og {1} {name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2} Wheel View Hjulvisning Box View Kvadratvisning + Show Out-of-Gamut Colors Vis farver uden for gamut Box Channel Kvadratets kanal Color box Farvekvadrat Color Wheel Options Indstillinger for farvehjul + Show Document Colors Vis dokumentfarver + Document Colors Dokumentfarver + Selection Colors Markeringens farver +@plural Used {n} time|Used {n} times Brugt {n} gang|Brugt {n} gange Show Harmony Vis harmoni Harmony Rule Harmoniregel Harmony color Harmonifarve @@ -4692,6 +4702,10 @@ digits Malayalam Malayalam Rename Preset Omdøb forudindstilling Save Image Trace Preset Gem forudindstilling til billedsporing Delete Image Trace Preset Slet forudindstilling til billedsporing + Tracing Presets… Vektoriseringsforudindstillinger… + Import Image Trace Presets Importér forudindstillinger til billedsporing + Export Image Trace Presets Eksportér forudindstillinger til billedsporing + Replace the saved presets that have these names? Vil du erstatte de gemte forudindstillinger med disse navne? Method: Metode: Pad Forlæng Repeats Gentagelser @@ -6771,6 +6785,13 @@ theme Appearance Udseende Pen Tool Pen-værktøj Quick Pen Tool Hurtigpen-værktøj Quick Pen Hurtigpen + Quick Pen Toolbar Hurtigpennens værktøjslinje + Continuous Arc Fortløbende bue + Sharp Corner Arc Bue med skarpt hjørne + Flip Arc Vend bue + Hide Toolbar Skjul værktøjslinjen + Pin Toolbar Position Fastgør værktøjslinjens placering + Reset Toolbar Position Nulstil værktøjslinjens placering Picas Pica Portuguese Portugisisk Preserve Appearance and Overprints Bevar udseende og overprint @@ -6886,6 +6907,11 @@ theme Appearance Udseende Edit Arrowheads Redigér pilespidser Edit Arrowheads… Redigér pilespidser… Reload Arrowheads Genindlæs pilespidser + Bevels Facetter + Edit Bevels Redigér facetter + Edit Bevels… Redigér facetter… + {name} (document) {name} (dokument) + Reload Bevels Genindlæs facetter Stroke Options Konturindstillinger Width Profiles Breddeprofiler Apply Graphic Style Anvend grafikstil @@ -7105,6 +7131,11 @@ axis Both Begge Image Billede Ink Blæk Lab Lab + OKLCH Sliders OKLCH-skydere + HSL Sliders HSL-skydere + Chroma Kroma + The largest chroma sRGB holds at this lightness and hue Den største kroma, sRGB kan rumme ved denne lyshed og farvetone + OKLCH needs sRGB as the working RGB space OKLCH kræver sRGB som RGB-arbejdsfarverum Medium Medium Name Navn None Ingen @@ -7196,6 +7227,7 @@ font-technology Variable Variable Recent Commands Seneste kommandoer No recent commands Ingen seneste kommandoer Type to search commands, tools, panels and effects Skriv for at søge i kommandoer, værktøjer, paneler og effekter + Clear Recent Commands Ryd seneste kommandoer Dashed Line Stiplet linje Panel menu Panelmenu Unembed… Ophæv integrering… @@ -7315,9 +7347,13 @@ font-technology Variable Variable Edit type set in fonts that aren't available? Rediger tekst i skrifttyper, der ikke er tilgængelige? Shows each slice's number in a box at its top left on the canvas; off, the slice outlines still show. Viser hvert udsnits nummer i en boks i dets øverste venstre hjørne på lærredet; når den er slået fra, vises udsnittenes konturer stadig. The color of user and object slice outlines and their number boxes; auto slices use a dimmer shade of it. Farven på konturerne af bruger- og objektudsnit og på boksene med deres numre; automatiske udsnit bruger en svagere nuance af den. + In paragraphs with Hyphenate on, a listed word is hyphenated only at the hyphens typed in it, or never when it has none, whatever its language or case. I afsnit med Orddeling slået til får et ord på listen kun orddelingsbindestreg ved de bindestreger, der er skrevet i det, eller aldrig uden nogen, uanset sprog og store eller små bogstaver. + On the desktop, this folder's .wasm plug-ins load at startup and when OK sets a new folder, except in Safe Mode; one that asks for permissions loads only after you grant them. The web version loads none. I desktopversionen indlæses denne mappes .wasm-plug-ins ved start, og når OK angiver en ny mappe, undtagen i sikker tilstand; et plug-in, der beder om tilladelser, indlæses først, når du har givet dem. Webversionen indlæser ingen. + Large gives each filter or command plug-in run at least 250 million instructions, with the same time limit; Normal keeps the plug-in's own budget. Live effects, exporters and importers keep theirs. Stor giver hver kørsel af et filter- eller kommando-plug-in mindst 250 millioner instruktioner med samme tidsgrænse; Normal beholder plug-in'ets eget budget. Live-effekter, eksportører og importører beholder deres. New type takes this language while Document Setup's language is English: USA; type already in a document keeps its own language. Ny tekst får dette sprog, så længe sproget i Dokumentopsætning er Engelsk: USA; tekst, der allerede er i et dokument, beholder sit eget sprog. In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its language or case. I afsnit med Orddeling slået til deles et ord på listen kun ved de bindestreger, der er skrevet i det, eller slet ikke uden nogen, uanset sprog og store eller små bogstaver. On the desktop, the .wasm plug-ins in this folder load at startup and when you click OK with a new folder here, except in Safe Mode; the web version does not load them. I desktopversionen indlæses .wasm-plug-ins i denne mappe ved start, og når du klikker på OK med en ny mappe her, undtagen i sikker tilstand; webversionen indlæser dem ikke. + Normal keeps each plug-in's own limits; with Large, a plug-in filter or command may run at least 250 million instructions besides those for its input. The time limit stays the same. Normal beholder hvert plug-ins egne grænser; med Stor kan et plug-in-filter eller en plug-in-kommando køre mindst 250 millioner instruktioner ud over dem til sit input. Tidsgrænsen forbliver den samme. How many instructions each run of a plug-in object filter may use; Large allows more than Normal with the same 60-second limit. Heavy filters keep their own budget. Hvor mange instruktioner hver kørsel af et plug-ins objektfilter må bruge; Stor tillader flere end Normal med den samme grænse på 60 sekunder. Tunge filtre beholder deres eget budget. The first scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. Det første valg af midlertidig disk: Startup, None eller en mappesti; VectorCraft gemmer det, men bruger endnu ikke midlertidige diske. The second scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. Det andet valg af midlertidig disk: Startup, None eller en mappesti; VectorCraft gemmer det, men bruger endnu ikke midlertidige diske. @@ -7329,13 +7365,15 @@ font-technology Variable Variable Shows each tool group's name above its tools in the toolbar; off, the groups follow one another with nothing between them. Viser hver værktøjsgruppes navn over dens værktøjer i værktøjslinjen; slået fra følger grupperne efter hinanden uden noget imellem. From now on, documents you open or create open as tabs; off, each opens in a floating window. Documents already open stay where they are. Fremover åbner dokumenter, du åbner eller opretter, som faner; slået fra åbner hvert i et flydende vindue. Dokumenter, der allerede er åbne, bliver, hvor de er. Makes the document tabs taller and their names larger. Gør dokumentfanerne højere og deres navne større. - From the next start, the system draws the window's title bar where VectorCraft would otherwise draw its own. Fra næste start tegner systemet vinduets titellinje, hvor VectorCraft ellers ville tegne sin egen. - From the next start, VectorCraft draws the window's title bar even where the desktop would draw it, unless System Title Bar is on. Fra næste start tegner VectorCraft vinduets titellinje, også hvor skrivebordsmiljøet ville tegne den, medmindre Systemtitellinje er slået til. + From the next start, the system draws the window's title bar where VectorCraft would otherwise draw its own; on Linux and the BSDs, the VECTORCRAFT_TITLEBAR variable takes precedence. Fra næste start tegner systemet vinduets titellinje, hvor VectorCraft ellers ville tegne sin egen; på Linux og BSD-systemerne har variablen VECTORCRAFT_TITLEBAR forrang. + From the next start, VectorCraft draws the window's title bar even where the desktop would draw it, unless System Title Bar is on or the VECTORCRAFT_TITLEBAR variable chooses it. Fra næste start tegner VectorCraft vinduets titellinje, også hvor skrivebordsmiljøet ville tegne den, medmindre Systemtitellinje er slået til eller variablen VECTORCRAFT_TITLEBAR vælger den. Makes the interface larger or smaller; art on the canvas keeps its size at the same zoom. Gør brugergrænsefladen større eller mindre; grafik på lærredet beholder sin størrelse ved samme zoom. The tool pointers VectorCraft draws grow and shrink with UI Scaling; off, they keep their size. De værktøjsmarkører, VectorCraft tegner, vokser og krymper med UI-skalering; slået fra beholder de deres størrelse. The language of the interface; Auto uses the system's language. The dialog switches language as soon as you choose one. Brugergrænsefladens sprog; Auto bruger systemets sprog. Dialogen skifter sprog, så snart du vælger et. Animated Zoom works only while this is on; off, Animated Zoom is dimmed and zooming does not animate. Animeret zoom virker kun, mens dette er slået til; slået fra er Animeret zoom nedtonet, og zoom animeres ikke. The wheel's zoom glides in, and the Zoom tool zooms as you drag sideways or hold it down; off, the Zoom tool zooms to the area you drag across. Zoom med hjulet glider blødt ind, og Zoomværktøjet zoomer, mens du trækker til siden eller holder det nede; slået fra zoomer Zoomværktøjet til det område, du trækker hen over. + From the next start, the desktop version shows the canvas through this kind of graphics processor; the artwork is drawn on the CPU either way. Automatic prefers the integrated one on Windows and macOS. The web version does not use it. Fra næste start viser desktopversionen lærredet gennem denne type grafikprocessor; illustrationen tegnes altid på CPU'en. Automatisk foretrækker den integrerede på Windows og macOS. Webversionen bruger den ikke. + From the next start, the window shows each frame without waiting for the display's refresh where the graphics driver allows, at most 240 frames a second. Fra næste start viser vinduet hvert billede uden at vente på skærmens opdatering, hvor grafikdriveren tillader det, højst 240 billeder i sekundet. From the next start, the desktop version draws with this kind of graphics processor; Automatic prefers the one that drives the display. The web version does not use it. Fra næste start tegner desktopversionen med denne type grafikprocessor; Automatisk foretrækker den, der styrer skærmen. Webversionen bruger den ikke. From the next start, the window shows frames without waiting for the display to refresh, at most 240 a second; off, the display paces them. A present mode set at launch overrides it. Fra næste start viser vinduet billeder uden at vente på, at skærmen opdateres, højst 240 i sekundet; slået fra bestemmer skærmen tempoet. En visningstilstand angivet ved start har forrang. The most undo steps each document keeps; lowering it drops the oldest steps when you click OK. Steps can also go sooner when they use too much memory. Det største antal fortryd-trin, hvert dokument beholder; et lavere tal fjerner de ældste trin, når du klikker på OK. Trin kan også forsvinde tidligere, når de bruger for meget hukommelse. @@ -7354,6 +7392,9 @@ font-technology Variable Variable Open Recent Files and the Home screen list at most this many recent files; 0 lists none, and VectorCraft still remembers up to 30. Åbn seneste filer og Home-skærmen viser højst så mange seneste filer; 0 viser ingen, og VectorCraft husker stadig op til 30. When a document opens, a linked EPS image that shows its saved preview keeps it instead of reading the EPS file again; changed files still follow Update Links. Når et dokument åbnes, beholder et linket EPS-billede, der viser sin gemte forhåndsvisning, den i stedet for at læse EPS-filen igen; ændrede filer følger stadig Opdatér links. In Pixel Preview, images are drawn smoothed; off, their pixels show with hard edges. Outside Pixel Preview, images are always smoothed. I Pixel-forhåndsvisning tegnes billeder udglattet; slået fra viser deres pixels skarpe kanter. Uden for Pixel-forhåndsvisning udglattes billeder altid. + PDF Text PDF-tekst + The text of a PDF you open or embed comes in as editable type, or as outlines that look the same on a computer without its fonts. Teksten i en PDF, du åbner eller indlejrer, kommer ind som redigerbar tekst eller som omrids, der ser ens ud på en computer uden dens skrifttyper. + Linked pages show the file's own text. Linkede sider viser filens egen tekst. When a linked file changes, Automatically reads it again, Ask When Modified asks you first, and Manually leaves it and shows a note in the status bar. Når en linket fil ændres, læser Automatisk den igen, Spørg ved ændringer spørger dig først, og Manuelt lader den være og viser en besked i statuslinjen. On the desktop, the folder New from Template… and Save as Template… start in; leave it blank for VectorCraft Templates in your documents folder. I desktopversionen den mappe, Ny fra skabelon… og Gem som skabelon… starter i; lad den stå tom for VectorCraft Templates i din dokumentmappe. Edit Original opens a linked file in the system's default app for its type; off, a linked raster image opens in PhotoCraft where it is installed. Redigér original åbner en linket fil i systemets standardapp for dens type; slået fra åbnes et linket rasterbillede i PhotoCraft, hvis det er installeret. @@ -7391,6 +7432,10 @@ font-technology Variable Variable Cusp Spids Straight segment Lige segment Circle too large Cirklen er for stor + Show Radii Vis radier + Show Diameter Vis diameter + Anchors at Standard Positions Ankerpunkter i standardpositioner + Third Point by Dragging Tredje punkt ved træk Clip to Art Beskær til grafik Colorize Farvelæg Gamma Gamma @@ -8079,6 +8124,10 @@ imageTrace Outline Kontur @msg this trace would make more than {max} anchor points, more than the document can show smoothly: raise Noise, lower Paths or Colors, or pick a lower-fidelity preset denne sporing ville skabe flere end {max} ankerpunkter, hvilket er flere, end dokumentet kan vise flydende: hæv Støj, sænk Stier eller Farver, eller vælg en forudindstilling med lavere kvalitet @msg select an envelope markér en konvolut @msg select an image markér et billede +@msg object {_1} is an image changed by Perspective Distort or Free Distort, which this command does not work on objektet {_1} er et billede, der er ændret med Perspektivforvrængning eller Fri forvrængning, og denne kommando virker ikke på det +@msg image {_1} cannot be distorted this way: its corners would not make a convex shape billedet {_1} kan ikke forvrænges sådan: dets hjørner ville ikke danne en konveks form +@msg image {_1} cannot be distorted this way: its corners would cross the warp's horizon billedet {_1} kan ikke forvrænges sådan: dets hjørner ville krydse forvrængningens horisont +@msg image {_1} cannot be distorted this way: its corners would be too close together for a perspective map billedet {_1} kan ikke forvrænges sådan: dets hjørner ville ligge for tæt på hinanden til en perspektivisk afbildning @msg select an object in perspective markér et objekt i perspektiv @msg select artwork (or a colour group) to recolor markér grafik (eller en farvegruppe) for at skifte farver @msg select at least two objects markér mindst to objekter @@ -9109,6 +9158,8 @@ variable-list-end {0}, {1} {0} og {1} @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` skal være grayscale, rgb, hsb, cmyk eller websafe @msg `view` must be wheel or box `view` skal være wheel eller box @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` skal være hue, saturation, brightness, red, green eller blue +@msg `sliders` must be none, oklch or hsl `sliders` skal være none, oklch eller hsl +@msg OKLCH needs sRGB as the working RGB space OKLCH kræver sRGB som RGB-arbejdsfarverum @msg the Color Picker is not open farvevælgeren er ikke åben @msg the screen color sampler is already open skærmfarvesampleren er allerede åben @msg this system has no screen color sampler dette system har ingen skærmfarvesampler @@ -10810,6 +10861,20 @@ breakText Glyphs Glyffer @msg A joint does not close by {gap} pt. En samling lukker ikke med {gap} pt. @msg Two panels pass through each other. To paneler går gennem hinanden. @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer skal være "singleLine", "everyLine", "standardSingleLine" eller "standardEveryLine" + Vector Packs Vektorpakker + Compass Rose Kompasrose + Botanical Sprig Botanisk kvist + Facet Diamond Facetteret diamant + Tide Crest Bølgetop + Leaf Vine Bladranke + Blossom Chain Blomsterkæde + Pennant Garland Vimpelguirlande + Lantern String Lygtekæde + Orbit Lines Banekurver + Petal Garland Kronbladsguirlande + Lattice Braid Gitterfletning + Facet Sweep Facetteret strøg + Artistic Brushes Kunstneriske pensler Paint Maling Flat Sweep Fladt strøg Dry Drag Tørt træk diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 0c5908c2be..fe6d9599a1 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -484,6 +484,11 @@ font-technology Variable Variabel Cusp Spitze Straight segment Gerades Segment Circle too large Kreis zu groß + Show Radii Radien anzeigen + Show Diameter Durchmesser anzeigen + Anchors at Standard Positions Ankerpunkte an Standardpositionen + Third Point by Dragging Dritter Punkt durch Ziehen + Gray Grau Classic Defaults Klassische Standardwerte Clean Up… Aufräumen… Clear Löschen @@ -590,9 +595,14 @@ font-technology Variable Variabel {name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2} Wheel View Kreisansicht Box View Quadratansicht + Show Out-of-Gamut Colors Farben außerhalb des Farbumfangs einblenden Box Channel Kanal des Quadrats Color box Farbquadrat Color Wheel Options Optionen für den Farbkreis + Show Document Colors Dokumentfarben einblenden + Document Colors Dokumentfarben + Selection Colors Farben der Auswahl +@plural Used {n} time|Used {n} times {n}-mal verwendet|{n}-mal verwendet Show Harmony Harmonie einblenden Harmony Rule Harmonieregel Harmony color Harmoniefarbe @@ -636,6 +646,8 @@ font-technology Variable Variabel Contextual Task Bar Kontextbezogene Taskleiste Pin Bar Position Position der Leiste fixieren Reset Bar Position Position der Leiste zurücksetzen + Bar Actions Aktionen der Leiste + Reset Bar Actions Aktionen der Leiste zurücksetzen Resize Größe ändern Contrast Kontrast Control Steuerung @@ -1905,6 +1917,10 @@ file-filter Templates Vorlagen Rename Preset Vorgabe umbenennen Save Image Trace Preset Bildnachzeichner-Vorgabe speichern Delete Image Trace Preset Bildnachzeichner-Vorgabe löschen + Tracing Presets… Nachzeichnervorgaben… + Import Image Trace Presets Bildnachzeichner-Vorgaben importieren + Export Image Trace Presets Bildnachzeichner-Vorgaben exportieren + Replace the saved presets that have these names? Gespeicherte Vorgaben mit diesen Namen ersetzen? Image Trace Presets Bildnachzeichner-Vorgaben Image: Bild: Images: Bilder: @@ -2038,6 +2054,11 @@ file-filter Templates Vorlagen Knife Messer Knockout Group Aussparungsgruppe Lab Lab + OKLCH Sliders OKLCH-Regler + HSL Sliders HSL-Regler + Chroma Chroma + The largest chroma sRGB holds at this lightness and hue Das größte Chroma, das sRGB bei dieser Helligkeit und diesem Farbton enthält + OKLCH needs sRGB as the working RGB space OKLCH erfordert sRGB als RGB-Arbeitsfarbraum Lab Spot Colors: Lab-Volltonfarben: Lab Values Lab-Werte Landscape Querformat @@ -2755,6 +2776,13 @@ file-filter Templates Vorlagen Pen Tool Zeichenstift-Werkzeug Quick Pen Tool Schnellzeichenstift-Werkzeug Quick Pen Schnellzeichenstift + Quick Pen Toolbar Schnellzeichenstift-Werkzeugleiste + Continuous Arc Fortlaufender Bogen + Sharp Corner Arc Bogen mit scharfer Ecke + Flip Arc Bogen spiegeln + Hide Toolbar Werkzeugleiste ausblenden + Pin Toolbar Position Position der Werkzeugleiste fixieren + Reset Toolbar Position Position der Werkzeugleiste zurücksetzen Pencil Buntstift Pencil Tool Buntstift-Werkzeug per slice pro Slice @@ -3202,6 +3230,11 @@ digits Malayalam Malayalam Edit Arrowheads Pfeilspitzen bearbeiten Edit Arrowheads… Pfeilspitzen bearbeiten… Reload Arrowheads Pfeilspitzen neu laden + Bevels Abgeflachte Kanten + Edit Bevels Abgeflachte Kanten bearbeiten + Edit Bevels… Abgeflachte Kanten bearbeiten… + {name} (document) {name} (Dokument) + Reload Bevels Abgeflachte Kanten neu laden Rotate View Ansicht drehen Reset Rotate View Ansichtsdrehung zurücksetzen Rotate View to Selection Ansicht nach Auswahl drehen @@ -3340,9 +3373,14 @@ digits Malayalam Malayalam Edit type set in fonts that aren't available? Text in Schriften bearbeiten, die nicht verfügbar sind? Shows each slice's number in a box at its top left on the canvas; off, the slice outlines still show. Zeigt auf der Arbeitsfläche die Nummer jedes Slices in einem Kästchen oben links im Slice; ist die Option aus, werden die Slice-Umrisse weiterhin angezeigt. The color of user and object slice outlines and their number boxes; auto slices use a dimmer shade of it. Die Farbe der Umrisse von Benutzer- und Objekt-Slices und ihrer Nummernkästchen; automatische Slices verwenden einen blasseren Ton davon. + In paragraphs with Hyphenate on, a listed word is hyphenated only at the hyphens typed in it, or never when it has none, whatever its language or case. In Absätzen mit eingeschalteter Silbentrennung erhält ein aufgeführtes Wort nur an den darin eingegebenen Bindestrichen einen Trennstrich oder nie, wenn es keine hat, unabhängig von Sprache und Groß- und Kleinschreibung. + On the desktop, this folder's .wasm plug-ins load at startup and when OK sets a new folder, except in Safe Mode; one that asks for permissions loads only after you grant them. The web version loads none. In der Desktop-Version werden die .wasm-Plug-ins dieses Ordners beim Start geladen und wenn OK einen neuen Ordner festlegt, außer im abgesicherten Modus; eines, das Berechtigungen anfordert, erst nachdem Sie sie erteilt haben. Die Webversion lädt keine. + Large gives each filter or command plug-in run at least 250 million instructions, with the same time limit; Normal keeps the plug-in's own budget. Live effects, exporters and importers keep theirs. „Groß“ gibt jedem Lauf eines Filter- oder Befehls-Plug-ins mindestens 250 Millionen Anweisungen bei gleichem Zeitlimit; „Normal“ behält das eigene Budget des Plug-ins. Live-Effekte, Exporter und Importer behalten ihres. New type takes this language while Document Setup's language is English: USA; type already in a document keeps its own language. Neuer Text erhält diese Sprache, solange die Sprache unter „Dokument einrichten“ Englisch: USA ist; Text, der bereits in einem Dokument steht, behält seine Sprache. + New type takes this language while Document Setup's language is English: USA and [Normal Character Style] sets none; type already in a document keeps its own language. Neuer Text erhält diese Sprache, solange die Sprache unter „Dokument einrichten“ Englisch: USA ist und [Normales Zeichenformat] keine Sprache festlegt; Text, der bereits in einem Dokument steht, behält seine Sprache. In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its language or case. In Absätzen mit eingeschalteter Silbentrennung wird ein aufgeführtes Wort nur an den darin eingegebenen Bindestrichen getrennt oder gar nicht, wenn es keine hat, unabhängig von Sprache und Groß- und Kleinschreibung. On the desktop, the .wasm plug-ins in this folder load at startup and when you click OK with a new folder here, except in Safe Mode; the web version does not load them. In der Desktop-Version werden die .wasm-Plug-ins in diesem Ordner beim Start geladen und wenn Sie hier mit einem neuen Ordner auf OK klicken, außer im abgesicherten Modus; die Webversion lädt sie nicht. + Normal keeps each plug-in's own limits; with Large, a plug-in filter or command may run at least 250 million instructions besides those for its input. The time limit stays the same. „Normal“ behält die eigenen Grenzen jedes Plug-ins; mit „Groß“ darf ein Plug-in-Filter oder -Befehl mindestens 250 Millionen Anweisungen zusätzlich zu denen für seine Eingabe ausführen. Das Zeitlimit bleibt gleich. How many instructions each run of a plug-in object filter may use; Large allows more than Normal with the same 60-second limit. Heavy filters keep their own budget. Wie viele Anweisungen jeder Lauf eines Objektfilters aus einem Plug-in verwenden darf; „Groß“ erlaubt mehr als „Normal“, bei derselben Grenze von 60 Sekunden. Aufwendige Filter behalten ihr eigenes Budget. The first scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. Die erste Wahl für das Arbeitsvolume: Startup, None oder ein Ordnerpfad; VectorCraft speichert sie, verwendet aber noch keine Arbeitsvolumes. The second scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. Die zweite Wahl für das Arbeitsvolume: Startup, None oder ein Ordnerpfad; VectorCraft speichert sie, verwendet aber noch keine Arbeitsvolumes. @@ -3354,13 +3392,15 @@ digits Malayalam Malayalam Shows each tool group's name above its tools in the toolbar; off, the groups follow one another with nothing between them. Zeigt den Namen jeder Werkzeuggruppe über ihren Werkzeugen in der Werkzeugleiste; ausgeschaltet folgen die Gruppen ohne etwas dazwischen aufeinander. From now on, documents you open or create open as tabs; off, each opens in a floating window. Documents already open stay where they are. Ab jetzt öffnen sich Dokumente, die Sie öffnen oder erstellen, als Registerkarten; ausgeschaltet öffnet sich jedes in einem schwebenden Fenster. Bereits geöffnete Dokumente bleiben, wo sie sind. Makes the document tabs taller and their names larger. Macht die Registerkarten der Dokumente höher und ihre Namen größer. - From the next start, the system draws the window's title bar where VectorCraft would otherwise draw its own. Ab dem nächsten Start zeichnet das System die Titelleiste des Fensters dort, wo VectorCraft sonst seine eigene zeichnen würde. - From the next start, VectorCraft draws the window's title bar even where the desktop would draw it, unless System Title Bar is on. Ab dem nächsten Start zeichnet VectorCraft die Titelleiste des Fensters auch dort, wo der Desktop sie zeichnen würde, außer „Systemtitelleiste“ ist eingeschaltet. + From the next start, the system draws the window's title bar where VectorCraft would otherwise draw its own; on Linux and the BSDs, the VECTORCRAFT_TITLEBAR variable takes precedence. Ab dem nächsten Start zeichnet das System die Titelleiste des Fensters dort, wo VectorCraft sonst seine eigene zeichnen würde; unter Linux und den BSDs hat die Variable VECTORCRAFT_TITLEBAR Vorrang. + From the next start, VectorCraft draws the window's title bar even where the desktop would draw it, unless System Title Bar is on or the VECTORCRAFT_TITLEBAR variable chooses it. Ab dem nächsten Start zeichnet VectorCraft die Titelleiste des Fensters auch dort, wo der Desktop sie zeichnen würde, außer „Systemtitelleiste“ ist eingeschaltet oder die Variable VECTORCRAFT_TITLEBAR legt sie fest. Makes the interface larger or smaller; art on the canvas keeps its size at the same zoom. Macht die Benutzeroberfläche größer oder kleiner; Bildmaterial auf der Arbeitsfläche behält bei gleichem Zoom seine Größe. The tool pointers VectorCraft draws grow and shrink with UI Scaling; off, they keep their size. Die Werkzeugzeiger, die VectorCraft zeichnet, wachsen und schrumpfen mit der „Skalierung der Benutzeroberfläche“; ausgeschaltet behalten sie ihre Größe. The language of the interface; Auto uses the system's language. The dialog switches language as soon as you choose one. Die Sprache der Benutzeroberfläche; „Auto“ verwendet die Sprache des Systems. Der Dialog wechselt die Sprache, sobald Sie eine wählen. Animated Zoom works only while this is on; off, Animated Zoom is dimmed and zooming does not animate. „Animierter Zoom“ funktioniert nur, solange dies eingeschaltet ist; ausgeschaltet ist „Animierter Zoom“ abgeblendet und das Zoomen wird nicht animiert. The wheel's zoom glides in, and the Zoom tool zooms as you drag sideways or hold it down; off, the Zoom tool zooms to the area you drag across. Der Zoom mit dem Mausrad gleitet weich, und das Zoom-Werkzeug zoomt, während Sie seitwärts ziehen oder es gedrückt halten; ausgeschaltet zoomt es auf den Bereich, über den Sie ziehen. + From the next start, the desktop version shows the canvas through this kind of graphics processor; the artwork is drawn on the CPU either way. Automatic prefers the integrated one on Windows and macOS. The web version does not use it. Ab dem nächsten Start zeigt die Desktop-Version die Zeichenfläche über diese Art von Grafikprozessor an; das Bildmaterial wird in jedem Fall auf der CPU gezeichnet. „Automatisch“ bevorzugt unter Windows und macOS den integrierten. Die Webversion verwendet sie nicht. + From the next start, the window shows each frame without waiting for the display's refresh where the graphics driver allows, at most 240 frames a second. Ab dem nächsten Start zeigt das Fenster jedes Bild, ohne auf die Bildwiederholung des Bildschirms zu warten, wo der Grafiktreiber es zulässt, höchstens 240 Bilder pro Sekunde. From the next start, the desktop version draws with this kind of graphics processor; Automatic prefers the one that drives the display. The web version does not use it. Ab dem nächsten Start zeichnet die Desktop-Version mit dieser Art von Grafikprozessor; „Automatisch“ bevorzugt den, der den Bildschirm ansteuert. Die Webversion verwendet sie nicht. From the next start, the window shows frames without waiting for the display to refresh, at most 240 a second; off, the display paces them. A present mode set at launch overrides it. Ab dem nächsten Start zeigt das Fenster Bilder, ohne auf die Bildwiederholung des Bildschirms zu warten, höchstens 240 pro Sekunde; aus, gibt der Bildschirm den Takt vor. Ein beim Start festgelegter Darstellungsmodus hat Vorrang. The most undo steps each document keeps; lowering it drops the oldest steps when you click OK. Steps can also go sooner when they use too much memory. Die Höchstzahl der Rückgängig-Schritte, die jedes Dokument behält; eine kleinere Zahl entfernt beim Klick auf OK die ältesten Schritte. Schritte können auch früher entfallen, wenn sie zu viel Speicher belegen. @@ -3379,6 +3419,9 @@ digits Malayalam Malayalam Open Recent Files and the Home screen list at most this many recent files; 0 lists none, and VectorCraft still remembers up to 30. „Zuletzt geöffnete Dateien“ und der Startbildschirm listen höchstens so viele zuletzt verwendete Dateien; 0 listet keine, und VectorCraft merkt sich weiterhin bis zu 30. When a document opens, a linked EPS image that shows its saved preview keeps it instead of reading the EPS file again; changed files still follow Update Links. Beim Öffnen eines Dokuments behält ein verknüpftes EPS-Bild, das seine gespeicherte Vorschau zeigt, diese, statt die EPS-Datei neu zu lesen; geänderte Dateien folgen weiterhin „Verknüpfungen aktualisieren“. In Pixel Preview, images are drawn smoothed; off, their pixels show with hard edges. Outside Pixel Preview, images are always smoothed. In der Pixelvorschau werden Bilder geglättet gezeichnet; ausgeschaltet zeigen ihre Pixel harte Kanten. Außerhalb der Pixelvorschau werden Bilder immer geglättet. + PDF Text PDF-Text + The text of a PDF you open or embed comes in as editable type, or as outlines that look the same on a computer without its fonts. Der Text einer PDF, die Sie öffnen oder einbetten, kommt als bearbeitbarer Text oder als Pfade, die auf einem Computer ohne ihre Schriften gleich aussehen. + Linked pages show the file's own text. Verknüpfte Seiten zeigen den Text der Datei selbst. When a linked file changes, Automatically reads it again, Ask When Modified asks you first, and Manually leaves it and shows a note in the status bar. Ändert sich eine verknüpfte Datei, liest „Automatisch“ sie neu, „Bei Änderung fragen“ fragt Sie zuerst, und „Manuell“ lässt sie unverändert und zeigt einen Hinweis in der Statusleiste. On the desktop, the folder New from Template… and Save as Template… start in; leave it blank for VectorCraft Templates in your documents folder. In der Desktop-Version der Ordner, in dem „Neu aus Vorlage…“ und „Als Vorlage speichern…“ beginnen; leer lassen für VectorCraft Templates in Ihrem Dokumentordner. Edit Original opens a linked file in the system's default app for its type; off, a linked raster image opens in PhotoCraft where it is installed. „Original bearbeiten“ öffnet eine verknüpfte Datei im Standardprogramm des Systems für ihren Typ; ausgeschaltet öffnet sich ein verknüpftes Rasterbild in PhotoCraft, sofern es installiert ist. @@ -3393,7 +3436,6 @@ digits Malayalam Malayalam Output All Blacks as Rich Black draws pure CMYK black as RGB black in RGB and grayscale raster exports and Print as Bitmap; it does not change vector exports, CMYK JPEG, TIFF and PSD, or other printing. „Alle Schwarztöne als tiefes Schwarz ausgeben“ zeichnet reines CMYK-Schwarz in RGB- und Graustufen-Rasterexporten und bei „Als Bitmap drucken“ als RGB-Schwarz; Vektorexporte, CMYK-JPEG, -TIFF und -PSD und anderes Drucken ändert es nicht. On a touch screen, switches to the Touch workspace; turning this off, or losing the touch screen, goes back to the workspace it switched from. Auf einem Touchscreen wird zum Touch-Arbeitsbereich gewechselt; beim Ausschalten oder wenn kein Touchscreen mehr erkannt wird, kehrt es zum vorherigen Arbeitsbereich zurück. A two-finger tap on the canvas undoes, or switches between selection and drawing tools in the Touch workspace, and a three-finger tap redoes; neither works in Presentation Mode. Tippen mit zwei Fingern auf die Arbeitsfläche macht rückgängig oder wechselt im Touch-Arbeitsbereich zwischen Auswahl- und Zeichenwerkzeugen, Tippen mit drei Fingern wiederholt; beides wirkt nicht im Präsentationsmodus. - New type takes this language while Document Setup's language is English: USA and [Normal Character Style] sets none; type already in a document keeps its own language. Neuer Text erhält diese Sprache, solange die Sprache unter „Dokument einrichten“ Englisch: USA ist und [Normales Zeichenformat] keine Sprache festlegt; Text, der bereits in einem Dokument steht, behält seine Sprache. In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its case; Korean words take no hyphen, and Indian-language words do not break inside a character cluster. In Absätzen mit Silbentrennung wird ein aufgeführtes Wort nur an seinen eingegebenen Bindestrichen getrennt, ohne solche gar nicht, unabhängig von Groß- und Kleinschreibung; koreanische Wörter erhalten keinen Trennstrich, Wörter indischer Sprachen keine Trennung in einer Zeichengruppe. Reset all preferences to their defaults? Alle Voreinstellungen auf ihre Standardwerte zurücksetzen? The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. Die Standardwerte werden angewendet, wenn Sie in den Voreinstellungen auf OK klicken. Abbrechen dort behält Ihre aktuellen Voreinstellungen. @@ -3640,6 +3682,7 @@ digits Malayalam Malayalam Recent Commands Zuletzt verwendete Befehle No recent commands Keine zuletzt verwendeten Befehle Type to search commands, tools, panels and effects Tippen, um Befehle, Werkzeuge, Bedienfelder und Effekte zu suchen + Clear Recent Commands Liste der zuletzt verwendeten Befehle leeren Search commands Befehle suchen Search Commands… Befehle suchen… Secondary Sekundär @@ -5072,6 +5115,8 @@ liquify-list-end {0}, {1} {0} und {1} @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` muss grayscale, rgb, hsb, cmyk oder websafe sein @msg `view` must be wheel or box `view` muss wheel oder box sein @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` muss hue, saturation, brightness, red, green oder blue sein +@msg `sliders` must be none, oklch or hsl `sliders` muss none, oklch oder hsl sein +@msg OKLCH needs sRGB as the working RGB space OKLCH erfordert sRGB als RGB-Arbeitsfarbraum @msg `{k}` must be [x, y] `{k}` muss [x, y] sein @msg `{name}` has no options `{name}` hat keine Optionen @msg `{name}` is a built-in workspace; choose another name `{name}` ist ein integrierter Arbeitsbereich; wählen Sie einen anderen Namen @@ -5483,6 +5528,10 @@ liquify-list-end {0}, {1} {0} und {1} @msg this trace would make more than {max} anchor points, more than the document can show smoothly: raise Noise, lower Paths or Colors, or pick a lower-fidelity preset diese Nachzeichnung würde mehr als {max} Ankerpunkte erzeugen, mehr als das Dokument flüssig darstellen kann: Erhöhen Sie „Rauschen“, verringern Sie „Pfade“ oder „Farben“ oder wählen Sie eine Vorgabe mit geringerer Genauigkeit @msg select an envelope wählen Sie eine Hülle aus @msg select an image wählen Sie ein Bild aus +@msg object {_1} is an image changed by Perspective Distort or Free Distort, which this command does not work on Objekt {_1} ist ein Bild, das mit Perspektivisch verzerren oder Frei verzerren verändert wurde; dieser Befehl funktioniert damit nicht +@msg image {_1} cannot be distorted this way: its corners would not make a convex shape Bild {_1} kann so nicht verzerrt werden: seine Ecken würden keine konvexe Form bilden +@msg image {_1} cannot be distorted this way: its corners would cross the warp's horizon Bild {_1} kann so nicht verzerrt werden: seine Ecken würden den Horizont der Verzerrung überschreiten +@msg image {_1} cannot be distorted this way: its corners would be too close together for a perspective map Bild {_1} kann so nicht verzerrt werden: seine Ecken lägen für eine perspektivische Abbildung zu nah beieinander @msg `background` must be edges, corners or colors `background` muss edges, corners oder colors sein @msg `match` must be distance or channels `match` muss distance oder channels sein @msg `{key}` must be from 0 to 100 `{key}` muss von 0 bis 100 sein @@ -6396,7 +6445,10 @@ lighting Light Licht @msg the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate) das Objekt hat keinen 3D-Effekt (Extrudieren und abgeflachte Kante, Kreiseln, Aufblasen oder Drehen) @msg `render` must be an object holding only `mode`, set to shaded or wireframe `render` muss ein Objekt sein, das nur `mode` mit dem Wert shaded oder wireframe enthält @msg its 3D effect builds no solid sein 3D-Effekt erzeugt keinen Körper -@msg bevel must be none or one of {_1} bevel muss none oder einer der folgenden Werte sein: {_1} +@msg bevel must be none or one of {_1}, or custom with {BEVEL_PROFILE} bevel muss none, einer der Werte {_1} oder custom mit {BEVEL_PROFILE} sein +@msg bevel custom needs {BEVEL_PROFILE}, the bevel's points bevel custom benötigt {BEVEL_PROFILE}, die Punkte der abgeflachten Kante +@msg {BEVEL_NAME} must be a string {BEVEL_NAME} muss eine Zeichenfolge sein +@msg {BEVEL_PROFILE} must be 2 to {most} [x, y] points, each share between 0 and 1, from [0, 0] (the cap's edge) to [1, 1] (the side wall) {BEVEL_PROFILE} muss 2 bis {most} Punkte [x, y] enthalten, jeder Anteil zwischen 0 und 1, von [0, 0] (Kante der Deckfläche) bis [1, 1] (Seitenwand) @msg {_1} can't build solids from this art: its symbol instances, blends and clipping groups hold too many objects {_1} kann aus diesem Bildmaterial keine Körper erstellen: Seine Symbolinstanzen, Angleichungen und Schnittgruppen enthalten zu viele Objekte @msg {label} can't build a solid from the instance of symbol "{symbol}": the symbol's art isn't available {label} kann keinen Körper aus der Instanz des Symbols „{symbol}“ erstellen: Das Bildmaterial des Symbols ist nicht verfügbar @msg {_1}: the clipping path is too complex to cut the art with {_1}: Der Schnittpfad ist zu komplex, um das Bildmaterial damit zu beschneiden @@ -10389,6 +10441,20 @@ breakText Glyphs Glyphen @msg A panel is not joined to the rest by a crease. Ein Feld ist durch keine Rilllinie mit den übrigen verbunden. @msg A fold line is on a non-printing layer. Eine Faltlinie liegt auf einer nicht druckbaren Ebene. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Felder: {panels}, Scharniere: {hinges}, Fehler: {errors}, Warnungen: {warnings} + Vector Packs Vektorpakete + Compass Rose Kompassrose + Botanical Sprig Botanischer Zweig + Facet Diamond Facettierter Diamant + Tide Crest Wellenkamm + Leaf Vine Blätterranke + Blossom Chain Blütenkette + Pennant Garland Wimpelgirlande + Lantern String Laternenkette + Orbit Lines Orbitlinien + Petal Garland Blütengirlande + Lattice Braid Gittergeflecht + Facet Sweep Facettenstrich + Artistic Brushes Künstlerische Pinsel Paint Farbe Flat Sweep Flacher Schwung Dry Drag Trockener Zug diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index f120344fc3..db9bcfef44 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -477,6 +477,10 @@ font-technology Variable Μεταβλητές Cusp Ακίδα Straight segment Ευθύ τμήμα Circle too large Ο κύκλος είναι πολύ μεγάλος + Show Radii Εμφάνιση ακτίνων + Show Diameter Εμφάνιση διαμέτρου + Anchors at Standard Positions Σημεία αγκύρωσης σε τυπικές θέσεις + Third Point by Dragging Τρίτο σημείο με σύρσιμο Classic Defaults Κλασικές προεπιλογές Clean Up… Εκκαθάριση… Clear Εκκαθάριση @@ -565,9 +569,14 @@ font-technology Variable Μεταβλητές {name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2} Wheel View Προβολή τροχού Box View Προβολή τετραγώνου + Show Out-of-Gamut Colors Εμφάνιση χρωμάτων εκτός χρωματικής γκάμας Box Channel Κανάλι τετραγώνου Color box Τετράγωνο χρώματος Color Wheel Options Επιλογές χρωματικού τροχού + Show Document Colors Εμφάνιση χρωμάτων εγγράφου + Document Colors Χρώματα εγγράφου + Selection Colors Χρώματα επιλογής +@plural Used {n} time|Used {n} times Χρησιμοποιείται {n} φορά|Χρησιμοποιείται {n} φορές Show Harmony Εμφάνιση αρμονίας Harmony Rule Κανόνας χρωματικής αρμονίας Harmony color Χρώμα αρμονίας @@ -610,6 +619,8 @@ font-technology Variable Μεταβλητές Contextual Task Bar Γραμμή εργασιών βάσει περιβάλλοντος Pin Bar Position Σταθεροποίηση θέσης γραμμής Reset Bar Position Επαναφορά θέσης γραμμής + Bar Actions Ενέργειες γραμμής + Reset Bar Actions Επαναφορά ενεργειών γραμμής Resize Αλλαγή μεγέθους Contrast Αντίθεση Control Έλεγχος @@ -1814,6 +1825,10 @@ font-technology Variable Μεταβλητές Rename Preset Μετονομασία προεπιλογής Save Image Trace Preset Αποθήκευση προεπιλογής ανίχνευσης περιγραμμάτων εικόνας Delete Image Trace Preset Διαγραφή προεπιλογής ανίχνευσης περιγραμμάτων εικόνας + Tracing Presets… Προεπιλογές ανίχνευσης περιγραμμάτων… + Import Image Trace Presets Εισαγωγή προεπιλογών ανίχνευσης περιγραμμάτων εικόνας + Export Image Trace Presets Εξαγωγή προεπιλογών ανίχνευσης περιγραμμάτων εικόνας + Replace the saved presets that have these names? Αντικατάσταση των αποθηκευμένων προεπιλογών με αυτά τα ονόματα; Image Trace Presets Προεπιλογές ανίχνευσης περιγραμμάτων εικόνας Image: Εικόνα: Images: Εικόνες: @@ -1933,6 +1948,11 @@ font-technology Variable Μεταβλητές Knife Μαχαίρι (Knife) Knockout Group Ομάδα διάτρησης Lab Lab + OKLCH Sliders Ρυθμιστικά OKLCH + HSL Sliders Ρυθμιστικά HSL + Chroma Χρωματική ένταση + The largest chroma sRGB holds at this lightness and hue Η μεγαλύτερη χρωματική ένταση που χωρά το sRGB σε αυτή τη φωτεινότητα και απόχρωση + OKLCH needs sRGB as the working RGB space Το OKLCH απαιτεί sRGB ως χώρο εργασίας RGB Lab Spot Colors: Πλακάτα χρώματα Lab: Lab Values Τιμές Lab Landscape Οριζόντιος προσανατολισμός @@ -2160,6 +2180,13 @@ font-technology Variable Μεταβλητές Pen Tool Πένα (Pen Tool) Quick Pen Tool Εργαλείο γρήγορης πένας Quick Pen Γρήγορη πένα + Quick Pen Toolbar Γραμμή εργαλείων γρήγορης πένας + Continuous Arc Συνεχές τόξο + Sharp Corner Arc Τόξο με αιχμηρή γωνία + Flip Arc Αναστροφή τόξου + Hide Toolbar Απόκρυψη γραμμής εργαλείων + Pin Toolbar Position Σταθεροποίηση θέσης γραμμής εργαλείων + Reset Toolbar Position Επαναφορά θέσης γραμμής εργαλείων Pencil Μολύβι Pencil Tool Μολύβι (Pencil Tool) Percent: Ποσοστό: @@ -4060,6 +4087,11 @@ digits Malayalam Μαλαγιάλαμ Edit Arrowheads Επεξεργασία αιχμών βελών Edit Arrowheads… Επεξεργασία αιχμών βελών… Reload Arrowheads Επαναφόρτωση αιχμών βελών + Bevels Λοξοτμήσεις + Edit Bevels Επεξεργασία λοξοτμήσεων + Edit Bevels… Επεξεργασία λοξοτμήσεων… + {name} (document) {name} (έγγραφο) + Reload Bevels Επαναφόρτωση λοξοτμήσεων Reset Rotate View Επαναφορά περιστροφής προβολής Rotate View to Selection Περιστροφή προβολής ως προς την επιλογή Reset the rows to the artwork's colors Επαναφορά γραμμών στα χρώματα του σχεδίου @@ -4193,9 +4225,14 @@ digits Malayalam Μαλαγιάλαμ Edit type set in fonts that aren't available? Επεξεργασία κειμένου σε γραμματοσειρές που δεν είναι διαθέσιμες; Shows each slice's number in a box at its top left on the canvas; off, the slice outlines still show. Εμφανίζει στον καμβά τον αριθμό κάθε τομής σε ένα πλαίσιο πάνω αριστερά της· όταν είναι απενεργοποιημένο, τα περιγράμματα των τομών εξακολουθούν να εμφανίζονται. The color of user and object slice outlines and their number boxes; auto slices use a dimmer shade of it. Το χρώμα των περιγραμμάτων των τομών χρήστη και αντικειμένου και των πλαισίων με τους αριθμούς τους· οι αυτόματες τομές χρησιμοποιούν μια πιο αχνή απόχρωσή του. + New type takes this language while Document Setup's language is English: USA and [Normal Character Style] sets none; type already in a document keeps its own language. Το νέο κείμενο παίρνει αυτήν τη γλώσσα όσο η γλώσσα στη Ρύθμιση εγγράφου είναι Αγγλικά: ΗΠΑ και το [Κανονικό στυλ χαρακτήρων] δεν ορίζει γλώσσα· το κείμενο που υπάρχει ήδη σε ένα έγγραφο κρατά τη δική του γλώσσα. + In paragraphs with Hyphenate on, a listed word is hyphenated only at the hyphens typed in it, or never when it has none, whatever its language or case. Σε παραγράφους με ενεργό τον Συλλαβισμό, μια λέξη της λίστας συλλαβίζεται μόνο στα ενωτικά που έχουν πληκτρολογηθεί σε αυτήν ή ποτέ αν δεν έχει, ανεξάρτητα από τη γλώσσα ή τα πεζά-κεφαλαία της. + On the desktop, this folder's .wasm plug-ins load at startup and when OK sets a new folder, except in Safe Mode; one that asks for permissions loads only after you grant them. The web version loads none. Στην έκδοση για υπολογιστή, τα πρόσθετα .wasm του φακέλου φορτώνονται στην εκκίνηση και όταν το Εντάξει ορίζει νέο φάκελο, εκτός από την Ασφαλή λειτουργία· ένα που ζητά άδειες φορτώνεται μόνο αφού τις δώσετε. Η έκδοση web δεν φορτώνει κανένα. + Large gives each filter or command plug-in run at least 250 million instructions, with the same time limit; Normal keeps the plug-in's own budget. Live effects, exporters and importers keep theirs. Το Μεγάλο δίνει σε κάθε εκτέλεση προσθέτου φίλτρου ή εντολής τουλάχιστον 250 εκατομμύρια εντολές με το ίδιο χρονικό όριο· η Κανονική κρατά τον προϋπολογισμό του ίδιου του προσθέτου. Τα ζωντανά εφέ, οι εξαγωγείς και οι εισαγωγείς κρατούν τον δικό τους. New type takes this language while Document Setup's language is English: USA; type already in a document keeps its own language. Το νέο κείμενο παίρνει αυτήν τη γλώσσα όσο η γλώσσα στη Ρύθμιση εγγράφου είναι Αγγλικά: ΗΠΑ· το κείμενο που υπάρχει ήδη σε ένα έγγραφο κρατά τη δική του γλώσσα. In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its language or case. Σε παραγράφους με ενεργό τον Συλλαβισμό, μια λέξη της λίστας χωρίζεται μόνο στα ενωτικά που έχουν πληκτρολογηθεί σε αυτήν ή πουθενά αν δεν έχει, ανεξάρτητα από τη γλώσσα ή τα πεζά-κεφαλαία της. On the desktop, the .wasm plug-ins in this folder load at startup and when you click OK with a new folder here, except in Safe Mode; the web version does not load them. Στην έκδοση για υπολογιστή, τα πρόσθετα .wasm αυτού του φακέλου φορτώνονται κατά την εκκίνηση και όταν κάνετε κλικ στο Εντάξει με νέο φάκελο εδώ, εκτός από την Ασφαλή λειτουργία· η έκδοση web δεν τα φορτώνει. + Normal keeps each plug-in's own limits; with Large, a plug-in filter or command may run at least 250 million instructions besides those for its input. The time limit stays the same. Το Κανονική διατηρεί τα δικά όρια κάθε επέκτασης· με το Μεγάλο, ένα φίλτρο ή μια εντολή επέκτασης μπορεί να εκτελέσει τουλάχιστον 250 εκατομμύρια εντολές επιπλέον εκείνων για την είσοδό του. Το χρονικό όριο μένει το ίδιο. How many instructions each run of a plug-in object filter may use; Large allows more than Normal with the same 60-second limit. Heavy filters keep their own budget. Πόσες εντολές μπορεί να χρησιμοποιεί κάθε εκτέλεση φίλτρου αντικειμένων επέκτασης· το Μεγάλο επιτρέπει περισσότερες από το Κανονική, με το ίδιο όριο 60 δευτερολέπτων. Τα βαριά φίλτρα κρατούν το δικό τους όριο. The first scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. Η πρώτη επιλογή δίσκου προσωρινής αποθήκευσης: Startup, None ή διαδρομή φακέλου· το VectorCraft την αποθηκεύει, αλλά δεν χρησιμοποιεί ακόμη δίσκους προσωρινής αποθήκευσης. The second scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. Η δεύτερη επιλογή δίσκου προσωρινής αποθήκευσης: Startup, None ή διαδρομή φακέλου· το VectorCraft την αποθηκεύει, αλλά δεν χρησιμοποιεί ακόμη δίσκους προσωρινής αποθήκευσης. @@ -4207,13 +4244,15 @@ digits Malayalam Μαλαγιάλαμ Shows each tool group's name above its tools in the toolbar; off, the groups follow one another with nothing between them. Εμφανίζει το όνομα κάθε ομάδας εργαλείων πάνω από τα εργαλεία της στη γραμμή εργαλείων· όταν είναι ανενεργό, οι ομάδες ακολουθούν η μία την άλλη χωρίς τίποτα ανάμεσα. From now on, documents you open or create open as tabs; off, each opens in a floating window. Documents already open stay where they are. Από εδώ και πέρα, τα έγγραφα που ανοίγετε ή δημιουργείτε ανοίγουν σε καρτέλες· όταν είναι ανενεργό, το καθένα ανοίγει σε αιωρούμενο παράθυρο. Τα ήδη ανοιχτά έγγραφα μένουν εκεί που είναι. Makes the document tabs taller and their names larger. Κάνει τις καρτέλες των εγγράφων ψηλότερες και τα ονόματά τους μεγαλύτερα. - From the next start, the system draws the window's title bar where VectorCraft would otherwise draw its own. Από την επόμενη εκκίνηση, το σύστημα σχεδιάζει τη γραμμή τίτλου του παραθύρου εκεί όπου αλλιώς το VectorCraft θα σχεδίαζε τη δική του. - From the next start, VectorCraft draws the window's title bar even where the desktop would draw it, unless System Title Bar is on. Από την επόμενη εκκίνηση, το VectorCraft σχεδιάζει τη γραμμή τίτλου του παραθύρου ακόμη κι εκεί όπου θα τη σχεδίαζε η επιφάνεια εργασίας, εκτός αν είναι ενεργή η Γραμμή τίτλου συστήματος. + From the next start, the system draws the window's title bar where VectorCraft would otherwise draw its own; on Linux and the BSDs, the VECTORCRAFT_TITLEBAR variable takes precedence. Από την επόμενη εκκίνηση, το σύστημα σχεδιάζει τη γραμμή τίτλου του παραθύρου εκεί όπου αλλιώς το VectorCraft θα σχεδίαζε τη δική του· σε Linux και BSD προηγείται η μεταβλητή VECTORCRAFT_TITLEBAR. + From the next start, VectorCraft draws the window's title bar even where the desktop would draw it, unless System Title Bar is on or the VECTORCRAFT_TITLEBAR variable chooses it. Από την επόμενη εκκίνηση, το VectorCraft σχεδιάζει τη γραμμή τίτλου ακόμη κι εκεί όπου θα τη σχεδίαζε η επιφάνεια εργασίας, εκτός αν είναι ενεργή η Γραμμή τίτλου συστήματος ή την επιλέγει η μεταβλητή VECTORCRAFT_TITLEBAR. Makes the interface larger or smaller; art on the canvas keeps its size at the same zoom. Μεγαλώνει ή μικραίνει το περιβάλλον χρήστη· το έργο στον καμβά κρατά το μέγεθός του στο ίδιο ζουμ. The tool pointers VectorCraft draws grow and shrink with UI Scaling; off, they keep their size. Οι δείκτες εργαλείων που σχεδιάζει το VectorCraft μεγαλώνουν και μικραίνουν με την Κλιμάκωση περιβάλλοντος χρήστη· όταν είναι ανενεργό, κρατούν το μέγεθός τους. The language of the interface; Auto uses the system's language. The dialog switches language as soon as you choose one. Η γλώσσα του περιβάλλοντος χρήστη· το Αυτόματα χρησιμοποιεί τη γλώσσα του συστήματος. Ο διάλογος αλλάζει γλώσσα μόλις επιλέξετε μία. Animated Zoom works only while this is on; off, Animated Zoom is dimmed and zooming does not animate. Η Κινούμενη μεγέθυνση λειτουργεί μόνο όσο αυτό είναι ενεργό· όταν είναι ανενεργό, η Κινούμενη μεγέθυνση είναι αχνή και η μεγέθυνση δεν κινείται. The wheel's zoom glides in, and the Zoom tool zooms as you drag sideways or hold it down; off, the Zoom tool zooms to the area you drag across. Η μεγέθυνση με τον τροχό γλιστρά ομαλά, και το εργαλείο Μεγέθυνση μεγεθύνει καθώς σύρετε στο πλάι ή το κρατάτε πατημένο· όταν είναι ανενεργό, μεγεθύνει στην περιοχή που σύρετε. + From the next start, the desktop version shows the canvas through this kind of graphics processor; the artwork is drawn on the CPU either way. Automatic prefers the integrated one on Windows and macOS. The web version does not use it. Από την επόμενη εκκίνηση, η έκδοση για υπολογιστή εμφανίζει τον καμβά μέσω αυτού του είδους επεξεργαστή γραφικών· το έργο σχεδιάζεται πάντα στη CPU. Το Αυτόματο προτιμά τον ενσωματωμένο σε Windows και macOS. Η έκδοση web δεν το χρησιμοποιεί. + From the next start, the window shows each frame without waiting for the display's refresh where the graphics driver allows, at most 240 frames a second. Από την επόμενη εκκίνηση, το παράθυρο εμφανίζει κάθε καρέ χωρίς να περιμένει την ανανέωση της οθόνης, όπου το επιτρέπει το πρόγραμμα οδήγησης γραφικών, έως 240 καρέ το δευτερόλεπτο. From the next start, the desktop version draws with this kind of graphics processor; Automatic prefers the one that drives the display. The web version does not use it. Από την επόμενη εκκίνηση, η έκδοση για υπολογιστή σχεδιάζει με αυτό το είδος επεξεργαστή γραφικών· το Αυτόματο προτιμά αυτόν που οδηγεί την οθόνη. Η έκδοση web δεν το χρησιμοποιεί. From the next start, the window shows frames without waiting for the display to refresh, at most 240 a second; off, the display paces them. A present mode set at launch overrides it. Από την επόμενη εκκίνηση, το παράθυρο δείχνει τα καρέ χωρίς αναμονή για ανανέωση της οθόνης, έως 240 το δευτερόλεπτο· ανενεργό, τα ρυθμίζει η οθόνη. Υπερισχύει η λειτουργία που ορίζεται στην εκκίνηση. The most undo steps each document keeps; lowering it drops the oldest steps when you click OK. Steps can also go sooner when they use too much memory. Τα περισσότερα βήματα αναίρεσης που κρατά κάθε έγγραφο· μικρότερος αριθμός αφαιρεί τα παλαιότερα βήματα όταν κάνετε κλικ στο Εντάξει. Βήματα μπορεί να φύγουν και νωρίτερα αν πιάνουν πολλή μνήμη. @@ -4232,6 +4271,9 @@ digits Malayalam Μαλαγιάλαμ Open Recent Files and the Home screen list at most this many recent files; 0 lists none, and VectorCraft still remembers up to 30. Το Άνοιγμα πρόσφατων αρχείων και η Αρχική οθόνη δείχνουν το πολύ τόσα πρόσφατα αρχεία· το 0 δεν δείχνει κανένα, και το VectorCraft θυμάται ακόμη έως 30. When a document opens, a linked EPS image that shows its saved preview keeps it instead of reading the EPS file again; changed files still follow Update Links. Όταν ανοίγει ένα έγγραφο, μια συνδεδεμένη εικόνα EPS που δείχνει την αποθηκευμένη προεπισκόπησή της την κρατά αντί να διαβάσει ξανά το αρχείο EPS· τα αλλαγμένα αρχεία ακολουθούν πάντα την Ενημέρωση συνδέσμων. In Pixel Preview, images are drawn smoothed; off, their pixels show with hard edges. Outside Pixel Preview, images are always smoothed. Στην Προεπισκόπηση εικονοστοιχείων οι εικόνες σχεδιάζονται εξομαλυμένες· όταν είναι ανενεργό, τα εικονοστοιχεία τους έχουν αιχμηρές άκρες. Εκτός Προεπισκόπησης εικονοστοιχείων οι εικόνες εξομαλύνονται πάντα. + PDF Text Κείμενο PDF + The text of a PDF you open or embed comes in as editable type, or as outlines that look the same on a computer without its fonts. Το κείμενο ενός PDF που ανοίγετε ή ενσωματώνετε εισάγεται ως επεξεργάσιμο κείμενο ή ως περιγράμματα που φαίνονται ίδια σε υπολογιστή χωρίς τις γραμματοσειρές του. + Linked pages show the file's own text. Οι συνδεδεμένες σελίδες δείχνουν το κείμενο του ίδιου του αρχείου. When a linked file changes, Automatically reads it again, Ask When Modified asks you first, and Manually leaves it and shows a note in the status bar. Όταν αλλάζει ένα συνδεδεμένο αρχείο, το Αυτόματα το διαβάζει ξανά, το Ερώτηση όταν τροποποιηθεί σας ρωτά πρώτα και το Χειροκίνητα το αφήνει ως έχει και δείχνει μια σημείωση στη γραμμή κατάστασης. On the desktop, the folder New from Template… and Save as Template… start in; leave it blank for VectorCraft Templates in your documents folder. Στην έκδοση για υπολογιστή, ο φάκελος όπου ξεκινούν το Νέο από πρότυπο… και η Αποθήκευση ως πρότυπο…· αφήστε τον κενό για το VectorCraft Templates στον φάκελο εγγράφων σας. Edit Original opens a linked file in the system's default app for its type; off, a linked raster image opens in PhotoCraft where it is installed. Η Επεξεργασία πρωτοτύπου ανοίγει ένα συνδεδεμένο αρχείο στην προεπιλεγμένη εφαρμογή του συστήματος για τον τύπο του· όταν είναι ανενεργό, μια συνδεδεμένη εικόνα raster ανοίγει στο PhotoCraft, αν είναι εγκατεστημένο. @@ -4246,7 +4288,6 @@ digits Malayalam Μαλαγιάλαμ Output All Blacks as Rich Black draws pure CMYK black as RGB black in RGB and grayscale raster exports and Print as Bitmap; it does not change vector exports, CMYK JPEG, TIFF and PSD, or other printing. Η Απόδοση όλων των μαύρων ως πλούσιο μαύρο σχεδιάζει το καθαρό μαύρο CMYK ως μαύρο RGB στις εξαγωγές raster RGB και κλίμακας του γκρι και με την Εκτύπωση ως bitmap· δεν αλλάζει τις διανυσματικές εξαγωγές, τα CMYK JPEG, TIFF και PSD ή την άλλη εκτύπωση. On a touch screen, switches to the Touch workspace; turning this off, or losing the touch screen, goes back to the workspace it switched from. Σε οθόνη αφής μεταβαίνει στον χώρο εργασίας αφής· η απενεργοποίηση ή η απώλεια της οθόνης αφής επαναφέρει τον χώρο εργασίας που υπήρχε πριν. A two-finger tap on the canvas undoes, or switches between selection and drawing tools in the Touch workspace, and a three-finger tap redoes; neither works in Presentation Mode. Το πάτημα με δύο δάχτυλα στον καμβά κάνει αναίρεση ή, στον χώρο εργασίας αφής, εναλλάσσει εργαλεία επιλογής και σχεδίασης, και το πάτημα με τρία δάχτυλα κάνει επανάληψη· κανένα δεν λειτουργεί στη λειτουργία παρουσίασης. - New type takes this language while Document Setup's language is English: USA and [Normal Character Style] sets none; type already in a document keeps its own language. Το νέο κείμενο παίρνει αυτήν τη γλώσσα όσο η γλώσσα στη Ρύθμιση εγγράφου είναι Αγγλικά: ΗΠΑ και το [Κανονικό στυλ χαρακτήρων] δεν ορίζει γλώσσα· το κείμενο που υπάρχει ήδη σε ένα έγγραφο κρατά τη δική του γλώσσα. In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its case; Korean words take no hyphen, and Indian-language words do not break inside a character cluster. Με Συλλαβισμό, μια λέξη της λίστας χωρίζεται μόνο στα ενωτικά της ή πουθενά αν δεν έχει, με πεζά ή κεφαλαία· οι κορεατικές λέξεις δεν παίρνουν ενωτικό, οι λέξεις ινδικών γλωσσών δεν χωρίζονται μέσα σε ομάδα χαρακτήρων. Reset all preferences to their defaults? Επαναφορά όλων των προτιμήσεων στις προεπιλογές τους; The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. Οι προεπιλογές εφαρμόζονται όταν κάνετε κλικ στο Εντάξει στις Προτιμήσεις. Το Ακύρωση εκεί διατηρεί τις τρέχουσες προτιμήσεις σας. @@ -4376,6 +4417,7 @@ digits Malayalam Μαλαγιάλαμ Recent Commands Πρόσφατες εντολές No recent commands Δεν υπάρχουν πρόσφατες εντολές Type to search commands, tools, panels and effects Πληκτρολογήστε για αναζήτηση εντολών, εργαλείων, πλαισίων και εφέ + Clear Recent Commands Εκκαθάριση πρόσφατων εντολών Search commands Αναζήτηση εντολών Search Commands… Αναζήτηση εντολών… Secondary Δευτερεύον @@ -5540,6 +5582,10 @@ digits Malayalam Μαλαγιάλαμ @msg this trace would make more than {max} anchor points, more than the document can show smoothly: raise Noise, lower Paths or Colors, or pick a lower-fidelity preset αυτή η διανυσματοποίηση θα δημιουργούσε πάνω από {max} σημεία αγκύρωσης, περισσότερα από όσα μπορεί να εμφανίσει ομαλά το έγγραφο: αυξήστε τον Θόρυβο, μειώστε τις Διαδρομές ή τα Χρώματα ή επιλέξτε προεπιλογή χαμηλότερης πιστότητας @msg select an envelope επιλέξτε περίβλημα @msg select an image επιλέξτε εικόνα +@msg object {_1} is an image changed by Perspective Distort or Free Distort, which this command does not work on το αντικείμενο {_1} είναι εικόνα που άλλαξε με Παραμόρφωση προοπτικής ή Ελεύθερη παραμόρφωση, στην οποία δεν λειτουργεί αυτή η εντολή +@msg image {_1} cannot be distorted this way: its corners would not make a convex shape η εικόνα {_1} δεν μπορεί να παραμορφωθεί έτσι: οι γωνίες της δεν θα σχημάτιζαν κυρτό σχήμα +@msg image {_1} cannot be distorted this way: its corners would cross the warp's horizon η εικόνα {_1} δεν μπορεί να παραμορφωθεί έτσι: οι γωνίες της θα περνούσαν τον ορίζοντα της παραμόρφωσης +@msg image {_1} cannot be distorted this way: its corners would be too close together for a perspective map η εικόνα {_1} δεν μπορεί να παραμορφωθεί έτσι: οι γωνίες της θα ήταν πολύ κοντά μεταξύ τους για προοπτική απεικόνιση @msg `background` must be edges, corners or colors το `background` πρέπει να είναι edges, corners ή colors @msg `match` must be distance or channels το `match` πρέπει να είναι distance ή channels @msg `{key}` must be from 0 to 100 το `{key}` πρέπει να είναι από 0 έως 100 @@ -6215,7 +6261,10 @@ variable-list-end {0}, {1} {0} και {1} @msg the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate) το αντικείμενο δεν έχει εφέ 3D (Εξώθηση και λοξότμηση, Περιστροφή γύρω από άξονα, Φούσκωμα ή Περιστροφή) @msg `render` must be an object holding only `mode`, set to shaded or wireframe το `render` πρέπει να είναι αντικείμενο που περιέχει μόνο `mode`, με τιμή shaded ή wireframe @msg its 3D effect builds no solid το εφέ 3D του δεν δημιουργεί στερεό -@msg bevel must be none or one of {_1} το bevel πρέπει να είναι none ή ένα από τα {_1} +@msg bevel must be none or one of {_1}, or custom with {BEVEL_PROFILE} το bevel πρέπει να είναι none, ένα από τα {_1} ή custom με {BEVEL_PROFILE} +@msg bevel custom needs {BEVEL_PROFILE}, the bevel's points το bevel custom χρειάζεται το {BEVEL_PROFILE}, τα σημεία της λοξότμησης +@msg {BEVEL_NAME} must be a string το {BEVEL_NAME} πρέπει να είναι συμβολοσειρά +@msg {BEVEL_PROFILE} must be 2 to {most} [x, y] points, each share between 0 and 1, from [0, 0] (the cap's edge) to [1, 1] (the side wall) το {BEVEL_PROFILE} πρέπει να έχει 2 έως {most} σημεία [x, y], κάθε αναλογία μεταξύ 0 και 1, από [0, 0] (η ακμή της ακραίας όψης) έως [1, 1] (το πλευρικό τοίχωμα) @msg {_1} can't build solids from this art: its symbol instances, blends and clipping groups hold too many objects {_1}: δεν μπορούν να δημιουργηθούν στερεά από αυτό το σχέδιο· οι παρουσίες συμβόλων, οι αναμείξεις και οι ομάδες αποκοπής του περιέχουν πάρα πολλά αντικείμενα @msg {label} can't build a solid from the instance of symbol "{symbol}": the symbol's art isn't available {label}: δεν μπορεί να δημιουργηθεί στερεό από την παρουσία του συμβόλου «{symbol}»· το σχέδιο του συμβόλου δεν είναι διαθέσιμο @msg {_1}: the clipping path is too complex to cut the art with {_1}: η διαδρομή αποκοπής είναι πολύ σύνθετη για να κόψει το σχέδιο @@ -6985,6 +7034,8 @@ effect Points Σημεία @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe το `mode` πρέπει να είναι grayscale, rgb, hsb, cmyk ή websafe @msg `view` must be wheel or box το `view` πρέπει να είναι wheel ή box @msg `channel` must be hue, saturation, brightness, red, green or blue το `channel` πρέπει να είναι hue, saturation, brightness, red, green ή blue +@msg `sliders` must be none, oklch or hsl Το `sliders` πρέπει να είναι none, oklch ή hsl +@msg OKLCH needs sRGB as the working RGB space Το OKLCH απαιτεί sRGB ως χώρο εργασίας RGB @msg `{key}` must be an array of these names: {_1} το `{key}` πρέπει να είναι πίνακας με αυτά τα ονόματα: {_1} @msg choose a destination folder επιλέξτε φάκελο προορισμού @msg choose a source folder επιλέξτε φάκελο προέλευσης @@ -8897,6 +8948,20 @@ breakText Glyphs Γλύφοι @msg A joint does not close by {gap} pt. Μια ένωση δεν κλείνει κατά {gap} pt. @msg Two panels pass through each other. Δύο πάνελ διαπερνούν το ένα το άλλο. @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" το composer πρέπει να είναι "singleLine", "everyLine", "standardSingleLine" ή "standardEveryLine" + Vector Packs Διανυσματικά πακέτα + Compass Rose Ρόδο πυξίδας + Botanical Sprig Βοτανικό κλαδάκι + Facet Diamond Πολυεδρικό διαμάντι + Tide Crest Κορυφή κύματος + Leaf Vine Κληματίδα φύλλων + Blossom Chain Αλυσίδα λουλουδιών + Pennant Garland Γιρλάντα σημαιών + Lantern String Σειρά φαναριών + Orbit Lines Τροχιακές γραμμές + Petal Garland Γιρλάντα πετάλων + Lattice Braid Πλεξούδα πλέγματος + Facet Sweep Πολυεδρική πινελιά + Artistic Brushes Καλλιτεχνικά πινέλα Paint Ζωγραφική Flat Sweep Επίπεδη πινελιά Dry Drag Στεγνό σύρσιμο diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index ac18b080ce..91c9c4e676 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -507,6 +507,10 @@ font-technology Variable Variables Cusp Cúspide Straight segment Segmento recto Circle too large Círculo demasiado grande + Show Radii Mostrar radios + Show Diameter Mostrar diámetro + Anchors at Standard Positions Puntos de ancla en posiciones estándar + Third Point by Dragging Tercer punto arrastrando Classic Defaults Valores predeterminados clásicos Clean Up… Limpiar… Clear Borrar @@ -610,9 +614,14 @@ font-technology Variable Variables {name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2} Wheel View Vista de rueda Box View Vista de cuadro + Show Out-of-Gamut Colors Mostrar colores fuera de gama Box Channel Canal del cuadro Color box Cuadro de color Color Wheel Options Opciones de la rueda de color + Show Document Colors Mostrar colores del documento + Document Colors Colores del documento + Selection Colors Colores de la selección +@plural Used {n} time|Used {n} times Usado {n} vez|Usado {n} veces Show Harmony Mostrar armonía Harmony Rule Regla de armonía Harmony color Color de la armonía @@ -656,6 +665,8 @@ font-technology Variable Variables Contextual Task Bar Barra de tareas contextual Pin Bar Position Fijar posición de la barra Reset Bar Position Restablecer posición de la barra + Bar Actions Acciones de la barra + Reset Bar Actions Restablecer acciones de la barra Resize Cambiar tamaño Contrast Contraste Control Control @@ -1906,6 +1917,10 @@ font-technology Variable Variables Rename Preset Cambiar nombre del preajuste Save Image Trace Preset Guardar preajuste de calco de imagen Delete Image Trace Preset Eliminar preajuste de calco de imagen + Tracing Presets… Preajustes de calco… + Import Image Trace Presets Importar preajustes de calco de imagen + Export Image Trace Presets Exportar preajustes de calco de imagen + Replace the saved presets that have these names? ¿Reemplazar los preajustes guardados que tienen estos nombres? Image Trace Presets Preajustes de calco de imagen Image: Imagen: Images: Imágenes: @@ -2037,6 +2052,11 @@ font-technology Variable Variables Knife Cuchilla Knockout Group Grupo de exclusión Lab Lab + OKLCH Sliders Controles deslizantes OKLCH + HSL Sliders Controles deslizantes HSL + Chroma Croma + The largest chroma sRGB holds at this lightness and hue El croma más alto que admite sRGB con esta luminosidad y este tono + OKLCH needs sRGB as the working RGB space OKLCH necesita sRGB como espacio de trabajo RGB Lab Spot Colors: Tintas planas Lab: Lab Values Valores Lab Landscape Horizontal @@ -2797,6 +2817,13 @@ font-technology Variable Variables Pen Tool Herramienta Pluma Quick Pen Tool Herramienta Pluma rápida Quick Pen Pluma rápida + Quick Pen Toolbar Barra de herramientas de Pluma rápida + Continuous Arc Arco continuo + Sharp Corner Arc Arco de esquina aguda + Flip Arc Voltear arco + Hide Toolbar Ocultar barra de herramientas + Pin Toolbar Position Fijar posición de la barra de herramientas + Reset Toolbar Position Restablecer posición de la barra de herramientas Pencil Lápiz Pencil Tool Herramienta Lápiz per slice por sector @@ -3240,6 +3267,11 @@ digits Malayalam Malayálam Edit Arrowheads Editar puntas de flecha Edit Arrowheads… Editar puntas de flecha… Reload Arrowheads Volver a cargar puntas de flecha + Bevels Biseles + Edit Bevels Editar biseles + Edit Bevels… Editar biseles… + {name} (document) {name} (documento) + Reload Bevels Volver a cargar biseles Reset Rotate View Restablecer rotación de vista Rotate View to Selection Rotar vista según la selección Reset the rows to the artwork's colors Restablecer las filas a los colores de la ilustración @@ -3377,9 +3409,14 @@ digits Malayalam Malayálam Edit type set in fonts that aren't available? ¿Editar el texto en fuentes que no están disponibles? Shows each slice's number in a box at its top left on the canvas; off, the slice outlines still show. Muestra en el lienzo el número de cada sector en un recuadro en su esquina superior izquierda; si está desactivado, los contornos de los sectores siguen visibles. The color of user and object slice outlines and their number boxes; auto slices use a dimmer shade of it. El color de los contornos de los sectores de usuario y de objeto y de los recuadros con su número; los sectores automáticos usan un tono más apagado de ese color. + New type takes this language while Document Setup's language is English: USA and [Normal Character Style] sets none; type already in a document keeps its own language. El texto nuevo toma este idioma mientras el idioma de Ajustar documento sea Inglés: Estados Unidos y [Estilo de carácter normal] no defina ninguno; el texto que ya está en un documento conserva su idioma. + In paragraphs with Hyphenate on, a listed word is hyphenated only at the hyphens typed in it, or never when it has none, whatever its language or case. En los párrafos con Separar con guiones activado, una palabra de la lista solo recibe guion de separación en los guiones escritos en ella, o nunca si no tiene, sea cual sea su idioma o uso de mayúsculas. + On the desktop, this folder's .wasm plug-ins load at startup and when OK sets a new folder, except in Safe Mode; one that asks for permissions loads only after you grant them. The web version loads none. En la versión de escritorio, los plugins .wasm de esta carpeta se cargan al iniciar y cuando Aceptar fija una carpeta nueva, salvo en Modo seguro; uno que pide permisos solo se carga después de que los concedas. La versión web no carga ninguno. + Large gives each filter or command plug-in run at least 250 million instructions, with the same time limit; Normal keeps the plug-in's own budget. Live effects, exporters and importers keep theirs. Grande da a cada ejecución de un plugin de filtro o de comando al menos 250 millones de instrucciones, con el mismo límite de tiempo; Normal mantiene el presupuesto propio del plugin. Los efectos en vivo, exportadores e importadores mantienen el suyo. New type takes this language while Document Setup's language is English: USA; type already in a document keeps its own language. El texto nuevo toma este idioma mientras el idioma de Ajustar documento sea Inglés: Estados Unidos; el texto que ya está en un documento conserva su idioma. In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its language or case. En los párrafos con Separar con guiones activado, una palabra de la lista se divide solo en los guiones escritos en ella, o en ningún punto si no tiene, sea cual sea su idioma o uso de mayúsculas. On the desktop, the .wasm plug-ins in this folder load at startup and when you click OK with a new folder here, except in Safe Mode; the web version does not load them. En la versión de escritorio, los plugins .wasm de esta carpeta se cargan al iniciar y al hacer clic en Aceptar con una carpeta nueva aquí, salvo en Modo seguro; la versión web no los carga. + Normal keeps each plug-in's own limits; with Large, a plug-in filter or command may run at least 250 million instructions besides those for its input. The time limit stays the same. Normal mantiene los límites propios de cada plugin; con Grande, un filtro o un comando de un plugin puede ejecutar al menos 250 millones de instrucciones además de las de su entrada. El límite de tiempo no cambia. How many instructions each run of a plug-in object filter may use; Large allows more than Normal with the same 60-second limit. Heavy filters keep their own budget. Cuántas instrucciones puede usar cada ejecución de un filtro de objetos de un plugin; Grande permite más que Normal con el mismo límite de 60 segundos. Los filtros pesados conservan su propio presupuesto. The first scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. La primera opción de disco de memoria virtual: Startup, None o la ruta de una carpeta; VectorCraft la guarda, pero aún no usa discos de memoria virtual. The second scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. La segunda opción de disco de memoria virtual: Startup, None o la ruta de una carpeta; VectorCraft la guarda, pero aún no usa discos de memoria virtual. @@ -3391,13 +3428,15 @@ digits Malayalam Malayálam Shows each tool group's name above its tools in the toolbar; off, the groups follow one another with nothing between them. Muestra el nombre de cada grupo de herramientas encima de sus herramientas en la barra de herramientas; desactivado, los grupos se suceden sin nada entre ellos. From now on, documents you open or create open as tabs; off, each opens in a floating window. Documents already open stay where they are. A partir de ahora, los documentos que abra o cree se abren como pestañas; desactivado, cada uno se abre en una ventana flotante. Los documentos ya abiertos se quedan donde están. Makes the document tabs taller and their names larger. Hace más altas las pestañas de los documentos y más grandes sus nombres. - From the next start, the system draws the window's title bar where VectorCraft would otherwise draw its own. A partir del próximo inicio, el sistema dibuja la barra de título de la ventana donde, si no, VectorCraft dibujaría la suya. - From the next start, VectorCraft draws the window's title bar even where the desktop would draw it, unless System Title Bar is on. A partir del próximo inicio, VectorCraft dibuja la barra de título de la ventana incluso donde la dibujaría el escritorio, salvo que Barra de título del sistema esté activada. + From the next start, the system draws the window's title bar where VectorCraft would otherwise draw its own; on Linux and the BSDs, the VECTORCRAFT_TITLEBAR variable takes precedence. A partir del próximo inicio, el sistema dibuja la barra de título de la ventana donde, si no, VectorCraft dibujaría la suya; en Linux y los BSD, la variable VECTORCRAFT_TITLEBAR tiene prioridad. + From the next start, VectorCraft draws the window's title bar even where the desktop would draw it, unless System Title Bar is on or the VECTORCRAFT_TITLEBAR variable chooses it. A partir del próximo inicio, VectorCraft dibuja la barra de título de la ventana incluso donde la dibujaría el escritorio, salvo que Barra de título del sistema esté activada o la variable VECTORCRAFT_TITLEBAR la elija. Makes the interface larger or smaller; art on the canvas keeps its size at the same zoom. Agranda o reduce la interfaz; el arte del lienzo conserva su tamaño con el mismo zoom. The tool pointers VectorCraft draws grow and shrink with UI Scaling; off, they keep their size. Los punteros de herramienta que dibuja VectorCraft crecen y se reducen con la Escala de la interfaz; desactivado, conservan su tamaño. The language of the interface; Auto uses the system's language. The dialog switches language as soon as you choose one. El idioma de la interfaz; Auto usa el idioma del sistema. El cuadro de diálogo cambia de idioma en cuanto elige uno. Animated Zoom works only while this is on; off, Animated Zoom is dimmed and zooming does not animate. El Zoom animado solo funciona mientras esto está activado; desactivado, el Zoom animado aparece atenuado y el zoom no se anima. The wheel's zoom glides in, and the Zoom tool zooms as you drag sideways or hold it down; off, the Zoom tool zooms to the area you drag across. El zoom con la rueda se desliza suavemente, y la Herramienta Zoom amplía mientras arrastra de lado o la mantiene pulsada; desactivado, la Herramienta Zoom amplía el área que arrastra. + From the next start, the desktop version shows the canvas through this kind of graphics processor; the artwork is drawn on the CPU either way. Automatic prefers the integrated one on Windows and macOS. The web version does not use it. A partir del próximo inicio, la versión de escritorio muestra el lienzo a través de este tipo de procesador gráfico; la ilustración siempre se dibuja en la CPU. Automático prefiere el integrado en Windows y macOS. La versión web no lo usa. + From the next start, the window shows each frame without waiting for the display's refresh where the graphics driver allows, at most 240 frames a second. A partir del próximo inicio, la ventana muestra cada fotograma sin esperar la actualización de la pantalla cuando el controlador gráfico lo permite, con un máximo de 240 fotogramas por segundo. From the next start, the desktop version draws with this kind of graphics processor; Automatic prefers the one that drives the display. The web version does not use it. A partir del próximo inicio, la versión de escritorio dibuja con este tipo de procesador gráfico; Automático prefiere el que controla la pantalla. La versión web no lo usa. From the next start, the window shows frames without waiting for the display to refresh, at most 240 a second; off, the display paces them. A present mode set at launch overrides it. A partir del próximo inicio, la ventana muestra los fotogramas sin esperar a que la pantalla se actualice, como máximo 240 por segundo; desactivado, la pantalla marca el ritmo. Un modo de presentación definido al iniciar tiene prioridad. The most undo steps each document keeps; lowering it drops the oldest steps when you click OK. Steps can also go sooner when they use too much memory. El máximo de pasos de deshacer que conserva cada documento; un número menor quita los pasos más antiguos al hacer clic en Aceptar. Los pasos también pueden irse antes si ocupan demasiada memoria. @@ -3416,6 +3455,9 @@ digits Malayalam Malayálam Open Recent Files and the Home screen list at most this many recent files; 0 lists none, and VectorCraft still remembers up to 30. Abrir archivos recientes y la pantalla de Inicio muestran como máximo este número de archivos recientes; 0 no muestra ninguno, y VectorCraft sigue recordando hasta 30. When a document opens, a linked EPS image that shows its saved preview keeps it instead of reading the EPS file again; changed files still follow Update Links. Al abrir un documento, una imagen EPS vinculada que muestra su vista previa guardada la conserva en lugar de volver a leer el archivo EPS; los archivos modificados siguen Actualizar vínculos. In Pixel Preview, images are drawn smoothed; off, their pixels show with hard edges. Outside Pixel Preview, images are always smoothed. En Vista previa de píxeles, las imágenes se dibujan suavizadas; desactivado, sus píxeles muestran bordes duros. Fuera de Vista previa de píxeles, las imágenes siempre se suavizan. + PDF Text Texto de PDF + The text of a PDF you open or embed comes in as editable type, or as outlines that look the same on a computer without its fonts. El texto de un PDF que abre o incrusta entra como texto editable o como contornos que se ven igual en un equipo sin sus fuentes. + Linked pages show the file's own text. Las páginas vinculadas muestran el texto propio del archivo. When a linked file changes, Automatically reads it again, Ask When Modified asks you first, and Manually leaves it and shows a note in the status bar. Cuando un archivo vinculado cambia, Automáticamente lo vuelve a leer, Preguntar al modificar le pregunta primero, y Manualmente lo deja como está y muestra un aviso en la barra de estado. On the desktop, the folder New from Template… and Save as Template… start in; leave it blank for VectorCraft Templates in your documents folder. En la versión de escritorio, la carpeta en la que empiezan Nuevo a partir de plantilla… y Guardar como plantilla…; déjela vacía para VectorCraft Templates en su carpeta de documentos. Edit Original opens a linked file in the system's default app for its type; off, a linked raster image opens in PhotoCraft where it is installed. Editar original abre un archivo vinculado en la aplicación predeterminada del sistema para su tipo; desactivado, una imagen rasterizada vinculada se abre en PhotoCraft si está instalado. @@ -3430,7 +3472,6 @@ digits Malayalam Malayálam Output All Blacks as Rich Black draws pure CMYK black as RGB black in RGB and grayscale raster exports and Print as Bitmap; it does not change vector exports, CMYK JPEG, TIFF and PSD, or other printing. Imprimir todos los negros como negro enriquecido dibuja el negro CMYK puro como negro RGB en las exportaciones ráster RGB y en escala de grises y con Imprimir como mapa de bits; no cambia las exportaciones vectoriales, los JPEG, TIFF y PSD CMYK ni otras impresiones. On a touch screen, switches to the Touch workspace; turning this off, or losing the touch screen, goes back to the workspace it switched from. En una pantalla táctil, cambia al espacio de trabajo táctil; al desactivarlo o dejar de detectarse la pantalla táctil, vuelve al espacio de trabajo anterior al cambio. A two-finger tap on the canvas undoes, or switches between selection and drawing tools in the Touch workspace, and a three-finger tap redoes; neither works in Presentation Mode. Un toque con dos dedos en el lienzo deshace o, en el espacio de trabajo táctil, alterna entre herramientas de selección y de dibujo, y un toque con tres dedos rehace; ninguno funciona en el modo de presentación. - New type takes this language while Document Setup's language is English: USA and [Normal Character Style] sets none; type already in a document keeps its own language. El texto nuevo toma este idioma mientras el idioma de Ajustar documento sea Inglés: Estados Unidos y [Estilo de carácter normal] no defina ninguno; el texto que ya está en un documento conserva su idioma. In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its case; Korean words take no hyphen, and Indian-language words do not break inside a character cluster. En los párrafos con Separar con guiones activado, una palabra de la lista se divide solo en los guiones escritos en ella, o en ningún punto si no tiene, sea cual sea su uso de mayúsculas; las palabras coreanas no llevan guion, y las palabras en lenguas indias no se dividen dentro de un grupo de caracteres. Reset all preferences to their defaults? ¿Restablecer todas las preferencias a sus valores predeterminados? The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. Los valores predeterminados se aplican al hacer clic en Aceptar en Preferencias. Cancelar ahí conserva sus preferencias actuales. @@ -3673,6 +3714,7 @@ digits Malayalam Malayálam Recent Commands Comandos recientes No recent commands No hay comandos recientes Type to search commands, tools, panels and effects Escriba para buscar comandos, herramientas, paneles y efectos + Clear Recent Commands Borrar comandos recientes Search commands Buscar comandos Search Commands… Buscar comandos… Secondary Secundario @@ -5184,6 +5226,8 @@ liquify-list-end {0}, {1} {0}, {1} @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` debe ser grayscale, rgb, hsb, cmyk o websafe @msg `view` must be wheel or box `view` debe ser wheel o box @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` debe ser hue, saturation, brightness, red, green o blue +@msg `sliders` must be none, oklch or hsl `sliders` debe ser none, oklch o hsl +@msg OKLCH needs sRGB as the working RGB space OKLCH necesita sRGB como espacio de trabajo RGB @msg `{k}` must be [x, y] `{k}` debe ser [x, y] @msg `{name}` has no options `{name}` no tiene opciones @msg `{name}` is a built-in workspace; choose another name `{name}` es un espacio de trabajo integrado; elige otro nombre @@ -5598,6 +5642,10 @@ liquify-list-end {0}, {1} {0}, {1} @msg this trace would make more than {max} anchor points, more than the document can show smoothly: raise Noise, lower Paths or Colors, or pick a lower-fidelity preset este calco crearía más de {max} puntos de ancla, más de los que el documento puede mostrar con fluidez: sube Ruido, baja Trazados o Colores, o elige un preajuste de menor fidelidad @msg select an envelope selecciona una envolvente @msg select an image selecciona una imagen +@msg object {_1} is an image changed by Perspective Distort or Free Distort, which this command does not work on el objeto {_1} es una imagen modificada con Distorsión de perspectiva o Distorsión libre, con la que este comando no funciona +@msg image {_1} cannot be distorted this way: its corners would not make a convex shape la imagen {_1} no se puede distorsionar así: sus esquinas no formarían una forma convexa +@msg image {_1} cannot be distorted this way: its corners would cross the warp's horizon la imagen {_1} no se puede distorsionar así: sus esquinas cruzarían el horizonte de la distorsión +@msg image {_1} cannot be distorted this way: its corners would be too close together for a perspective map la imagen {_1} no se puede distorsionar así: sus esquinas estarían demasiado juntas para una proyección en perspectiva @msg `background` must be edges, corners or colors `background` debe ser edges, corners o colors @msg `match` must be distance or channels `match` debe ser distance o channels @msg `{key}` must be from 0 to 100 `{key}` debe estar entre 0 y 100 @@ -6803,7 +6851,10 @@ mark-style Japanese Japonesas @msg the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate) el objeto no tiene ningún efecto 3D (Extrusión y biselado, Revolución, Inflar o Rotar) @msg `render` must be an object holding only `mode`, set to shaded or wireframe `render` debe ser un objeto que solo contenga `mode`, con el valor shaded o wireframe @msg its 3D effect builds no solid su efecto 3D no construye ningún sólido -@msg bevel must be none or one of {_1} bevel debe ser none o uno de estos: {_1} +@msg bevel must be none or one of {_1}, or custom with {BEVEL_PROFILE} bevel debe ser none, uno de estos: {_1}, o custom con {BEVEL_PROFILE} +@msg bevel custom needs {BEVEL_PROFILE}, the bevel's points bevel custom necesita {BEVEL_PROFILE}, los puntos del bisel +@msg {BEVEL_NAME} must be a string {BEVEL_NAME} debe ser una cadena +@msg {BEVEL_PROFILE} must be 2 to {most} [x, y] points, each share between 0 and 1, from [0, 0] (the cap's edge) to [1, 1] (the side wall) {BEVEL_PROFILE} debe tener de 2 a {most} puntos [x, y], cada proporción entre 0 y 1, desde [0, 0] (el borde de la tapa) hasta [1, 1] (la pared lateral) @msg {_1} can't build solids from this art: its symbol instances, blends and clipping groups hold too many objects {_1} no puede construir sólidos a partir de esta ilustración: sus instancias de símbolo, fusiones y grupos de recorte contienen demasiados objetos @msg {label} can't build a solid from the instance of symbol "{symbol}": the symbol's art isn't available {label} no puede construir un sólido a partir de la instancia del símbolo «{symbol}»: la ilustración del símbolo no está disponible @msg {_1}: the clipping path is too complex to cut the art with {_1}: el trazado de recorte es demasiado complejo para recortar la ilustración @@ -10641,6 +10692,20 @@ breakText Glyphs Glifos @msg A joint does not close by {gap} pt. Una unión no cierra por {gap} pt. @msg Two panels pass through each other. Dos paneles se atraviesan entre sí. @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer debe ser "singleLine", "everyLine", "standardSingleLine" o "standardEveryLine" + Vector Packs Paquetes vectoriales + Compass Rose Rosa de los vientos + Botanical Sprig Ramita botánica + Facet Diamond Diamante facetado + Tide Crest Cresta de ola + Leaf Vine Enredadera de hojas + Blossom Chain Cadena de flores + Pennant Garland Guirnalda de banderines + Lantern String Cadena de faroles + Orbit Lines Líneas orbitales + Petal Garland Guirnalda de pétalos + Lattice Braid Trenza reticular + Facet Sweep Trazo facetado + Artistic Brushes Pinceles artísticos Paint Pintura Flat Sweep Barrido plano Dry Drag Arrastre seco diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index c8ba66e8ab..7c337e3b0d 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -795,6 +795,8 @@ Contextual Task Bar Kontekstuaalinen tehtäväpalkki Pin Bar Position Kiinnitä palkin sijainti Reset Bar Position Palauta palkin sijainti + Bar Actions Palkin toiminnot + Reset Bar Actions Palauta palkin toiminnot Resize Muuta kokoa Tools Työkalut Toolbars Työkalurivit @@ -815,9 +817,14 @@ {name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2} Wheel View Ympyränäkymä Box View Ruutunäkymä + Show Out-of-Gamut Colors Näytä väriavaruuden ulkopuoliset värit Box Channel Ruudun kanava Color box Väriruutu Color Wheel Options Väriympyrän asetukset + Show Document Colors Näytä asiakirjan värit + Document Colors Asiakirjan värit + Selection Colors Valinnan värit +@plural Used {n} time|Used {n} times Käytetty {n} kerran|Käytetty {n} kertaa Show Harmony Näytä harmonia Harmony Rule Harmoniasääntö Harmony color Harmonian väri @@ -2094,6 +2101,10 @@ digits Malayalam Malajalam Rename Preset Nimeä esiasetus uudelleen Save Image Trace Preset Tallenna kuvan jäljityksen esiasetus Delete Image Trace Preset Poista kuvan jäljityksen esiasetus + Tracing Presets… Jäljityksen esiasetukset… + Import Image Trace Presets Tuo kuvan jäljityksen esiasetukset + Export Image Trace Presets Vie kuvan jäljityksen esiasetukset + Replace the saved presets that have these names? Korvataanko tallennetut esiasetukset, joilla on nämä nimet? Method: Menetelmä: Pad Jatka Repeats Toistokerrat @@ -4232,6 +4243,13 @@ theme Appearance Ulkoasu Pen Tool Kynätyökalu Quick Pen Tool Pikakynätyökalu Quick Pen Pikakynä + Quick Pen Toolbar Pikakynän työkalurivi + Continuous Arc Jatkuva kaari + Sharp Corner Arc Terävän kulman kaari + Flip Arc Käännä kaari + Hide Toolbar Piilota työkalurivi + Pin Toolbar Position Kiinnitä työkalurivin sijainti + Reset Toolbar Position Palauta työkalurivin sijainti Picas Picat Portuguese Portugali Preserve Appearance and Overprints Säilytä ulkoasu ja päällepainatukset @@ -4347,6 +4365,11 @@ theme Appearance Ulkoasu Edit Arrowheads Muokkaa nuolenkärkiä Edit Arrowheads… Muokkaa nuolenkärkiä… Reload Arrowheads Lataa nuolenkärjet uudelleen + Bevels Viisteet + Edit Bevels Muokkaa viisteitä + Edit Bevels… Muokkaa viisteitä… + {name} (document) {name} (asiakirja) + Reload Bevels Lataa viisteet uudelleen Stroke Options Viivan asetukset Width Profiles Leveysprofiilit Apply Graphic Style Käytä grafiikkatyyliä @@ -4568,6 +4591,11 @@ axis Both Molemmat Image Kuva Ink Muste Lab Lab + OKLCH Sliders OKLCH-liukusäätimet + HSL Sliders HSL-liukusäätimet + Chroma Kroma + The largest chroma sRGB holds at this lightness and hue Suurin kroma, jonka sRGB sisältää tällä vaaleudella ja sävyllä + OKLCH needs sRGB as the working RGB space OKLCH vaatii sRGB:n RGB-työväriavaruudeksi Medium Keskitaso Name Nimi None Ei mitään @@ -4661,6 +4689,7 @@ font-technology Variable Muuttuvat Recent Commands Viimeisimmät komennot No recent commands Ei viimeisimpiä komentoja Type to search commands, tools, panels and effects Kirjoita hakeaksesi komentoja, työkaluja, paneeleita ja tehosteita + Clear Recent Commands Tyhjennä viimeisimmät komennot Dashed Line Katkoviiva Panel menu Paneelivalikko Unembed… Poista upotus… @@ -4780,9 +4809,14 @@ font-technology Variable Muuttuvat Edit type set in fonts that aren't available? Muokataanko tekstiä, jonka fontit eivät ole käytettävissä? Shows each slice's number in a box at its top left on the canvas; off, the slice outlines still show. Näyttää piirtopinnalla kunkin viipaleen numeron ruudussa sen vasemmassa yläkulmassa; kun asetus on pois päältä, viipaleiden ääriviivat näkyvät edelleen. The color of user and object slice outlines and their number boxes; auto slices use a dimmer shade of it. Käyttäjä- ja objektiviipaleiden ääriviivojen ja niiden numeroruutujen väri; automaattiset viipaleet käyttävät siitä himmeämpää sävyä. + New type takes this language while Document Setup's language is English: USA and [Normal Character Style] sets none; type already in a document keeps its own language. Uusi teksti saa tämän kielen, kun Asiakirjan asetusten kieli on Englanti: USA eikä [Normaali merkkityyli] määritä kieltä; asiakirjassa jo oleva teksti säilyttää oman kielensä. + In paragraphs with Hyphenate on, a listed word is hyphenated only at the hyphens typed in it, or never when it has none, whatever its language or case. Kappaleissa, joissa Tavuta on käytössä, luettelon sana saa tavuviivan vain siihen kirjoitettujen yhdysmerkkien kohdalle tai ei koskaan, jos niitä ei ole, kielestä ja kirjainkoosta riippumatta. + On the desktop, this folder's .wasm plug-ins load at startup and when OK sets a new folder, except in Safe Mode; one that asks for permissions loads only after you grant them. The web version loads none. Työpöytäversiossa tämän kansion .wasm-laajennukset ladataan käynnistettäessä ja kun OK asettaa uuden kansion, paitsi vikasietotilassa; käyttöoikeuksia pyytävä laajennus ladataan vasta, kun myönnät ne. Verkkoversio ei lataa yhtään. + Large gives each filter or command plug-in run at least 250 million instructions, with the same time limit; Normal keeps the plug-in's own budget. Live effects, exporters and importers keep theirs. Suuri antaa suodatin- tai komentolaajennuksen jokaiselle ajolle vähintään 250 miljoonaa käskyä samalla aikarajalla; Normaali säilyttää laajennuksen oman budjetin. Live-tehosteet, viejät ja tuojat säilyttävät omansa. New type takes this language while Document Setup's language is English: USA; type already in a document keeps its own language. Uusi teksti saa tämän kielen, kun Asiakirjan asetusten kieli on Englanti: USA; asiakirjassa jo oleva teksti säilyttää oman kielensä. In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its language or case. Kappaleissa, joissa Tavuta on käytössä, luettelon sana tavutetaan vain siihen kirjoitettujen yhdysmerkkien kohdalta tai ei lainkaan, jos niitä ei ole, kielestä ja kirjainkoosta riippumatta. On the desktop, the .wasm plug-ins in this folder load at startup and when you click OK with a new folder here, except in Safe Mode; the web version does not load them. Työpöytäversiossa tämän kansion .wasm-laajennukset ladataan käynnistettäessä ja kun napsautat OK uuden kansion kanssa tässä, paitsi vikasietotilassa; verkkoversio ei lataa niitä. + Normal keeps each plug-in's own limits; with Large, a plug-in filter or command may run at least 250 million instructions besides those for its input. The time limit stays the same. Normaali säilyttää kunkin laajennuksen omat rajat; Suuri-asetuksella laajennuksen suodin tai komento voi suorittaa vähintään 250 miljoonaa käskyä syötteensä käskyjen lisäksi. Aikaraja pysyy samana. How many instructions each run of a plug-in object filter may use; Large allows more than Normal with the same 60-second limit. Heavy filters keep their own budget. Kuinka monta käskyä laajennuksen objektisuotimen kukin suorituskerta saa käyttää; Suuri sallii enemmän kuin Normaali samalla 60 sekunnin rajalla. Raskaat suotimet säilyttävät oman budjettinsa. The first scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. Ensimmäinen työlevyvalinta: Startup, None tai kansiopolku; VectorCraft tallentaa sen, mutta ei vielä käytä työlevyjä. The second scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. Toinen työlevyvalinta: Startup, None tai kansiopolku; VectorCraft tallentaa sen, mutta ei vielä käytä työlevyjä. @@ -4794,13 +4828,15 @@ font-technology Variable Muuttuvat Shows each tool group's name above its tools in the toolbar; off, the groups follow one another with nothing between them. Näyttää kunkin työkaluryhmän nimen sen työkalujen yläpuolella työkalurivissä; pois päältä ryhmät seuraavat toisiaan ilman mitään välissä. From now on, documents you open or create open as tabs; off, each opens in a floating window. Documents already open stay where they are. Tästä lähtien avaamasi tai luomasi asiakirjat avautuvat välilehtinä; pois päältä kukin avautuu kelluvaan ikkunaan. Jo avoinna olevat asiakirjat pysyvät paikoillaan. Makes the document tabs taller and their names larger. Tekee asiakirjojen välilehdistä korkeampia ja niiden nimistä suurempia. - From the next start, the system draws the window's title bar where VectorCraft would otherwise draw its own. Seuraavasta käynnistyksestä alkaen järjestelmä piirtää ikkunan otsikkorivin siellä, missä VectorCraft muuten piirtäisi omansa. - From the next start, VectorCraft draws the window's title bar even where the desktop would draw it, unless System Title Bar is on. Seuraavasta käynnistyksestä alkaen VectorCraft piirtää ikkunan otsikkorivin silloinkin, kun työpöytä piirtäisi sen, ellei Järjestelmän otsikkorivi ole päällä. + From the next start, the system draws the window's title bar where VectorCraft would otherwise draw its own; on Linux and the BSDs, the VECTORCRAFT_TITLEBAR variable takes precedence. Seuraavasta käynnistyksestä alkaen järjestelmä piirtää ikkunan otsikkorivin siellä, missä VectorCraft muuten piirtäisi omansa; Linuxissa ja BSD-järjestelmissä VECTORCRAFT_TITLEBAR-muuttuja menee edelle. + From the next start, VectorCraft draws the window's title bar even where the desktop would draw it, unless System Title Bar is on or the VECTORCRAFT_TITLEBAR variable chooses it. Seuraavasta käynnistyksestä alkaen VectorCraft piirtää ikkunan otsikkorivin silloinkin, kun työpöytä piirtäisi sen, ellei Järjestelmän otsikkorivi ole päällä tai VECTORCRAFT_TITLEBAR-muuttuja valitse sitä. Makes the interface larger or smaller; art on the canvas keeps its size at the same zoom. Suurentaa tai pienentää käyttöliittymää; kankaalla oleva kuvitus säilyttää kokonsa samalla zoomauksella. The tool pointers VectorCraft draws grow and shrink with UI Scaling; off, they keep their size. VectorCraftin piirtämät työkaluosoittimet kasvavat ja pienenevät Käyttöliittymän skaalauksen mukana; pois päältä ne säilyttävät kokonsa. The language of the interface; Auto uses the system's language. The dialog switches language as soon as you choose one. Käyttöliittymän kieli; Automaattinen käyttää järjestelmän kieltä. Valintaikkuna vaihtaa kielen heti, kun valitset sellaisen. Animated Zoom works only while this is on; off, Animated Zoom is dimmed and zooming does not animate. Animoitu zoomaus toimii vain, kun tämä on päällä; pois päältä Animoitu zoomaus on himmennetty eikä zoomausta animoida. The wheel's zoom glides in, and the Zoom tool zooms as you drag sideways or hold it down; off, the Zoom tool zooms to the area you drag across. Rullalla zoomaus liukuu pehmeästi, ja Zoomaustyökalu zoomaa, kun vedät sivulle tai pidät sitä painettuna; pois päältä Zoomaustyökalu zoomaa alueeseen, jonka yli vedät. + From the next start, the desktop version shows the canvas through this kind of graphics processor; the artwork is drawn on the CPU either way. Automatic prefers the integrated one on Windows and macOS. The web version does not use it. Seuraavasta käynnistyksestä alkaen työpöytäversio näyttää piirtoalueen tämän tyyppisen grafiikkasuorittimen kautta; kuvitus piirretään joka tapauksessa suorittimella. Automaattinen suosii integroitua Windowsissa ja macOS:ssä. Verkkoversio ei käytä sitä. + From the next start, the window shows each frame without waiting for the display's refresh where the graphics driver allows, at most 240 frames a second. Seuraavasta käynnistyksestä alkaen ikkuna näyttää jokaisen kuvan odottamatta näytön virkistystä, kun grafiikkaohjain sallii sen, enintään 240 kuvaa sekunnissa. From the next start, the desktop version draws with this kind of graphics processor; Automatic prefers the one that drives the display. The web version does not use it. Seuraavasta käynnistyksestä alkaen työpöytäversio piirtää tämän tyyppisellä grafiikkasuorittimella; Automaattinen suosii näyttöä ohjaavaa. Verkkoversio ei käytä sitä. From the next start, the window shows frames without waiting for the display to refresh, at most 240 a second; off, the display paces them. A present mode set at launch overrides it. Seuraavasta käynnistyksestä alkaen ikkuna näyttää kuvat odottamatta näytön virkistystä, enintään 240 sekunnissa; pois päältä näyttö tahdittaa ne. Käynnistettäessä asetettu esitystila ohittaa sen. The most undo steps each document keeps; lowering it drops the oldest steps when you click OK. Steps can also go sooner when they use too much memory. Kumoamisvaiheiden enimmäismäärä, jonka kukin asiakirja säilyttää; pienempi luku poistaa vanhimmat vaiheet, kun napsautat OK. Vaiheita voi poistua aiemmin, jos ne vievät liikaa muistia. @@ -4819,6 +4855,9 @@ font-technology Variable Muuttuvat Open Recent Files and the Home screen list at most this many recent files; 0 lists none, and VectorCraft still remembers up to 30. Avaa viimeisimmät tiedostot ja Aloitus-näkymä luettelevat enintään näin monta viimeisintä tiedostoa; 0 ei luettele yhtään, ja VectorCraft muistaa silti enintään 30. When a document opens, a linked EPS image that shows its saved preview keeps it instead of reading the EPS file again; changed files still follow Update Links. Kun asiakirja avataan, linkitetty EPS-kuva, joka näyttää tallennetun esikatselunsa, säilyttää sen eikä lue EPS-tiedostoa uudelleen; muuttuneet tiedostot noudattavat silti Päivitä linkit -asetusta. In Pixel Preview, images are drawn smoothed; off, their pixels show with hard edges. Outside Pixel Preview, images are always smoothed. Pikseliesikatselussa kuvat piirretään pehmennettyinä; pois päältä niiden pikseleillä on terävät reunat. Pikseliesikatselun ulkopuolella kuvat pehmennetään aina. + PDF Text PDF-teksti + The text of a PDF you open or embed comes in as editable type, or as outlines that look the same on a computer without its fonts. Avaamasi tai upottamasi PDF:n teksti tuodaan muokattavana tekstinä tai ääriviivoina, jotka näyttävät samalta tietokoneella, jossa sen fontteja ei ole. + Linked pages show the file's own text. Linkitetyt sivut näyttävät tiedoston oman tekstin. When a linked file changes, Automatically reads it again, Ask When Modified asks you first, and Manually leaves it and shows a note in the status bar. Kun linkitetty tiedosto muuttuu, Automaattisesti lukee sen uudelleen, Kysy, kun muokattu kysyy ensin, ja Manuaalisesti jättää sen ennalleen ja näyttää ilmoituksen tilarivillä. On the desktop, the folder New from Template… and Save as Template… start in; leave it blank for VectorCraft Templates in your documents folder. Työpöytäversiossa kansio, josta Uusi mallipohjasta… ja Tallenna mallipohjana… alkavat; jätä tyhjäksi, niin käytetään asiakirjakansiosi VectorCraft Templates -kansiota. Edit Original opens a linked file in the system's default app for its type; off, a linked raster image opens in PhotoCraft where it is installed. Muokkaa alkuperäistä avaa linkitetyn tiedoston järjestelmän oletussovelluksessa sen tyypin mukaan; pois päältä linkitetty rasterikuva avautuu PhotoCraftissa, jos se on asennettu. @@ -4833,7 +4872,6 @@ font-technology Variable Muuttuvat Output All Blacks as Rich Black draws pure CMYK black as RGB black in RGB and grayscale raster exports and Print as Bitmap; it does not change vector exports, CMYK JPEG, TIFF and PSD, or other printing. Tulosta kaikki mustat syvämustina piirtää puhtaan CMYK-mustan RGB-mustana RGB- ja harmaasävyrasterivienneissä ja Tulosta bittikarttana -asetuksella; se ei muuta vektorivientejä, CMYK-JPEG-, -TIFF- ja -PSD-tiedostoja eikä muuta tulostusta. On a touch screen, switches to the Touch workspace; turning this off, or losing the touch screen, goes back to the workspace it switched from. Kosketusnäytöllä vaihtaa kosketustyötilaan; asetuksen poistaminen käytöstä tai kosketusnäytön katoaminen palauttaa työtilan, josta vaihdettiin. A two-finger tap on the canvas undoes, or switches between selection and drawing tools in the Touch workspace, and a three-finger tap redoes; neither works in Presentation Mode. Kahden sormen napautus piirtopinnalla kumoaa tai vaihtaa kosketustyötilassa valinta- ja piirtotyökalujen välillä, ja kolmen sormen napautus tekee uudelleen; kumpikaan ei toimi esitystilassa. - New type takes this language while Document Setup's language is English: USA and [Normal Character Style] sets none; type already in a document keeps its own language. Uusi teksti saa tämän kielen, kun Asiakirjan asetusten kieli on Englanti: USA eikä [Normaali merkkityyli] määritä kieltä; asiakirjassa jo oleva teksti säilyttää oman kielensä. In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its case; Korean words take no hyphen, and Indian-language words do not break inside a character cluster. Kappaleissa, joissa Tavuta on käytössä, luettelon sana tavutetaan vain siihen kirjoitettujen yhdysmerkkien kohdalta tai ei lainkaan, jos niitä ei ole, kirjainkoosta riippumatta; korealaisiin sanoihin ei tule tavuviivaa, eikä intialaisten kielten sanoja tavuteta merkkiryhmän sisältä. Reset all preferences to their defaults? Palautetaanko kaikki asetukset oletuksiin? The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. Oletukset otetaan käyttöön, kun valitset Asetuksissa OK. Peruuta siellä säilyttää nykyiset asetuksesi. @@ -4856,6 +4894,10 @@ font-technology Variable Muuttuvat Cusp Kärki Straight segment Suora segmentti Circle too large Ympyrä on liian suuri + Show Radii Näytä säteet + Show Diameter Näytä halkaisija + Anchors at Standard Positions Ankkuripisteet vakiokohdissa + Third Point by Dragging Kolmas piste vetämällä Clip to Art Rajaa kuvitukseen Colorize Väritä Gamma Gamma @@ -5823,6 +5865,10 @@ liquify-list-end {0}, {1} {0} ja {1} @msg this trace would make more than {max} anchor points, more than the document can show smoothly: raise Noise, lower Paths or Colors, or pick a lower-fidelity preset tämä jäljitys tuottaisi yli {max} ankkuripistettä, enemmän kuin asiakirja näyttää sujuvasti: nosta kohinaa, vähennä polkuja tai värejä tai valitse epätarkempi esiasetus @msg select an envelope valitse vääristyskuori @msg select an image valitse kuva +@msg object {_1} is an image changed by Perspective Distort or Free Distort, which this command does not work on objekti {_1} on kuva, jota on muutettu Perspektiivivääristyksellä tai Vapaalla vääristyksellä, eikä tämä komento toimi sille +@msg image {_1} cannot be distorted this way: its corners would not make a convex shape kuvaa {_1} ei voi vääristää näin: sen kulmat eivät muodostaisi kuperaa muotoa +@msg image {_1} cannot be distorted this way: its corners would cross the warp's horizon kuvaa {_1} ei voi vääristää näin: sen kulmat ylittäisivät vääristyksen horisontin +@msg image {_1} cannot be distorted this way: its corners would be too close together for a perspective map kuvaa {_1} ei voi vääristää näin: sen kulmat olisivat liian lähellä toisiaan perspektiivikuvausta varten @msg `background` must be edges, corners or colors `background`-arvon on oltava edges, corners tai colors @msg `match` must be distance or channels `match`-arvon on oltava distance tai channels @msg `{key}` must be from 0 to 100 `{key}`-arvon on oltava väliltä 0–100 @@ -6733,7 +6779,10 @@ mark-style Japanese Japanilainen @msg the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate) objektilla ei ole 3D-tehostetta (Pursota ja viistä, Pyöräytä, Täytä ilmalla tai Kierrä) @msg `render` must be an object holding only `mode`, set to shaded or wireframe `render` on oltava objekti, jossa on vain `mode` arvolla shaded tai wireframe @msg its 3D effect builds no solid sen 3D-tehoste ei muodosta kappaletta -@msg bevel must be none or one of {_1} bevel-arvon on oltava none tai jokin seuraavista: {_1} +@msg bevel must be none or one of {_1}, or custom with {BEVEL_PROFILE} bevel-arvon on oltava none, jokin seuraavista: {_1}, tai custom yhdessä arvon {BEVEL_PROFILE} kanssa +@msg bevel custom needs {BEVEL_PROFILE}, the bevel's points bevel custom tarvitsee arvon {BEVEL_PROFILE}, viisteen pisteet +@msg {BEVEL_NAME} must be a string {BEVEL_NAME} on oltava merkkijono +@msg {BEVEL_PROFILE} must be 2 to {most} [x, y] points, each share between 0 and 1, from [0, 0] (the cap's edge) to [1, 1] (the side wall) arvossa {BEVEL_PROFILE} on oltava vähintään 2 ja enintään {most} pistettä [x, y], kukin osuus väliltä 0 ja 1, pisteestä [0, 0] (päätypinnan reuna) pisteeseen [1, 1] (sivuseinä) @msg {_1} can't build solids from this art: its symbol instances, blends and clipping groups hold too many objects {_1} ei voi muodostaa kappaleita tästä kuvituksesta: sen symbolien esiintymät, sulautukset ja leikkausryhmät sisältävät liikaa objekteja @msg {label} can't build a solid from the instance of symbol "{symbol}": the symbol's art isn't available {label} ei voi muodostaa kappaletta symbolin ”{symbol}” esiintymästä: symbolin kuvitus ei ole käytettävissä @msg {_1}: the clipping path is too complex to cut the art with {_1}: leikkauspolku on liian monimutkainen kuvituksen leikkaamiseen @@ -6990,6 +7039,8 @@ mark-style Japanese Japanilainen @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode`-arvon on oltava grayscale, rgb, hsb, cmyk tai websafe @msg `view` must be wheel or box `view`-arvon on oltava wheel tai box @msg `channel` must be hue, saturation, brightness, red, green or blue `channel`-arvon on oltava hue, saturation, brightness, red, green tai blue +@msg `sliders` must be none, oklch or hsl `sliders` on oltava none, oklch tai hsl +@msg OKLCH needs sRGB as the working RGB space OKLCH vaatii sRGB:n RGB-työväriavaruudeksi @msg `{key}` must be an array of these names: {_1} `{key}`-arvon on oltava taulukko, jossa on näitä nimiä: {_1} @msg choose a destination folder valitse kohdekansio @msg choose a source folder valitse lähdekansio @@ -8980,6 +9031,20 @@ breakText Glyphs Merkit @msg A joint does not close by {gap} pt. Liitos ei sulkeudu, rako {gap} pt. @msg Two panels pass through each other. Kaksi paneelia kulkee toistensa läpi. @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer on oltava "singleLine", "everyLine", "standardSingleLine" tai "standardEveryLine" + Vector Packs Vektoripaketit + Compass Rose Kompassiruusu + Botanical Sprig Kasvinoksa + Facet Diamond Särmätty timantti + Tide Crest Aallonharja + Leaf Vine Lehtiköynnös + Blossom Chain Kukkaketju + Pennant Garland Viiririvistö + Lantern String Lyhtyketju + Orbit Lines Kiertoradan viivat + Petal Garland Terälehtiköynnös + Lattice Braid Ristikkopunos + Facet Sweep Särmikäs veto + Artistic Brushes Taidesiveltimet Paint Maalaus Flat Sweep Tasainen veto Dry Drag Kuiva veto diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 4df0d7445b..8f0a4f121e 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -508,6 +508,10 @@ font-technology Variable Variables Cusp Point de rebroussement Straight segment Segment droit Circle too large Cercle trop grand + Show Radii Afficher les rayons + Show Diameter Afficher le diamètre + Anchors at Standard Positions Points d’ancrage aux positions standard + Third Point by Dragging Troisième point par glissement Classic Defaults Valeurs par défaut classiques Clean Up… Nettoyer… Clear Effacer @@ -611,9 +615,14 @@ font-technology Variable Variables {name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2} Wheel View Affichage roue Box View Affichage carré + Show Out-of-Gamut Colors Afficher les couleurs hors gamme Box Channel Couche du carré Color box Carré de couleur Color Wheel Options Options de la roue chromatique + Show Document Colors Afficher les couleurs du document + Document Colors Couleurs du document + Selection Colors Couleurs de la sélection +@plural Used {n} time|Used {n} times Utilisée {n} fois|Utilisée {n} fois Show Harmony Afficher l’harmonie Harmony Rule Règle d’harmonie Harmony color Couleur de l’harmonie @@ -657,6 +666,8 @@ font-technology Variable Variables Contextual Task Bar Barre des tâches contextuelle Pin Bar Position Épingler la position de la barre Reset Bar Position Réinitialiser la position de la barre + Bar Actions Actions de la barre + Reset Bar Actions Réinitialiser les actions de la barre Resize Redimensionner Contrast Contraste Control Contrôle @@ -1896,6 +1907,10 @@ font-technology Variable Variables Rename Preset Renommer le paramètre prédéfini Save Image Trace Preset Enregistrer le paramètre prédéfini de vectorisation de l’image Delete Image Trace Preset Supprimer le paramètre prédéfini de vectorisation de l’image + Tracing Presets… Paramètres prédéfinis de vectorisation… + Import Image Trace Presets Importer des paramètres prédéfinis de vectorisation de l’image + Export Image Trace Presets Exporter les paramètres prédéfinis de vectorisation de l’image + Replace the saved presets that have these names? Remplacer les paramètres prédéfinis enregistrés qui portent ces noms ? Image Trace Presets Paramètres prédéfinis de vectorisation de l’image Image: Image : Images: Images : @@ -2027,6 +2042,11 @@ font-technology Variable Variables Knife Cutter Knockout Group Groupe perçant Lab Lab + OKLCH Sliders Curseurs OKLCH + HSL Sliders Curseurs HSL + Chroma Chroma + The largest chroma sRGB holds at this lightness and hue Le plus grand chroma que sRGB contient à cette luminosité et cette teinte + OKLCH needs sRGB as the working RGB space OKLCH nécessite sRGB comme espace de travail RGB Lab Spot Colors: Tons directs Lab : Lab Values Valeurs Lab Landscape Paysage @@ -2785,6 +2805,13 @@ font-technology Variable Variables Pen Tool Outil Plume Quick Pen Tool Outil Plume rapide Quick Pen Plume rapide + Quick Pen Toolbar Barre d’outils Plume rapide + Continuous Arc Arc continu + Sharp Corner Arc Arc à angle vif + Flip Arc Retourner l’arc + Hide Toolbar Masquer la barre d’outils + Pin Toolbar Position Épingler la position de la barre d’outils + Reset Toolbar Position Réinitialiser la position de la barre d’outils Pencil Crayon Pencil Tool Outil Crayon per slice par tranche @@ -3228,6 +3255,11 @@ digits Malayalam Malayalam Edit Arrowheads Modifier les pointes de flèche Edit Arrowheads… Modifier les pointes de flèche… Reload Arrowheads Recharger les pointes de flèche + Bevels Biseaux + Edit Bevels Modifier les biseaux + Edit Bevels… Modifier les biseaux… + {name} (document) {name} (document) + Reload Bevels Recharger les biseaux Reset Rotate View Réinitialiser la rotation de l’affichage Rotate View to Selection Faire pivoter l’affichage selon la sélection Reset the rows to the artwork's colors Réinitialiser les lignes avec les couleurs de l’illustration @@ -3365,9 +3397,14 @@ digits Malayalam Malayalam Edit type set in fonts that aren't available? Modifier le texte composé dans des polices non disponibles ? Shows each slice's number in a box at its top left on the canvas; off, the slice outlines still show. Affiche sur la zone de travail le numéro de chaque tranche dans un cadre en haut à gauche de la tranche. Désactivée, les contours des tranches restent affichés. The color of user and object slice outlines and their number boxes; auto slices use a dimmer shade of it. La couleur des contours des tranches utilisateur et objet et de leurs cadres de numéro. Les tranches automatiques utilisent une nuance plus terne de cette couleur. + New type takes this language while Document Setup's language is English: USA and [Normal Character Style] sets none; type already in a document keeps its own language. Le nouveau texte prend cette langue tant que la langue de Format de document est l’anglais des États-Unis et que [Style de caractère normal] n’en définit aucune. Le texte déjà présent dans un document garde sa langue. + In paragraphs with Hyphenate on, a listed word is hyphenated only at the hyphens typed in it, or never when it has none, whatever its language or case. Dans les paragraphes où Césure est activée, un mot de la liste ne reçoit de trait de césure qu’aux traits d’union saisis dedans, ou jamais s’il n’en a pas, quelles que soient sa langue et sa casse. + On the desktop, this folder's .wasm plug-ins load at startup and when OK sets a new folder, except in Safe Mode; one that asks for permissions loads only after you grant them. The web version loads none. Dans la version de bureau, les modules externes .wasm de ce dossier se chargent au démarrage et quand OK définit un nouveau dossier, sauf en mode sans échec. Un module qui demande des autorisations ne se charge qu’une fois celles-ci accordées. La version web n’en charge aucun. + Large gives each filter or command plug-in run at least 250 million instructions, with the same time limit; Normal keeps the plug-in's own budget. Live effects, exporters and importers keep theirs. Grand donne à chaque exécution d’un module externe de filtre ou de commande au moins 250 millions d’instructions, avec la même limite de temps. Normal garde le budget propre du module. Les effets dynamiques, exportateurs et importateurs gardent le leur. New type takes this language while Document Setup's language is English: USA; type already in a document keeps its own language. Le nouveau texte prend cette langue tant que la langue de Format de document est l’anglais des États-Unis. Le texte déjà présent dans un document garde sa langue. In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its language or case. Dans les paragraphes où Césure est activée, un mot de la liste n’est coupé qu’aux traits d’union saisis dedans, ou nulle part s’il n’en a pas, quelles que soient sa langue et sa casse. On the desktop, the .wasm plug-ins in this folder load at startup and when you click OK with a new folder here, except in Safe Mode; the web version does not load them. Dans la version de bureau, les modules externes .wasm de ce dossier se chargent au démarrage et lorsque vous cliquez sur OK avec un nouveau dossier ici, sauf en mode sans échec. La version web ne les charge pas. + Normal keeps each plug-in's own limits; with Large, a plug-in filter or command may run at least 250 million instructions besides those for its input. The time limit stays the same. Normal conserve les limites propres à chaque module externe. Avec Grand, un filtre ou une commande d’un module externe peut exécuter au moins 250 millions d’instructions en plus de celles de son entrée. La limite de temps reste la même. How many instructions each run of a plug-in object filter may use; Large allows more than Normal with the same 60-second limit. Heavy filters keep their own budget. Le nombre d’instructions que chaque exécution d’un filtre d’objets d’un module externe peut utiliser. Grand en autorise plus que Normal, avec la même limite de 60 secondes. Les filtres lourds gardent leur propre budget. The first scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. Premier disque de travail (Startup, None ou le chemin d’un dossier). VectorCraft l’enregistre, mais n’utilise pas encore de disques de travail. The second scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. Second disque de travail (Startup, None ou le chemin d’un dossier). VectorCraft l’enregistre, mais n’utilise pas encore de disques de travail. @@ -3379,13 +3416,15 @@ digits Malayalam Malayalam Shows each tool group's name above its tools in the toolbar; off, the groups follow one another with nothing between them. Affiche le nom de chaque groupe d’outils au-dessus de ses outils dans la barre d’outils. Désactivé, les groupes se suivent sans rien entre eux. From now on, documents you open or create open as tabs; off, each opens in a floating window. Documents already open stay where they are. Désormais, les documents que vous ouvrez ou créez s’ouvrent dans des onglets. Désactivé, chacun s’ouvre dans une fenêtre flottante. Les documents déjà ouverts restent où ils sont. Makes the document tabs taller and their names larger. Rend les onglets des documents plus hauts et leurs noms plus grands. - From the next start, the system draws the window's title bar where VectorCraft would otherwise draw its own. À partir du prochain démarrage, le système dessine la barre de titre de la fenêtre là où VectorCraft dessinerait sinon la sienne. - From the next start, VectorCraft draws the window's title bar even where the desktop would draw it, unless System Title Bar is on. À partir du prochain démarrage, VectorCraft dessine la barre de titre de la fenêtre même là où le bureau la dessinerait, sauf si Barre de titre du système est activée. + From the next start, the system draws the window's title bar where VectorCraft would otherwise draw its own; on Linux and the BSDs, the VECTORCRAFT_TITLEBAR variable takes precedence. À partir du prochain démarrage, le système dessine la barre de titre de la fenêtre là où VectorCraft dessinerait sinon la sienne. Sous Linux et les BSD, la variable VECTORCRAFT_TITLEBAR a la priorité. + From the next start, VectorCraft draws the window's title bar even where the desktop would draw it, unless System Title Bar is on or the VECTORCRAFT_TITLEBAR variable chooses it. À partir du prochain démarrage, VectorCraft dessine la barre de titre de la fenêtre même là où le bureau la dessinerait, sauf si Barre de titre du système est activée ou si la variable VECTORCRAFT_TITLEBAR la choisit. Makes the interface larger or smaller; art on the canvas keeps its size at the same zoom. Agrandit ou réduit l’interface. L’illustration de la zone de travail garde sa taille au même zoom. The tool pointers VectorCraft draws grow and shrink with UI Scaling; off, they keep their size. Les pointeurs d’outil que dessine VectorCraft grandissent et rétrécissent avec la Mise à l’échelle de l’interface. Désactivé, ils gardent leur taille. The language of the interface; Auto uses the system's language. The dialog switches language as soon as you choose one. La langue de l’interface. Auto utilise la langue du système. La boîte de dialogue change de langue dès que vous en choisissez une. Animated Zoom works only while this is on; off, Animated Zoom is dimmed and zooming does not animate. Le Zoom animé ne fonctionne que si cette option est activée. Désactivée, le Zoom animé est grisé et le zoom n’est pas animé. The wheel's zoom glides in, and the Zoom tool zooms as you drag sideways or hold it down; off, the Zoom tool zooms to the area you drag across. Le zoom à la molette glisse en douceur, et l’Outil Zoom zoome quand vous faites glisser de côté ou le maintenez enfoncé. Désactivée, l’Outil Zoom zoome sur la zone que vous parcourez. + From the next start, the desktop version shows the canvas through this kind of graphics processor; the artwork is drawn on the CPU either way. Automatic prefers the integrated one on Windows and macOS. The web version does not use it. À partir du prochain démarrage, la version de bureau affiche le canevas par ce type de processeur graphique. L’illustration est toujours dessinée par le processeur central. Automatique préfère le processeur intégré sous Windows et macOS. La version web ne l’utilise pas. + From the next start, the window shows each frame without waiting for the display's refresh where the graphics driver allows, at most 240 frames a second. À partir du prochain démarrage, la fenêtre affiche chaque image sans attendre le rafraîchissement de l’écran lorsque le pilote graphique le permet, au plus 240 images par seconde. From the next start, the desktop version draws with this kind of graphics processor; Automatic prefers the one that drives the display. The web version does not use it. À partir du prochain démarrage, la version de bureau dessine avec ce type de processeur graphique. Automatique préfère celui qui pilote l’écran. La version web ne l’utilise pas. From the next start, the window shows frames without waiting for the display to refresh, at most 240 a second; off, the display paces them. A present mode set at launch overrides it. À partir du prochain démarrage, la fenêtre affiche les images sans attendre le rafraîchissement de l’écran, au plus 240 par seconde. Désactivé, l’écran les cadence. Un mode de présentation défini au lancement a la priorité. The most undo steps each document keeps; lowering it drops the oldest steps when you click OK. Steps can also go sooner when they use too much memory. Le nombre maximal d’étapes d’annulation que chaque document conserve. Un nombre plus bas supprime les plus anciennes quand vous cliquez sur OK. Des étapes peuvent aussi partir plus tôt si elles occupent trop de mémoire. @@ -3404,6 +3443,9 @@ digits Malayalam Malayalam Open Recent Files and the Home screen list at most this many recent files; 0 lists none, and VectorCraft still remembers up to 30. Ouvrir les fichiers récents et l’écran Accueil listent au plus ce nombre de fichiers récents. 0 n’en liste aucun, et VectorCraft en retient toujours jusqu’à 30. When a document opens, a linked EPS image that shows its saved preview keeps it instead of reading the EPS file again; changed files still follow Update Links. À l’ouverture d’un document, une image EPS liée qui montre son aperçu enregistré le garde au lieu de relire le fichier EPS. Les fichiers modifiés suivent toujours Mettre à jour les liens. In Pixel Preview, images are drawn smoothed; off, their pixels show with hard edges. Outside Pixel Preview, images are always smoothed. En Aperçu en pixels, les images sont dessinées lissées. Désactivée, leurs pixels ont des bords nets. Hors de l’Aperçu en pixels, les images sont toujours lissées. + PDF Text Texte PDF + The text of a PDF you open or embed comes in as editable type, or as outlines that look the same on a computer without its fonts. Le texte d’un PDF que vous ouvrez ou incorporez arrive en texte modifiable, ou en contours qui s’affichent de la même façon sur un ordinateur sans ses polices. + Linked pages show the file's own text. Les pages liées affichent le texte propre au fichier. When a linked file changes, Automatically reads it again, Ask When Modified asks you first, and Manually leaves it and shows a note in the status bar. Quand un fichier lié change, Automatiquement le relit, Demander en cas de modification vous le demande d’abord, et Manuellement le laisse tel quel avec une note dans la barre d’état. On the desktop, the folder New from Template… and Save as Template… start in; leave it blank for VectorCraft Templates in your documents folder. Dans la version de bureau, Nouveau d’après un modèle… et Enregistrer comme modèle… s’ouvrent dans ce dossier. Laissez-le vide pour VectorCraft Templates dans votre dossier de documents. Edit Original opens a linked file in the system's default app for its type; off, a linked raster image opens in PhotoCraft where it is installed. Modifier l’original ouvre un fichier lié dans l’application par défaut du système pour son type. Désactivée, une image matricielle liée s’ouvre dans PhotoCraft s’il est installé. @@ -3418,7 +3460,6 @@ digits Malayalam Malayalam Output All Blacks as Rich Black draws pure CMYK black as RGB black in RGB and grayscale raster exports and Print as Bitmap; it does not change vector exports, CMYK JPEG, TIFF and PSD, or other printing. Reproduire tous les noirs en noir intense dessine le noir CMJN pur en noir RVB dans les exportations matricielles RVB et en niveaux de gris et avec Imprimer en tant que bitmap. Les exportations vectorielles, les JPEG, TIFF et PSD CMJN et les autres impressions ne changent pas. On a touch screen, switches to the Touch workspace; turning this off, or losing the touch screen, goes back to the workspace it switched from. Sur un écran tactile, passe à l’espace de travail tactile. Désactiver l’option ou perdre l’écran tactile ramène à l’espace de travail d’avant ce changement. A two-finger tap on the canvas undoes, or switches between selection and drawing tools in the Touch workspace, and a three-finger tap redoes; neither works in Presentation Mode. Un toucher à deux doigts sur la zone de travail annule ou, dans l’espace de travail tactile, bascule entre outils de sélection et de dessin, et un toucher à trois doigts rétablit. Aucun ne fonctionne en mode Présentation. - New type takes this language while Document Setup's language is English: USA and [Normal Character Style] sets none; type already in a document keeps its own language. Le nouveau texte prend cette langue tant que la langue de Format de document est l’anglais des États-Unis et que [Style de caractère normal] n’en définit aucune. Le texte déjà présent dans un document garde sa langue. In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its case; Korean words take no hyphen, and Indian-language words do not break inside a character cluster. Dans les paragraphes où Césure est activée, un mot de la liste n’est coupé qu’aux traits d’union saisis dedans, ou nulle part s’il n’en a pas, quelle que soit sa casse. Les mots coréens ne prennent pas de trait d’union, et les mots en langues indiennes ne sont pas coupés à l’intérieur d’un groupe de caractères. Reset all preferences to their defaults? Rétablir toutes les préférences à leur valeur par défaut ? The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. Les valeurs par défaut sont appliquées lorsque vous cliquez sur OK dans Préférences. Annuler y conserve vos préférences actuelles. @@ -3661,6 +3702,7 @@ digits Malayalam Malayalam Recent Commands Commandes récentes No recent commands Aucune commande récente Type to search commands, tools, panels and effects Tapez pour rechercher des commandes, des outils, des panneaux et des effets + Clear Recent Commands Effacer les commandes récentes Search commands Chercher des commandes Search Commands… Rechercher des commandes… Secondary Secondaire @@ -5143,6 +5185,8 @@ liquify-list-end {0}, {1} {0} et {1} @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` doit valoir grayscale, rgb, hsb, cmyk ou websafe @msg `view` must be wheel or box `view` doit valoir wheel ou box @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` doit valoir hue, saturation, brightness, red, green ou blue +@msg `sliders` must be none, oklch or hsl `sliders` doit valoir none, oklch ou hsl +@msg OKLCH needs sRGB as the working RGB space OKLCH nécessite sRGB comme espace de travail RGB @msg `{k}` must be [x, y] `{k}` doit être [x, y] @msg `{name}` has no options `{name}` n’a pas d’options @msg `{name}` is a built-in workspace; choose another name `{name}` est un espace de travail intégré ; choisissez un autre nom @@ -5553,6 +5597,10 @@ liquify-list-end {0}, {1} {0} et {1} @msg this trace would make more than {max} anchor points, more than the document can show smoothly: raise Noise, lower Paths or Colors, or pick a lower-fidelity preset cette vectorisation créerait plus de {max} points d’ancrage, plus que le document ne peut afficher de façon fluide : augmentez Bruit, réduisez Tracés ou Couleurs, ou choisissez un paramètre prédéfini moins fidèle @msg select an envelope sélectionnez une enveloppe @msg select an image sélectionnez une image +@msg object {_1} is an image changed by Perspective Distort or Free Distort, which this command does not work on l’objet {_1} est une image modifiée par Distorsion de perspective ou Distorsion manuelle, sur laquelle cette commande ne fonctionne pas +@msg image {_1} cannot be distorted this way: its corners would not make a convex shape l’image {_1} ne peut pas être déformée ainsi, car ses coins ne formeraient pas une forme convexe +@msg image {_1} cannot be distorted this way: its corners would cross the warp's horizon l’image {_1} ne peut pas être déformée ainsi, car ses coins franchiraient l’horizon de la déformation +@msg image {_1} cannot be distorted this way: its corners would be too close together for a perspective map l’image {_1} ne peut pas être déformée ainsi, car ses coins seraient trop proches pour une projection en perspective @msg `background` must be edges, corners or colors `background` doit valoir edges, corners ou colors @msg `match` must be distance or channels `match` doit valoir distance ou channels @msg `{key}` must be from 0 to 100 `{key}` doit être compris entre 0 et 100 @@ -6395,7 +6443,10 @@ lighting Light Lumière @msg the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate) l’objet n’a aucun effet 3D (Extrusion et biseautage, Révolution, Gonfler ou Rotation) @msg `render` must be an object holding only `mode`, set to shaded or wireframe `render` doit être un objet ne contenant que `mode`, avec la valeur shaded ou wireframe @msg its 3D effect builds no solid son effet 3D ne construit aucun volume -@msg bevel must be none or one of {_1} bevel doit valoir none ou l’une de ces valeurs : {_1} +@msg bevel must be none or one of {_1}, or custom with {BEVEL_PROFILE} bevel doit valoir none, l’une des valeurs {_1}, ou custom avec {BEVEL_PROFILE} +@msg bevel custom needs {BEVEL_PROFILE}, the bevel's points bevel custom nécessite {BEVEL_PROFILE}, les points du biseau +@msg {BEVEL_NAME} must be a string {BEVEL_NAME} doit être une chaîne +@msg {BEVEL_PROFILE} must be 2 to {most} [x, y] points, each share between 0 and 1, from [0, 0] (the cap's edge) to [1, 1] (the side wall) {BEVEL_PROFILE} doit contenir de 2 à {most} points [x, y], chaque proportion entre 0 et 1, de [0, 0] (le bord de la face) à [1, 1] (la paroi latérale) @msg {_1} can't build solids from this art: its symbol instances, blends and clipping groups hold too many objects {_1} ne peut pas construire de volumes à partir de cette illustration : ses occurrences de symbole, dégradés de formes et groupes de découpe contiennent trop d’objets @msg {label} can't build a solid from the instance of symbol "{symbol}": the symbol's art isn't available {label} ne peut pas construire de volume à partir de l’occurrence du symbole « {symbol} » : l’illustration du symbole n’est pas disponible @msg {_1}: the clipping path is too complex to cut the art with {_1} : le tracé de découpe est trop complexe pour découper l’illustration @@ -10711,6 +10762,20 @@ breakText Glyphs Glyphes @msg A joint does not close by {gap} pt. Un joint ne se ferme pas, avec un écart de {gap} pt. @msg Two panels pass through each other. Deux panneaux se traversent. @msg {_1} × {_2} pixels is too large for GIF (at most 65535 pixels a side): lower the resolution {_1} × {_2} pixels, c’est trop grand pour le GIF (65535 pixels par côté au plus) : réduisez la résolution + Vector Packs Packs vectoriels + Compass Rose Rose des vents + Botanical Sprig Rameau botanique + Facet Diamond Diamant facetté + Tide Crest Crête de vague + Leaf Vine Liane feuillue + Blossom Chain Chaîne de fleurs + Pennant Garland Guirlande de fanions + Lantern String Guirlande de lanternes + Orbit Lines Lignes orbitales + Petal Garland Guirlande de pétales + Lattice Braid Tresse en treillis + Facet Sweep Trait à facettes + Artistic Brushes Pinceaux artistiques Paint Peinture Flat Sweep Balayage plat Dry Drag Traînée sèche diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 3a12c0b214..0394c46530 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -606,6 +606,11 @@ Circle વર્તુળ Circle Tool વર્તુળ ટૂલ Circle too large વર્તુળ ખૂબ મોટું છે + Show Radii ત્રિજ્યાઓ બતાવો + Show Diameter વ્યાસ બતાવો + Anchors at Standard Positions પ્રમાણભૂત સ્થાનો પર એન્કર બિંદુઓ + Third Point by Dragging ખેંચીને ત્રીજું બિંદુ + Gray રાખોડી Circle: વર્તુળ: Classic ક્લાસિક Clean Up સાફ કરો @@ -2040,6 +2045,12 @@ Knife નાઇફ Knockout Group નૉકઆઉટ ગ્રૂપ LZW Compression LZW કમ્પ્રેશન + OKLCH Sliders OKLCH સ્લાઇડર્સ + HSL Sliders HSL સ્લાઇડર્સ + Chroma ક્રોમા + The largest chroma sRGB holds at this lightness and hue આ લાઇટનેસ અને હ્યૂ પર sRGB સમાવી શકે તે સૌથી વધુ ક્રોમા + OKLCH needs sRGB as the working RGB space OKLCH માટે કાર્યકારી RGB સ્પેસ તરીકે sRGB જરૂરી છે + Lightness લાઇટનેસ Lab Spot Colors: Lab સ્પોટ રંગો: Landscape લેન્ડસ્કેપ Language ભાષા @@ -2812,6 +2823,13 @@ Pen Tool પેન ટૂલ Quick Pen Tool ક્વિક પેન ટૂલ Quick Pen ક્વિક પેન + Quick Pen Toolbar ક્વિક પેન ટૂલબાર + Continuous Arc સતત આર્ક + Sharp Corner Arc તીક્ષ્ણ ખૂણાવાળો આર્ક + Flip Arc આર્ક ફ્લિપ કરો + Hide Toolbar ટૂલબાર છુપાવો + Pin Toolbar Position ટૂલબાર સ્થિતિ પિન કરો + Reset Toolbar Position ટૂલબાર સ્થિતિ રીસેટ કરો Pencil પેન્સિલ Pencil Tool પેન્સિલ ટૂલ Percent: ટકા: @@ -3284,6 +3302,8 @@ arrowhead Feather પીંછું Reselect ફરી પસંદ કરો Reset રીસેટ કરો Reset Bar Position બાર સ્થિતિ રીસેટ કરો + Bar Actions બાર ક્રિયાઓ + Reset Bar Actions બાર ક્રિયાઓ રીસેટ કરો Reset Bounding Box બાઉન્ડિંગ બોક્સ રીસેટ કરો Rotate Bounding Box બાઉન્ડિંગ બોક્સ ફેરવો Rotate Bounding Box… બાઉન્ડિંગ બોક્સ ફેરવો… @@ -3443,9 +3463,13 @@ arrowhead Feather પીંછું Snaps the end of a line segment so that it meets a nearby straight segment at a right angle. લાઇન સેગમેન્ટના છેડાને એ રીતે સ્નેપ કરે છે કે તે નજીકના સીધા સેગમેન્ટને કાટખૂણે મળે. Shows each slice's number in a box at its top left on the canvas; off, the slice outlines still show. કેનવાસ પર દરેક સ્લાઇસનો નંબર તેના ઉપરના ડાબા ખૂણે એક બૉક્સમાં બતાવે છે; બંધ હોય ત્યારે પણ સ્લાઇસની રૂપરેખાઓ દેખાય છે. The color of user and object slice outlines and their number boxes; auto slices use a dimmer shade of it. યુઝર અને ઑબ્જેક્ટ સ્લાઇસની રૂપરેખાઓ અને તેમના નંબર બૉક્સનો રંગ; ઑટો સ્લાઇસ તેની ઝાંખી છાયા વાપરે છે. + In paragraphs with Hyphenate on, a listed word is hyphenated only at the hyphens typed in it, or never when it has none, whatever its language or case. હાઇફનેટ કરો ચાલુ હોય તેવા ફકરાઓમાં, સૂચિમાંના શબ્દને ફક્ત તેમાં લખેલા હાઇફન પર જ હાઇફન લાગે છે, અથવા કોઈ ન હોય તો ક્યારેય નહીં, તેની ભાષા કે કેસ ગમે તે હોય. + On the desktop, this folder's .wasm plug-ins load at startup and when OK sets a new folder, except in Safe Mode; one that asks for permissions loads only after you grant them. The web version loads none. ડેસ્કટોપ સંસ્કરણમાં, આ ફોલ્ડરના .wasm પ્લગ-ઇન્સ શરૂઆતમાં અને ઠીક નવું ફોલ્ડર સેટ કરે ત્યારે લોડ થાય છે, સેફ મોડ સિવાય; પરવાનગીઓ માગતું પ્લગ-ઇન તમે તે આપો પછી જ લોડ થાય છે. વેબ સંસ્કરણ કોઈ લોડ કરતું નથી. + Large gives each filter or command plug-in run at least 250 million instructions, with the same time limit; Normal keeps the plug-in's own budget. Live effects, exporters and importers keep theirs. મોટું ફિલ્ટર કે કમાન્ડ પ્લગ-ઇનના દરેક રનને એ જ સમય મર્યાદા સાથે ઓછામાં ઓછી 250 મિલિયન સૂચનાઓ આપે છે; સામાન્ય પ્લગ-ઇનનું પોતાનું બજેટ રાખે છે. લાઇવ ઇફેક્ટ્સ, એક્સપોર્ટર્સ અને ઇમ્પોર્ટર્સ પોતાનું રાખે છે. New type takes this language while Document Setup's language is English: USA; type already in a document keeps its own language. દસ્તાવેજ સેટઅપની ભાષા અંગ્રેજી: USA હોય ત્યાં સુધી નવા ટેક્સ્ટને આ ભાષા મળે છે; દસ્તાવેજમાં પહેલેથી રહેલું ટેક્સ્ટ પોતાની ભાષા રાખે છે. In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its language or case. હાઇફનેટ કરો ચાલુ હોય તેવા ફકરાઓમાં, સૂચિમાંનો શબ્દ ફક્ત તેમાં લખેલા હાઇફન પર જ તૂટે છે, અથવા કોઈ ન હોય તો ક્યાંય નહીં, તેની ભાષા કે કેસ ગમે તે હોય. On the desktop, the .wasm plug-ins in this folder load at startup and when you click OK with a new folder here, except in Safe Mode; the web version does not load them. ડેસ્કટોપ સંસ્કરણમાં, આ ફોલ્ડરના .wasm પ્લગ-ઇન્સ શરૂઆતમાં અને અહીં નવા ફોલ્ડર સાથે ઠીક પર ક્લિક કરો ત્યારે લોડ થાય છે, સેફ મોડ સિવાય; વેબ સંસ્કરણ તેમને લોડ કરતું નથી. + Normal keeps each plug-in's own limits; with Large, a plug-in filter or command may run at least 250 million instructions besides those for its input. The time limit stays the same. સામાન્ય દરેક પ્લગ-ઇનની પોતાની મર્યાદાઓ રાખે છે; મોટું સાથે, પ્લગ-ઇન ફિલ્ટર અથવા આદેશ તેના ઇનપુટ માટેની સૂચનાઓ ઉપરાંત ઓછામાં ઓછી 250 મિલિયન સૂચનાઓ ચલાવી શકે છે. સમય મર્યાદા એ જ રહે છે. How many instructions each run of a plug-in object filter may use; Large allows more than Normal with the same 60-second limit. Heavy filters keep their own budget. પ્લગ-ઇનના ઑબ્જેક્ટ ફિલ્ટરનું દરેક રન કેટલી સૂચનાઓ વાપરી શકે; મોટું સામાન્ય કરતાં વધુ મંજૂરી આપે છે, 60 સેકન્ડની એ જ મર્યાદા સાથે. ભારે ફિલ્ટર પોતાનું બજેટ રાખે છે. The first scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. પ્રથમ સ્ક્રેચ ડિસ્ક પસંદગી: Startup, None અથવા ફોલ્ડરનો પાથ; VectorCraft તેને સાચવે છે, પરંતુ હજી સ્ક્રેચ ડિસ્કનો ઉપયોગ કરતું નથી. The second scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. બીજી સ્ક્રેચ ડિસ્ક પસંદગી: Startup, None અથવા ફોલ્ડરનો પાથ; VectorCraft તેને સાચવે છે, પરંતુ હજી સ્ક્રેચ ડિસ્કનો ઉપયોગ કરતું નથી. @@ -3457,13 +3481,15 @@ arrowhead Feather પીંછું Shows each tool group's name above its tools in the toolbar; off, the groups follow one another with nothing between them. ટૂલબારમાં દરેક ટૂલ ગ્રૂપનું નામ તેના ટૂલ્સની ઉપર બતાવે છે; બંધ હોય ત્યારે, ગ્રૂપ વચ્ચે કંઈ રાખ્યા વિના એક પછી એક આવે છે. From now on, documents you open or create open as tabs; off, each opens in a floating window. Documents already open stay where they are. હવેથી તમે ખોલો કે બનાવો તે દસ્તાવેજો ટેબ તરીકે ખૂલે છે; બંધ હોય ત્યારે, દરેક એક ફ્લોટિંગ વિન્ડોમાં ખૂલે છે. પહેલેથી ખુલ્લા દસ્તાવેજો જ્યાં છે ત્યાં જ રહે છે. Makes the document tabs taller and their names larger. દસ્તાવેજના ટૅબને ઊંચા અને તેમનાં નામ મોટાં બનાવે છે. - From the next start, the system draws the window's title bar where VectorCraft would otherwise draw its own. આગલી શરૂઆતથી, જ્યાં VectorCraft અન્યથા પોતાનો ટાઇટલ બાર દોરે ત્યાં સિસ્ટમ વિન્ડોનો ટાઇટલ બાર દોરે છે. - From the next start, VectorCraft draws the window's title bar even where the desktop would draw it, unless System Title Bar is on. આગલી શરૂઆતથી, ડેસ્કટોપ વિન્ડોનો ટાઇટલ બાર દોરે ત્યાં પણ VectorCraft તેને દોરે છે, સિવાય કે સિસ્ટમ ટાઇટલ બાર ચાલુ હોય. + From the next start, the system draws the window's title bar where VectorCraft would otherwise draw its own; on Linux and the BSDs, the VECTORCRAFT_TITLEBAR variable takes precedence. આગલી શરૂઆતથી, જ્યાં VectorCraft અન્યથા પોતાનો ટાઇટલ બાર દોરે ત્યાં સિસ્ટમ વિન્ડોનો ટાઇટલ બાર દોરે છે; Linux અને BSD પર VECTORCRAFT_TITLEBAR ચલને અગ્રતા મળે છે. + From the next start, VectorCraft draws the window's title bar even where the desktop would draw it, unless System Title Bar is on or the VECTORCRAFT_TITLEBAR variable chooses it. આગલી શરૂઆતથી, ડેસ્કટોપ વિન્ડોનો ટાઇટલ બાર દોરે ત્યાં પણ VectorCraft તેને દોરે છે, સિવાય કે સિસ્ટમ ટાઇટલ બાર ચાલુ હોય અથવા VECTORCRAFT_TITLEBAR ચલ તેને પસંદ કરે. Makes the interface larger or smaller; art on the canvas keeps its size at the same zoom. ઇન્ટરફેસને મોટું કે નાનું બનાવે છે; સમાન ઝૂમ પર કેનવાસ પરની આર્ટ પોતાનું કદ જાળવે છે. The tool pointers VectorCraft draws grow and shrink with UI Scaling; off, they keep their size. VectorCraft જે ટૂલ પોઇન્ટર દોરે છે તે UI સ્કેલિંગ સાથે મોટા અને નાના થાય છે; બંધ હોય ત્યારે, તે પોતાનું કદ જાળવે છે. The language of the interface; Auto uses the system's language. The dialog switches language as soon as you choose one. ઇન્ટરફેસની ભાષા; ઑટો સિસ્ટમની ભાષા વાપરે છે. તમે ભાષા પસંદ કરો કે તરત જ ડાયલોગ તે ભાષામાં બદલાય છે. Animated Zoom works only while this is on; off, Animated Zoom is dimmed and zooming does not animate. ઍનિમેટેડ ઝૂમ ફક્ત આ ચાલુ હોય ત્યારે જ કામ કરે છે; બંધ હોય ત્યારે, ઍનિમેટેડ ઝૂમ ઝાંખું થાય છે અને ઝૂમ ઍનિમેટ થતું નથી. The wheel's zoom glides in, and the Zoom tool zooms as you drag sideways or hold it down; off, the Zoom tool zooms to the area you drag across. વ્હીલથી ઝૂમ સરળતાથી સરકે છે, અને ઝૂમ ટૂલ તમે બાજુમાં ખેંચો અથવા દબાવી રાખો ત્યારે ઝૂમ કરે છે; બંધ હોય ત્યારે, ઝૂમ ટૂલ તમે ખેંચો તે વિસ્તાર પર ઝૂમ કરે છે. + From the next start, the desktop version shows the canvas through this kind of graphics processor; the artwork is drawn on the CPU either way. Automatic prefers the integrated one on Windows and macOS. The web version does not use it. આગલી શરૂઆતથી, ડેસ્કટોપ સંસ્કરણ આ પ્રકારના ગ્રાફિક્સ પ્રોસેસર દ્વારા કેનવાસ બતાવે છે; આર્ટવર્ક હંમેશાં CPU પર દોરાય છે. સ્વચાલિત Windows અને macOS પર સંકલિત પ્રોસેસરને પસંદ કરે છે. વેબ સંસ્કરણ તેનો ઉપયોગ કરતું નથી. + From the next start, the window shows each frame without waiting for the display's refresh where the graphics driver allows, at most 240 frames a second. આગલી શરૂઆતથી, જ્યાં ગ્રાફિક્સ ડ્રાઇવર મંજૂરી આપે ત્યાં વિન્ડો ડિસ્પ્લેના રિફ્રેશની રાહ જોયા વિના દરેક ફ્રેમ બતાવે છે, સેકન્ડ દીઠ વધુમાં વધુ 240 ફ્રેમ. From the next start, the desktop version draws with this kind of graphics processor; Automatic prefers the one that drives the display. The web version does not use it. આગલી શરૂઆતથી, ડેસ્કટોપ સંસ્કરણ આ પ્રકારના ગ્રાફિક્સ પ્રોસેસરથી દોરે છે; સ્વચાલિત ડિસ્પ્લે ચલાવતા પ્રોસેસરને પસંદ કરે છે. વેબ સંસ્કરણ તેનો ઉપયોગ કરતું નથી. From the next start, the window shows frames without waiting for the display to refresh, at most 240 a second; off, the display paces them. A present mode set at launch overrides it. આગલી શરૂઆતથી, વિન્ડો ડિસ્પ્લે રિફ્રેશની રાહ જોયા વિના ફ્રેમ બતાવે છે, સેકન્ડમાં વધુમાં વધુ 240; બંધ હોય ત્યારે ગતિ ડિસ્પ્લે નક્કી કરે છે. શરૂઆતમાં સેટ કરેલો પ્રેઝન્ટ મોડ પ્રાથમિકતા ધરાવે છે. The most undo steps each document keeps; lowering it drops the oldest steps when you click OK. Steps can also go sooner when they use too much memory. દરેક દસ્તાવેજ રાખે તે પૂર્વવત્ પગલાંની મહત્તમ સંખ્યા; ઓછી સંખ્યા ઠીક પર ક્લિક કરો ત્યારે સૌથી જૂનાં પગલાં દૂર કરે છે. પગલાં વધુ મેમરી લે ત્યારે વહેલાં પણ દૂર થઈ શકે છે. @@ -3482,6 +3508,9 @@ arrowhead Feather પીંછું Open Recent Files and the Home screen list at most this many recent files; 0 lists none, and VectorCraft still remembers up to 30. તાજેતરની ફાઇલો ખોલો અને હોમ સ્ક્રીન વધુમાં વધુ આટલી તાજેતરની ફાઇલો બતાવે છે; 0 એક પણ બતાવતું નથી, અને VectorCraft તો પણ 30 સુધી યાદ રાખે છે. When a document opens, a linked EPS image that shows its saved preview keeps it instead of reading the EPS file again; changed files still follow Update Links. દસ્તાવેજ ખૂલે ત્યારે, પોતાનું સાચવેલું પૂર્વાવલોકન બતાવતી લિંક કરેલી EPS છબી EPS ફાઇલ ફરીથી વાંચવાને બદલે તે પૂર્વાવલોકન રાખે છે; બદલાયેલી ફાઇલો હજુ પણ લિંક અપડેટ કરો ને અનુસરે છે. In Pixel Preview, images are drawn smoothed; off, their pixels show with hard edges. Outside Pixel Preview, images are always smoothed. પિક્સેલ પૂર્વાવલોકનમાં, છબીઓ સુંવાળી દોરાય છે; બંધ હોય ત્યારે, તેમના પિક્સેલ તીક્ષ્ણ કિનારીઓ સાથે દેખાય છે. પિક્સેલ પૂર્વાવલોકનની બહાર, છબીઓ હંમેશા સુંવાળી હોય છે. + PDF Text PDF ટેક્સ્ટ + The text of a PDF you open or embed comes in as editable type, or as outlines that look the same on a computer without its fonts. તમે ખોલો કે એમ્બેડ કરો તે PDF નું ટેક્સ્ટ સંપાદનયોગ્ય ટેક્સ્ટ તરીકે આવે છે, અથવા આઉટલાઇન્સ તરીકે, જે તેના ફૉન્ટ વગરના કમ્પ્યુટર પર પણ એકસરખી દેખાય છે. + Linked pages show the file's own text. લિંક કરેલાં પેજ ફાઇલનું પોતાનું ટેક્સ્ટ બતાવે છે. When a linked file changes, Automatically reads it again, Ask When Modified asks you first, and Manually leaves it and shows a note in the status bar. લિંક કરેલી ફાઇલ બદલાય ત્યારે, આપમેળે તેને ફરીથી વાંચે છે, ફેરફાર થાય ત્યારે પૂછો પહેલાં તમને પૂછે છે, અને જાતે તેને એમ જ રહેવા દે છે અને સ્ટેટસ બારમાં નોંધ બતાવે છે. On the desktop, the folder New from Template… and Save as Template… start in; leave it blank for VectorCraft Templates in your documents folder. ડેસ્કટોપ સંસ્કરણમાં, જે ફોલ્ડરમાં ટેમ્પ્લેટમાંથી નવું… અને ટેમ્પ્લેટ તરીકે સાચવો… શરૂ થાય છે; તમારા દસ્તાવેજ ફોલ્ડરમાંના VectorCraft Templates માટે તેને ખાલી છોડો. Edit Original opens a linked file in the system's default app for its type; off, a linked raster image opens in PhotoCraft where it is installed. મૂળ સંપાદિત કરો લિંક કરેલી ફાઇલને તેના પ્રકાર માટેની સિસ્ટમની ડિફૉલ્ટ ઍપમાં ખોલે છે; બંધ હોય ત્યારે, લિંક કરેલી રાસ્ટર છબી PhotoCraft ઇન્સ્ટોલ હોય તો તેમાં ખૂલે છે. @@ -3781,6 +3810,7 @@ arrowhead Feather પીંછું No recent commands કોઈ તાજેતરના આદેશો નથી Type to search commands, tools, panels and effects આદેશો, ટૂલ્સ, પેનલ્સ અને ઇફેક્ટ્સ શોધવા માટે લખો Recent તાજેતરના + Clear Recent Commands તાજેતરના આદેશો સાફ કરો Search commands આદેશો શોધો Search images છબીઓ શોધો Searching… શોધી રહ્યા છીએ… @@ -4798,9 +4828,14 @@ arrowhead Feather પીંછું {name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2} Wheel View વ્હીલ વ્યૂ Box View બૉક્સ વ્યૂ + Show Out-of-Gamut Colors ગેમટ બહારના રંગો બતાવો Box Channel બૉક્સ ચેનલ Color box રંગ બૉક્સ Color Wheel Options રંગ વ્હીલ વિકલ્પો + Show Document Colors દસ્તાવેજના રંગો બતાવો + Document Colors દસ્તાવેજના રંગો + Selection Colors પસંદગીના રંગો +@plural Used {n} time|Used {n} times {n} વાર વપરાયો|{n} વાર વપરાયો Show Harmony હાર્મની બતાવો Harmony Rule હાર્મની નિયમ Harmony color હાર્મની રંગ @@ -5634,6 +5669,20 @@ swatch [Registration] [રજિસ્ટ્રેશન] Standard Single-line Composer સ્ટાન્ડર્ડ સિંગલ-લાઇન કમ્પોઝર Standard Every-line Composer સ્ટાન્ડર્ડ એવરી-લાઇન કમ્પોઝર @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer આમાંથી એક હોવું જોઈએ: "singleLine", "everyLine", "standardSingleLine" અથવા "standardEveryLine" + Vector Packs વેક્ટર પૅક + Compass Rose દિશાસૂચક ગુલાબ + Botanical Sprig વનસ્પતિ ડાળી + Facet Diamond પાસાદાર હીરો + Tide Crest તરંગ શિખર + Leaf Vine પાંદડાની વેલ + Blossom Chain ફૂલોની સાંકળ + Pennant Garland ધ્વજપટ્ટીની માળા + Lantern String ફાનસની હાર + Orbit Lines ભ્રમણકક્ષાની રેખાઓ + Petal Garland પાંખડીઓની માળા + Lattice Braid જાળી વેણી + Facet Sweep પાસાદાર રેખા + Artistic Brushes કલાત્મક બ્રશ Paint રંગકામ Flat Sweep સપાટ લસરકો Dry Drag સૂકો ઘસારો diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index abff8da774..ecf0047d8b 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -1108,6 +1108,10 @@ arrowhead Feather पंख Cusp नुकीला बिंदु Straight segment सीधा सेगमेंट Circle too large वृत्त बहुत बड़ा है + Show Radii त्रिज्याएँ दिखाएँ + Show Diameter व्यास दिखाएँ + Anchors at Standard Positions मानक स्थानों पर एंकर पॉइंट्स + Third Point by Dragging खींचकर तीसरा बिंदु Circle (open) सर्किल (ओपन) Circle: वृत्त: Classic क्लासिक @@ -1273,9 +1277,14 @@ arrowhead Feather पंख {name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2} Wheel View व्हील व्यू Box View बॉक्स व्यू + Show Out-of-Gamut Colors गैमट से बाहर के रंग दिखाएँ Box Channel बॉक्स चैनल Color box कलर बॉक्स Color Wheel Options कलर व्हील ऑप्शन्स + Show Document Colors डॉक्यूमेंट के रंग दिखाएँ + Document Colors डॉक्यूमेंट के रंग + Selection Colors चयन के रंग +@plural Used {n} time|Used {n} times {n} बार उपयोग किया गया|{n} बार उपयोग किया गया Show Harmony सद्भाव दिखाएँ Harmony Rule सद्भाव नियम Harmony color सद्भाव रंग @@ -1640,6 +1649,10 @@ arrowhead Feather पंख Delete Guide गाइड हटाएँ Delete Guides गाइड्स हटाएँ Delete Image Trace Preset डिलीट इमेज ट्रेस प्रीसेट + Tracing Presets… ट्रेसिंग प्रीसेट… + Import Image Trace Presets आयात इमेज ट्रेस प्रीसेट्स + Export Image Trace Presets निर्यात इमेज ट्रेस प्रीसेट्स + Replace the saved presets that have these names? इन नामों वाले सेव किए गए प्रीसेट बदलें? Delete Instances इंस्टेंस हटाएँ Delete Layer लेयर हटाएँ Delete Library लाइब्रेरी हटाएँ @@ -3001,6 +3014,11 @@ arrowhead Feather पंख Knife चाकू Knockout Group नॉकआउट समूह Lab Lab + OKLCH Sliders OKLCH स्लाइडर्स + HSL Sliders HSL स्लाइडर्स + Chroma क्रोमा + The largest chroma sRGB holds at this lightness and hue इस लाइटनेस और ह्यू पर sRGB में आने वाला सबसे अधिक क्रोमा + OKLCH needs sRGB as the working RGB space OKLCH के लिए वर्किंग RGB स्पेस sRGB होना चाहिए Lab Spot Colors लैब स्पॉट रंग Lab Spot Colors: लैब स्पॉट रंग: Lab Values लैब मूल्य @@ -3999,6 +4017,13 @@ arrowhead Feather पंख Pen Tool पेन टूल Quick Pen Tool क्विक पेन टूल Quick Pen क्विक पेन + Quick Pen Toolbar क्विक पेन टूलबार + Continuous Arc सतत आर्क + Sharp Corner Arc तीखे कोने वाला आर्क + Flip Arc आर्क पलटें + Hide Toolbar टूलबार छिपाएँ + Pin Toolbar Position टूलबार स्थिति पिन करें + Reset Toolbar Position टूलबार स्थिति रीसेट करें Pencil पेंसिल Pencil Tool पेंसिल टूल Pentagram पेंटाग्राम @@ -4575,6 +4600,8 @@ arrowhead Feather पंख Reset all Revolve settings to their defaults. सभी रिवॉल्व सेटिंग्स डिफ़ॉल्ट पर रीसेट करें। Reset Automation स्वचालन रीसेट करें Reset Bar Position बार स्थिति रीसेट करें + Bar Actions बार क्रियाएँ + Reset Bar Actions बार क्रियाएँ रीसेट करें Reset Bounding Box बाउंडिंग बॉक्स रीसेट करें Rotate Bounding Box बाउंडिंग बॉक्स घुमाएँ Rotate Bounding Box… बाउंडिंग बॉक्स घुमाएँ… @@ -4603,6 +4630,11 @@ arrowhead Feather पंख Edit Arrowheads एरोहेड्स संपादित करें Edit Arrowheads… एरोहेड्स संपादित करें… Reload Arrowheads एरोहेड्स फिर से लोड करें + Bevels बेवल्स + Edit Bevels बेवल्स संपादित करें + Edit Bevels… बेवल्स संपादित करें… + {name} (document) {name} (दस्तावेज़) + Reload Bevels बेवल्स फिर से लोड करें Reset Rotate View व्यू घुमाएँ रीसेट करें Reset Ruler Origin रूलर ओरिजिन रीसेट करें Reset Symbol Instance सिंबल इंस्टेंस रीसेट करें @@ -4760,9 +4792,13 @@ arrowhead Feather पंख Edit type set in fonts that aren't available? जो फ़ॉन्ट उपलब्ध नहीं हैं, उनमें सेट टेक्स्ट एडिट करें? Shows each slice's number in a box at its top left on the canvas; off, the slice outlines still show. कैनवास पर हर स्लाइस का नंबर उसके ऊपरी बाएँ कोने में एक बॉक्स में दिखाता है; बंद होने पर भी स्लाइस की आउटलाइन दिखती रहती हैं। The color of user and object slice outlines and their number boxes; auto slices use a dimmer shade of it. यूज़र और ऑब्जेक्ट स्लाइस की आउटलाइन और उनके नंबर बॉक्स का रंग; ऑटो स्लाइस इसकी हल्की छाया इस्तेमाल करते हैं। + In paragraphs with Hyphenate on, a listed word is hyphenated only at the hyphens typed in it, or never when it has none, whatever its language or case. जिन पैराग्राफ़ में हाइफ़नेशन चालू है, उनमें सूची के शब्द पर हाइफ़न केवल उसमें टाइप किए गए हाइफ़न पर लगता है, या कोई न हो तो कभी नहीं, उसकी भाषा या केस चाहे जो हो। + On the desktop, this folder's .wasm plug-ins load at startup and when OK sets a new folder, except in Safe Mode; one that asks for permissions loads only after you grant them. The web version loads none. डेस्कटॉप संस्करण में, इस फ़ोल्डर के .wasm प्लग-इन शुरू होने पर और ठीक है से नया फ़ोल्डर सेट होने पर लोड होते हैं, सुरक्षित मोड को छोड़कर; अनुमतियाँ माँगने वाला प्लग-इन आपके उन्हें देने के बाद ही लोड होता है। वेब संस्करण कोई लोड नहीं करता। + Large gives each filter or command plug-in run at least 250 million instructions, with the same time limit; Normal keeps the plug-in's own budget. Live effects, exporters and importers keep theirs. बड़ा फ़िल्टर या कमांड प्लग-इन के हर रन को उसी समय सीमा के साथ कम से कम 25 करोड़ निर्देश देता है; सामान्य प्लग-इन का अपना बजट रखता है। लाइव इफ़ेक्ट, एक्सपोर्टर और इंपोर्टर अपना बजट रखते हैं। New type takes this language while Document Setup's language is English: USA; type already in a document keeps its own language. जब तक डॉक्यूमेंट सेटअप की भाषा अंग्रेज़ी: USA है, नए टेक्स्ट को यह भाषा मिलती है; डॉक्यूमेंट में पहले से मौजूद टेक्स्ट अपनी भाषा रखता है। In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its language or case. जिन पैराग्राफ़ में हाइफ़नेशन चालू है, उनमें सूची का शब्द केवल उसमें टाइप किए गए हाइफ़न पर टूटता है, या कोई न हो तो कहीं नहीं, उसकी भाषा या केस चाहे जो हो। On the desktop, the .wasm plug-ins in this folder load at startup and when you click OK with a new folder here, except in Safe Mode; the web version does not load them. डेस्कटॉप संस्करण में, इस फ़ोल्डर के .wasm प्लग-इन शुरू होने पर और यहाँ नया फ़ोल्डर देकर ठीक है पर क्लिक करने पर लोड होते हैं, सुरक्षित मोड को छोड़कर; वेब संस्करण उन्हें लोड नहीं करता। + Normal keeps each plug-in's own limits; with Large, a plug-in filter or command may run at least 250 million instructions besides those for its input. The time limit stays the same. सामान्य हर प्लग-इन की अपनी सीमाएँ रखता है; बड़ा के साथ, प्लग-इन फ़िल्टर या कमांड अपने इनपुट के निर्देशों के अलावा कम से कम 250 मिलियन निर्देश चला सकता है। समय सीमा वही रहती है। How many instructions each run of a plug-in object filter may use; Large allows more than Normal with the same 60-second limit. Heavy filters keep their own budget. प्लग-इन के ऑब्जेक्ट फ़िल्टर का हर रन कितने निर्देश इस्तेमाल कर सकता है; बड़ा सामान्य से अधिक की अनुमति देता है, 60 सेकंड की उसी सीमा के साथ। भारी फ़िल्टर अपना बजट रखते हैं। The first scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. पहला स्क्रैच डिस्क विकल्प: Startup, None या फ़ोल्डर पाथ; VectorCraft इसे सहेजता है, पर अभी स्क्रैच डिस्क का उपयोग नहीं करता। The second scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. दूसरा स्क्रैच डिस्क विकल्प: Startup, None या फ़ोल्डर पाथ; VectorCraft इसे सहेजता है, पर अभी स्क्रैच डिस्क का उपयोग नहीं करता। @@ -4774,13 +4810,15 @@ arrowhead Feather पंख Shows each tool group's name above its tools in the toolbar; off, the groups follow one another with nothing between them. टूलबार में हर टूल ग्रुप का नाम उसके टूल्स के ऊपर दिखाता है; बंद होने पर, ग्रुप बिना किसी अंतर के एक के बाद एक आते हैं। From now on, documents you open or create open as tabs; off, each opens in a floating window. Documents already open stay where they are. अब से आप जो डॉक्यूमेंट ओपन करते या बनाते हैं, वे टैब के रूप में खुलते हैं; बंद होने पर, हर एक फ़्लोटिंग विंडो में खुलता है। पहले से खुले डॉक्यूमेंट जहाँ हैं वहीं रहते हैं। Makes the document tabs taller and their names larger. डॉक्यूमेंट टैब को ऊँचा और उनके नाम बड़े बनाता है। - From the next start, the system draws the window's title bar where VectorCraft would otherwise draw its own. अगली शुरुआत से, जहाँ VectorCraft अन्यथा अपना टाइटल बार बनाता, वहाँ सिस्टम विंडो का टाइटल बार बनाता है। - From the next start, VectorCraft draws the window's title bar even where the desktop would draw it, unless System Title Bar is on. अगली शुरुआत से, VectorCraft विंडो का टाइटल बार वहाँ भी बनाता है जहाँ डेस्कटॉप उसे बनाता, जब तक सिस्टम टाइटल बार चालू न हो। + From the next start, the system draws the window's title bar where VectorCraft would otherwise draw its own; on Linux and the BSDs, the VECTORCRAFT_TITLEBAR variable takes precedence. अगली शुरुआत से, जहाँ VectorCraft अन्यथा अपना टाइटल बार बनाता, वहाँ सिस्टम विंडो का टाइटल बार बनाता है; Linux और BSD पर VECTORCRAFT_TITLEBAR वेरिएबल को प्राथमिकता मिलती है। + From the next start, VectorCraft draws the window's title bar even where the desktop would draw it, unless System Title Bar is on or the VECTORCRAFT_TITLEBAR variable chooses it. अगली शुरुआत से, VectorCraft विंडो का टाइटल बार वहाँ भी बनाता है जहाँ डेस्कटॉप उसे बनाता, जब तक सिस्टम टाइटल बार चालू न हो या VECTORCRAFT_TITLEBAR वेरिएबल उसे न चुने। Makes the interface larger or smaller; art on the canvas keeps its size at the same zoom. इंटरफ़ेस को बड़ा या छोटा करता है; उसी ज़ूम पर कैनवास का आर्टवर्क अपना आकार बनाए रखता है। The tool pointers VectorCraft draws grow and shrink with UI Scaling; off, they keep their size. VectorCraft जो टूल पॉइंटर बनाता है, वे यूआई स्केलिंग के साथ बड़े और छोटे होते हैं; बंद होने पर, वे अपना आकार बनाए रखते हैं। The language of the interface; Auto uses the system's language. The dialog switches language as soon as you choose one. इंटरफ़ेस की भाषा; स्वचालित सिस्टम की भाषा इस्तेमाल करता है। आप कोई भाषा चुनते ही डायलॉग उस भाषा में बदल जाता है। Animated Zoom works only while this is on; off, Animated Zoom is dimmed and zooming does not animate. एनिमेटेड ज़ूम केवल तभी काम करता है जब यह चालू हो; बंद होने पर, एनिमेटेड ज़ूम धुंधला हो जाता है और ज़ूम एनिमेट नहीं होता। The wheel's zoom glides in, and the Zoom tool zooms as you drag sideways or hold it down; off, the Zoom tool zooms to the area you drag across. व्हील से ज़ूम सहजता से सरकता है, और ज़ूम टूल बगल में खींचने या दबाए रखने पर ज़ूम करता है; बंद होने पर, ज़ूम टूल उस क्षेत्र पर ज़ूम करता है जिस पर आप खींचते हैं। + From the next start, the desktop version shows the canvas through this kind of graphics processor; the artwork is drawn on the CPU either way. Automatic prefers the integrated one on Windows and macOS. The web version does not use it. अगली शुरुआत से, डेस्कटॉप संस्करण इस प्रकार के ग्राफ़िक्स प्रोसेसर के ज़रिए कैनवास दिखाता है; आर्टवर्क हमेशा CPU पर बनता है। स्वचालित Windows और macOS पर इंटीग्रेटेड प्रोसेसर को प्राथमिकता देता है। वेब संस्करण इसका उपयोग नहीं करता। + From the next start, the window shows each frame without waiting for the display's refresh where the graphics driver allows, at most 240 frames a second. अगली शुरुआत से, जहाँ ग्राफ़िक्स ड्राइवर अनुमति देता है, विंडो डिस्प्ले के रीफ़्रेश की प्रतीक्षा किए बिना हर फ़्रेम दिखाती है, अधिकतम 240 फ़्रेम प्रति सेकंड। From the next start, the desktop version draws with this kind of graphics processor; Automatic prefers the one that drives the display. The web version does not use it. अगली शुरुआत से, डेस्कटॉप संस्करण इस प्रकार के ग्राफ़िक्स प्रोसेसर से बनाता है; स्वचालित उस प्रोसेसर को प्राथमिकता देता है जो डिस्प्ले चलाता है। वेब संस्करण इसका उपयोग नहीं करता। From the next start, the window shows frames without waiting for the display to refresh, at most 240 a second; off, the display paces them. A present mode set at launch overrides it. अगली शुरुआत से, विंडो डिस्प्ले रीफ़्रेश का इंतज़ार किए बिना फ़्रेम दिखाती है, एक सेकंड में अधिकतम 240; बंद होने पर गति डिस्प्ले तय करता है। शुरुआत पर सेट किया गया प्रेज़ेंट मोड प्राथमिकता रखता है। The most undo steps each document keeps; lowering it drops the oldest steps when you click OK. Steps can also go sooner when they use too much memory. हर दस्तावेज़ अधिकतम जितने पूर्ववत चरण रखता है; कम संख्या ठीक है पर क्लिक करने पर सबसे पुराने चरण हटा देती है। ज़्यादा मेमोरी लेने पर चरण पहले भी हट सकते हैं। @@ -4799,6 +4837,9 @@ arrowhead Feather पंख Open Recent Files and the Home screen list at most this many recent files; 0 lists none, and VectorCraft still remembers up to 30. रीसेंट फ़ाइल्स मेनू व होम स्क्रीन अधिकतम इतनी हाल की फ़ाइलें दिखाते हैं; 0 कोई नहीं दिखाता, फिर भी VectorCraft 30 तक याद रखता है। When a document opens, a linked EPS image that shows its saved preview keeps it instead of reading the EPS file again; changed files still follow Update Links. डॉक्यूमेंट खुलने पर, अपना सेव किया प्रीव्यू दिखाने वाली लिंक की गई EPS इमेज EPS फ़ाइल को फिर से पढ़ने के बजाय वही प्रीव्यू रखती है; बदली हुई फ़ाइलें फिर भी अद्यतन लिंक के अनुसार चलती हैं। In Pixel Preview, images are drawn smoothed; off, their pixels show with hard edges. Outside Pixel Preview, images are always smoothed. पिक्सेल प्रीव्यू में, इमेज स्मूद बनाई जाती हैं; बंद होने पर, उनके पिक्सेल के किनारे तीखे दिखते हैं। पिक्सेल प्रीव्यू के बाहर, इमेज हमेशा स्मूद होती हैं। + PDF Text PDF टेक्स्ट + The text of a PDF you open or embed comes in as editable type, or as outlines that look the same on a computer without its fonts. आप जो PDF खोलते या एम्बेड करते हैं, उसका टेक्स्ट संपादन योग्य टेक्स्ट के रूप में आता है, या रूपरेखा के रूप में, जो उसके फ़ॉन्ट के बिना वाले कंप्यूटर पर भी वैसी ही दिखती है। + Linked pages show the file's own text. लिंक किए गए पृष्ठ फ़ाइल का अपना टेक्स्ट दिखाते हैं। When a linked file changes, Automatically reads it again, Ask When Modified asks you first, and Manually leaves it and shows a note in the status bar. जब कोई लिंक की गई फ़ाइल बदलती है, अपने-आप उसे फिर से पढ़ता है, बदलाव होने पर पूछें पहले आपसे पूछता है, व मैन्युअल उसे वैसे ही छोड़कर स्टेटस बार में एक नोट दिखाता है। On the desktop, the folder New from Template… and Save as Template… start in; leave it blank for VectorCraft Templates in your documents folder. डेस्कटॉप संस्करण में, वह फ़ोल्डर जिसमें टेम्पलेट से नया… व टेम्पलेट के रूप में सेव करें… शुरू होते हैं; अपने डॉक्यूमेंट फ़ोल्डर में VectorCraft Templates के लिए इसे खाली छोड़ें। Edit Original opens a linked file in the system's default app for its type; off, a linked raster image opens in PhotoCraft where it is installed. मूल एडिट करें लिंक की गई फ़ाइल को उसके प्रकार के लिए सिस्टम के डिफ़ॉल्ट ऐप में खोलता है; बंद होने पर, लिंक की गई रास्टर इमेज PhotoCraft इंस्टॉल होने पर उसमें खुलती है। @@ -5125,6 +5166,7 @@ arrowhead Feather पंख Recent Commands हाल के आदेश No recent commands कोई हाल का आदेश नहीं Type to search commands, tools, panels and effects आदेश, टूल, पैनल्स और इफ़ेक्ट्स खोजने के लिए टाइप करें + Clear Recent Commands हाल के आदेश साफ़ करें Search commands आदेश खोजें Search Commands… कमांड खोजें… Search Fonts Folder खोज फ़ॉन्ट फ़ोल्डर @@ -7064,6 +7106,8 @@ arrowhead Feather पंख @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` को grayscale, rgb, hsb, cmyk या websafe होना चाहिए @msg `view` must be wheel or box `view` को wheel या box होना चाहिए @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` को hue, saturation, brightness, red, green या blue होना चाहिए +@msg `sliders` must be none, oklch or hsl `sliders` none, oklch या hsl होना चाहिए +@msg OKLCH needs sRGB as the working RGB space OKLCH के लिए वर्किंग RGB स्पेस sRGB होना चाहिए @msg `mode` must be one of {_1} `mode` को {_1} में से एक होना चाहिए @msg `mojikumi` must be "none", "yakumonoHankaku", "gyomatsuYakumonoHankaku", "gyomatsuYakumonoZenkaku", "yakumonoZenkaku" or "lineEndHalf" `mojikumi` "none", "yakumonoHankaku", "gyomatsuYakumonoHankaku", "gyomatsuYakumonoZenkaku", "yakumonoZenkaku" या "lineEndHalf" होना चाहिए। @msg `name` is empty `name` खाली है @@ -8894,6 +8938,10 @@ liquify-list-end {0}, {1} {0} और {1} @msg select a text object एक टेक्स्ट ऑब्जेक्ट चुनें @msg select an envelope एक लिफाफे सिलेक्ट करें @msg select an image एक इमेज चुनें +@msg object {_1} is an image changed by Perspective Distort or Free Distort, which this command does not work on ऑब्जेक्ट {_1} पर्सपेक्टिव या फ़्री डिस्टॉर्ट से बदली गई इमेज है, जिस पर यह कमांड काम नहीं करता +@msg image {_1} cannot be distorted this way: its corners would not make a convex shape इमेज {_1} को इस तरह डिस्टॉर्ट नहीं किया जा सकता: इसके कोने उत्तल आकार नहीं बनाएँगे +@msg image {_1} cannot be distorted this way: its corners would cross the warp's horizon इमेज {_1} को इस तरह डिस्टॉर्ट नहीं किया जा सकता: इसके कोने डिस्टॉर्ट के क्षितिज को पार कर जाएँगे +@msg image {_1} cannot be distorted this way: its corners would be too close together for a perspective map इमेज {_1} को इस तरह डिस्टॉर्ट नहीं किया जा सकता: इसके कोने पर्सपेक्टिव मैपिंग के लिए एक-दूसरे के बहुत पास होंगे @msg `background` must be edges, corners or colors `background` edges, corners या colors होना चाहिए @msg `match` must be distance or channels `match` distance या channels होना चाहिए @msg `{key}` must be from 0 to 100 `{key}` 0 से 100 तक होना चाहिए @@ -9145,7 +9193,10 @@ liquify-list-end {0}, {1} {0} और {1} @msg the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate) ऑब्जेक्ट पर कोई 3D इफ़ेक्ट नहीं है (एक्सट्रूडेड और बेवेल, रिवॉल्व, फुलाएँ या घुमाव) @msg `render` must be an object holding only `mode`, set to shaded or wireframe `render` केवल `mode` वाला ऑब्जेक्ट होना चाहिए, जिसका मान shaded या wireframe हो @msg its 3D effect builds no solid इसका 3D इफ़ेक्ट कोई ठोस नहीं बनाता -@msg bevel must be none or one of {_1} bevel को none या {_1} में से एक होना चाहिए +@msg bevel must be none or one of {_1}, or custom with {BEVEL_PROFILE} bevel को none, {_1} में से एक, या {BEVEL_PROFILE} के साथ custom होना चाहिए +@msg bevel custom needs {BEVEL_PROFILE}, the bevel's points bevel custom के लिए {BEVEL_PROFILE} चाहिए, यानी बेवल के बिंदु +@msg {BEVEL_NAME} must be a string {BEVEL_NAME} एक स्ट्रिंग होना चाहिए +@msg {BEVEL_PROFILE} must be 2 to {most} [x, y] points, each share between 0 and 1, from [0, 0] (the cap's edge) to [1, 1] (the side wall) {BEVEL_PROFILE} में 2 से {most} [x, y] बिंदु होने चाहिए, हर हिस्सा 0 और 1 के बीच, [0, 0] (सिरे की सतह का किनारा) से [1, 1] (बगल की दीवार) तक @msg {_1} can't build solids from this art: its symbol instances, blends and clipping groups hold too many objects {_1} इस आर्ट से ठोस नहीं बना सकता: इसके सिंबल इंस्टेंस, ब्लेंड और क्लिपिंग ग्रुप में बहुत अधिक ऑब्जेक्ट हैं @msg {label} can't build a solid from the instance of symbol "{symbol}": the symbol's art isn't available {label} सिंबल "{symbol}" के इंस्टेंस से ठोस नहीं बना सकता: सिंबल का आर्ट उपलब्ध नहीं है @msg {_1}: the clipping path is too complex to cut the art with {_1}: क्लिपिंग पाथ आर्ट को काटने के लिए बहुत जटिल है @@ -10354,6 +10405,20 @@ theme Appearance अपीयरेंस @msg A panel is not joined to the rest by a crease. कोई पैनल किसी क्रीज़ लाइन से बाकी से जुड़ा नहीं है। @msg A fold line is on a non-printing layer. एक फ़ोल्ड लाइन नॉन-प्रिंटिंग लेयर पर है। @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} पैनल: {panels}, हिंज: {hinges}, एरर: {errors}, वॉर्निंग: {warnings} + Vector Packs वेक्टर पैक + Compass Rose दिशासूचक गुलाब + Botanical Sprig वनस्पति टहनी + Facet Diamond पहलूदार हीरा + Tide Crest लहर की चोटी + Leaf Vine पत्तों की बेल + Blossom Chain फूलों की शृंखला + Pennant Garland झंडियों की माला + Lantern String लालटेन की शृंखला + Orbit Lines कक्षीय रेखाएँ + Petal Garland पंखुड़ी माला + Lattice Braid जाली चोटी + Facet Sweep पहलूदार स्ट्रोक + Artistic Brushes कलात्मक ब्रश Paint चित्रकारी Flat Sweep सपाट फेरा Dry Drag सूखा घिसाव diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index d6ee13c6d7..085633cf7e 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -673,6 +673,10 @@ arrowhead Target Céltábla Cusp Csúcspont Straight segment Egyenes szakasz Circle too large A kör túl nagy + Show Radii Sugarak megjelenítése + Show Diameter Átmérő megjelenítése + Anchors at Standard Positions Horgonypontok szabványos helyeken + Third Point by Dragging Harmadik pont húzással Circle (open) Kör (nyitott) Classic Defaults Klasszikus alapértékek Clean Up… Tisztítás… @@ -814,9 +818,14 @@ arrowhead Target Céltábla {name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2} Wheel View Körnézet Box View Négyzetnézet + Show Out-of-Gamut Colors Színtartományon kívüli színek megjelenítése Box Channel Négyzet csatornája Color box Színnégyzet Color Wheel Options Színkör beállításai + Show Document Colors Dokumentumszínek megjelenítése + Document Colors Dokumentumszínek + Selection Colors A kijelölés színei +@plural Used {n} time|Used {n} times {n} alkalommal használva Show Harmony Harmónia megjelenítése Harmony Rule Harmóniaszabály Harmony color Harmóniaszín @@ -2521,6 +2530,11 @@ file-filter Templates Sablonok Knife Kés Knockout Group Kiütő csoport Lab Lab + OKLCH Sliders OKLCH csúszkák + HSL Sliders HSL csúszkák + Chroma Króma + The largest chroma sRGB holds at this lightness and hue A legnagyobb króma, amelyet az sRGB ezen a világosságon és színárnyalaton tartalmaz + OKLCH needs sRGB as the working RGB space Az OKLCH-hoz sRGB munka-RGB-színtér szükséges Lab Spot Colors Lab-direktszínek Lab Spot Colors: Lab-direktszínek: Lab Values Lab-értékek @@ -3332,6 +3346,13 @@ file-filter Templates Sablonok Pen Tool Toll Quick Pen Tool Gyorstoll Quick Pen Gyorstoll + Quick Pen Toolbar Gyorstoll eszköztár + Continuous Arc Folytonos ív + Sharp Corner Arc Éles sarkú ív + Flip Arc Ív tükrözése + Hide Toolbar Eszköztár elrejtése + Pin Toolbar Position Eszköztár helyének rögzítése + Reset Toolbar Position Eszköztár helyének visszaállítása Pencil Ceruza Pencil Tool Ceruza Pentagram Pentagram @@ -3788,6 +3809,8 @@ mark-style Japanese Japán Reset all Revolve settings to their defaults. A tengely körüli forgatás minden beállítását visszaállítja az alapértékre. Reset Automation Automation visszaállítása Reset Bar Position Sáv helyének visszaállítása + Bar Actions Sáv műveletei + Reset Bar Actions Sáv műveleteinek visszaállítása Reset Bounding Box Befoglaló keret visszaállítása Rotate Bounding Box Befoglaló keret elforgatása Rotate Bounding Box… Befoglaló keret elforgatása… @@ -3816,6 +3839,11 @@ mark-style Japanese Japán Edit Arrowheads Nyílhegyek szerkesztése Edit Arrowheads… Nyílhegyek szerkesztése… Reload Arrowheads Nyílhegyek újratöltése + Bevels Élletörések + Edit Bevels Élletörések szerkesztése + Edit Bevels… Élletörések szerkesztése… + {name} (document) {name} (dokumentum) + Reload Bevels Élletörések újratöltése Reset Rotate View Nézetforgatás visszaállítása Rotate View to Selection Nézet elforgatása a kijelöléshez Reset the rows to the artwork's colors Sorok visszaállítása a grafika színeire @@ -3969,9 +3997,13 @@ mark-style Japanese Japán Edit type set in fonts that aren't available? Szerkeszti a nem elérhető betűtípusokkal szedett szöveget? Shows each slice's number in a box at its top left on the canvas; off, the slice outlines still show. A vásznon minden szelet számát egy keretben mutatja a szelet bal felső sarkában; kikapcsolva a szeletek körvonalai továbbra is látszanak. The color of user and object slice outlines and their number boxes; auto slices use a dimmer shade of it. A felhasználói és objektumszeletek körvonalainak és számkereteinek színe; az automatikus szeletek ennek egy halványabb árnyalatát használják. + In paragraphs with Hyphenate on, a listed word is hyphenated only at the hyphens typed in it, or never when it has none, whatever its language or case. Azokban a bekezdésekben, ahol az Elválasztás be van kapcsolva, a felsorolt szó csak a beleírt kötőjeleknél kap elválasztójelet, vagy soha, ha nincs benne, nyelvétől és kis- vagy nagybetűitől függetlenül. + On the desktop, this folder's .wasm plug-ins load at startup and when OK sets a new folder, except in Safe Mode; one that asks for permissions loads only after you grant them. The web version loads none. Az asztali változatban a mappa .wasm bővítményei indításkor töltődnek be, és amikor az OK új mappát állít be, kivéve csökkentett módban; az engedélyeket kérő bővítmény csak azok megadása után töltődik be. A webes változat egyet sem tölt be. + Large gives each filter or command plug-in run at least 250 million instructions, with the same time limit; Normal keeps the plug-in's own budget. Live effects, exporters and importers keep theirs. A Nagy egy szűrő- vagy parancsbővítmény minden futásának legalább 250 millió utasítást ad, ugyanazzal az időkorláttal; a Normál megtartja a bővítmény saját keretét. Az élő effektusok, exportálók és importálók megtartják a sajátjukat. New type takes this language while Document Setup's language is English: USA; type already in a document keeps its own language. Az új szöveg ezt a nyelvet kapja, amíg a Dokumentumbeállítás nyelve Angol: amerikai; a dokumentumban már meglévő szöveg megtartja a saját nyelvét. In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its language or case. Azokban a bekezdésekben, ahol az Elválasztás be van kapcsolva, a felsorolt szó csak a beleírt kötőjeleknél válik el, vagy sehol, ha nincs benne, nyelvétől és kis- vagy nagybetűitől függetlenül. On the desktop, the .wasm plug-ins in this folder load at startup and when you click OK with a new folder here, except in Safe Mode; the web version does not load them. Az asztali változatban a mappa .wasm bővítményei indításkor töltődnek be, és amikor itt új mappával az OK gombra kattint, kivéve csökkentett módban; a webes változat nem tölti be őket. + Normal keeps each plug-in's own limits; with Large, a plug-in filter or command may run at least 250 million instructions besides those for its input. The time limit stays the same. A Normál megtartja minden bővítmény saját korlátait; a Nagy beállítással egy bővítményszűrő vagy -parancs legalább 250 millió utasítást futtathat a bemenetéhez tartozókon felül. Az időkorlát nem változik. How many instructions each run of a plug-in object filter may use; Large allows more than Normal with the same 60-second limit. Heavy filters keep their own budget. Hány utasítást használhat egy bővítmény objektumszűrőjének egy-egy futása; a Nagy többet enged, mint a Normál, ugyanazzal a 60 másodperces korláttal. A nehéz szűrők megtartják saját keretüket. The first scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. Az első munkalemez-választás: Startup, None vagy egy mappa elérési útja; a VectorCraft tárolja, de munkalemezeket még nem használ. The second scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. A második munkalemez-választás: Startup, None vagy egy mappa elérési útja; a VectorCraft tárolja, de munkalemezeket még nem használ. @@ -3983,13 +4015,15 @@ mark-style Japanese Japán Shows each tool group's name above its tools in the toolbar; off, the groups follow one another with nothing between them. Az eszköztárban minden eszközcsoport nevét az eszközei fölött mutatja; kikapcsolva a csoportok egymás után következnek, semmi sincs köztük. From now on, documents you open or create open as tabs; off, each opens in a floating window. Documents already open stay where they are. Mostantól a megnyitott vagy létrehozott dokumentumok lapfülön nyílnak meg; kikapcsolva mindegyik lebegő ablakban nyílik meg. A már megnyitott dokumentumok a helyükön maradnak. Makes the document tabs taller and their names larger. Magasabbá teszi a dokumentumok lapfüleit, a nevüket pedig nagyobbá. - From the next start, the system draws the window's title bar where VectorCraft would otherwise draw its own. A következő indítástól a rendszer rajzolja az ablak címsorát ott, ahol a VectorCraft egyébként a sajátját rajzolná. - From the next start, VectorCraft draws the window's title bar even where the desktop would draw it, unless System Title Bar is on. A következő indítástól a VectorCraft rajzolja az ablak címsorát ott is, ahol az asztali környezet rajzolná, hacsak nincs bekapcsolva a Rendszer címsora. + From the next start, the system draws the window's title bar where VectorCraft would otherwise draw its own; on Linux and the BSDs, the VECTORCRAFT_TITLEBAR variable takes precedence. A következő indítástól a rendszer rajzolja az ablak címsorát ott, ahol a VectorCraft egyébként a sajátját rajzolná; Linuxon és a BSD-rendszereken a VECTORCRAFT_TITLEBAR változó élvez elsőbbséget. + From the next start, VectorCraft draws the window's title bar even where the desktop would draw it, unless System Title Bar is on or the VECTORCRAFT_TITLEBAR variable chooses it. A következő indítástól a VectorCraft rajzolja az ablak címsorát ott is, ahol az asztali környezet rajzolná, hacsak nincs bekapcsolva a Rendszer címsora, vagy a VECTORCRAFT_TITLEBAR változó nem választja ki. Makes the interface larger or smaller; art on the canvas keeps its size at the same zoom. Nagyobbá vagy kisebbé teszi a felületet; a vásznon lévő grafika azonos nagyításnál megtartja a méretét. The tool pointers VectorCraft draws grow and shrink with UI Scaling; off, they keep their size. A VectorCraft által rajzolt eszközmutatók a Felület méretezésével együtt nőnek és kisebbednek; kikapcsolva megtartják a méretüket. The language of the interface; Auto uses the system's language. The dialog switches language as soon as you choose one. A felület nyelve; az Automatikus a rendszer nyelvét használja. A párbeszédablak azonnal nyelvet vált, amint választ egyet. Animated Zoom works only while this is on; off, Animated Zoom is dimmed and zooming does not animate. Az Animált nagyítás csak akkor működik, ha ez be van kapcsolva; kikapcsolva az Animált nagyítás halvány, és a nagyítás nem animált. The wheel's zoom glides in, and the Zoom tool zooms as you drag sideways or hold it down; off, the Zoom tool zooms to the area you drag across. A görgős nagyítás simán úszik be, a Nagyító pedig akkor nagyít, amikor oldalra húz vagy lenyomva tartja; kikapcsolva a Nagyító arra a területre nagyít, amelyen áthúz. + From the next start, the desktop version shows the canvas through this kind of graphics processor; the artwork is drawn on the CPU either way. Automatic prefers the integrated one on Windows and macOS. The web version does not use it. A következő indítástól az asztali változat ilyen típusú grafikus processzoron keresztül jeleníti meg a vásznat; a grafikát minden esetben a CPU rajzolja. Az Automatikus Windowson és macOS-en az integráltat részesíti előnyben. A webes változat nem használja. + From the next start, the window shows each frame without waiting for the display's refresh where the graphics driver allows, at most 240 frames a second. A következő indítástól az ablak minden képkockát a kijelző frissítésének kivárása nélkül jelenít meg, ahol a grafikus illesztőprogram engedi, legfeljebb másodpercenként 240 képkockát. From the next start, the desktop version draws with this kind of graphics processor; Automatic prefers the one that drives the display. The web version does not use it. A következő indítástól az asztali változat ilyen típusú grafikus processzorral rajzol; az Automatikus a kijelzőt meghajtót részesíti előnyben. A webes változat nem használja. From the next start, the window shows frames without waiting for the display to refresh, at most 240 a second; off, the display paces them. A present mode set at launch overrides it. A következő indítástól az ablak a képkockákat a kijelző frissítésére várás nélkül jeleníti meg, legfeljebb másodpercenként 240-et; kikapcsolva a kijelző diktálja az ütemet. Az indításkor megadott megjelenítési mód felülírja. The most undo steps each document keeps; lowering it drops the oldest steps when you click OK. Steps can also go sooner when they use too much memory. A dokumentumonként megőrzött visszavonási lépések legnagyobb száma; kisebb szám az OK gombra kattintáskor törli a legrégebbi lépéseket. A lépések korábban is törlődhetnek, ha túl sok memóriát foglalnak. @@ -4008,6 +4042,9 @@ mark-style Japanese Japán Open Recent Files and the Home screen list at most this many recent files; 0 lists none, and VectorCraft still remembers up to 30. A Legutóbbi fájlok megnyitása és a Kezdőképernyő legfeljebb ennyi legutóbbi fájlt sorol fel; 0 esetén egyet sem, és a VectorCraft ekkor is megjegyez legfeljebb 30-at. When a document opens, a linked EPS image that shows its saved preview keeps it instead of reading the EPS file again; changed files still follow Update Links. Dokumentum megnyitásakor a mentett előnézetét mutató csatolt EPS-kép megtartja azt, ahelyett hogy újra beolvasná az EPS-fájlt; a módosult fájlokra továbbra is a Csatolások frissítése érvényes. In Pixel Preview, images are drawn smoothed; off, their pixels show with hard edges. Outside Pixel Preview, images are always smoothed. Pixeles előnézetben a képek simítva jelennek meg; kikapcsolva a képpontjaik éles szélűek. A Pixeles előnézeten kívül a képek mindig simítottak. + PDF Text PDF-szöveg + The text of a PDF you open or embed comes in as editable type, or as outlines that look the same on a computer without its fonts. A megnyitott vagy beágyazott PDF szövege szerkeszthető szövegként érkezik, vagy vázlatként, amely a betűkészletei nélküli számítógépen is ugyanúgy néz ki. + Linked pages show the file's own text. A csatolt oldalak a fájl saját szövegét mutatják. When a linked file changes, Automatically reads it again, Ask When Modified asks you first, and Manually leaves it and shows a note in the status bar. Ha egy csatolt fájl megváltozik, az Automatikusan újra beolvassa, a Kérdés módosításkor előbb rákérdez, a Kézzel pedig változatlanul hagyja, és megjegyzést mutat az állapotsoron. On the desktop, the folder New from Template… and Save as Template… start in; leave it blank for VectorCraft Templates in your documents folder. Az asztali változatban a mappa, amelyből az Új sablonból… és a Mentés sablonként… indul; hagyja üresen a dokumentumok mappájában lévő VectorCraft Templates mappához. Edit Original opens a linked file in the system's default app for its type; off, a linked raster image opens in PhotoCraft where it is installed. Az Eredeti szerkesztése a csatolt fájlt a rendszer adott típushoz tartozó alapértelmezett alkalmazásában nyitja meg; kikapcsolva a csatolt raszterkép a PhotoCraftban nyílik meg, ha telepítve van. @@ -4307,6 +4344,7 @@ mark-style Japanese Japán Recent Commands Legutóbbi parancsok No recent commands Nincsenek legutóbbi parancsok Type to search commands, tools, panels and effects Gépeljen parancsok, eszközök, panelek és effektusok kereséséhez + Clear Recent Commands Legutóbbi parancsok listájának törlése Search commands Parancsok keresése Search Commands… Parancsok keresése… Search Fonts Folder Keresés betűtípusmappában @@ -5072,6 +5110,10 @@ mark-style Japanese Japán Rename Preset Előbeállítás átnevezése Save Image Trace Preset Képvektorizálási előbeállítás mentése Delete Image Trace Preset Képvektorizálási előbeállítás törlése + Tracing Presets… Vektorizálási előbeállítások… + Import Image Trace Presets Képvektorizálási előbeállítások importálása + Export Image Trace Presets Képvektorizálási előbeállítások exportálása + Replace the saved presets that have these names? Lecseréli az ilyen nevű mentett előbeállításokat? Tracing Result Vektorizálás eredménye Tracing Result with Outlines Vektorizálás eredménye vázlattal Tracking Betűköz @@ -5523,6 +5565,8 @@ imageTrace Outline Körvonal @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode`: grayscale, rgb, hsb, cmyk vagy websafe kell @msg `view` must be wheel or box `view`: wheel vagy box kell @msg `channel` must be hue, saturation, brightness, red, green or blue `channel`: hue, saturation, brightness, red, green vagy blue kell +@msg `sliders` must be none, oklch or hsl A `sliders` értéke none, oklch vagy hsl lehet +@msg OKLCH needs sRGB as the working RGB space Az OKLCH-hoz sRGB munka-RGB-színtér szükséges @msg `{k}` must be [x, y] `{k}`: [x, y] kell @msg `{name}` has no options ennek nincsenek beállításai: `{name}` @msg `{name}` is a built-in workspace; choose another name beépített munkaterület: `{name}`; válassz másik nevet @@ -6368,6 +6412,10 @@ liquify-list-end {0}, {1} {0} és {1} @msg a symbol can't hold an instance of itself egy szimbólum nem tartalmazhatja a saját példányát @msg select an envelope jelölj ki egy burkolót @msg select an image jelölj ki egy képet +@msg object {_1} is an image changed by Perspective Distort or Free Distort, which this command does not work on ez a parancs nem működik Perspektivikus torzítással vagy Szabad torzítással módosított képen: {_1} +@msg image {_1} cannot be distorted this way: its corners would not make a convex shape a kép nem torzítható így, mert a sarkai nem alkotnának konvex alakzatot: {_1} +@msg image {_1} cannot be distorted this way: its corners would cross the warp's horizon a kép nem torzítható így, mert a sarkai átlépnék a torzítás horizontját: {_1} +@msg image {_1} cannot be distorted this way: its corners would be too close together for a perspective map a kép nem torzítható így, mert a sarkai túl közel lennének egymáshoz a perspektivikus leképezéshez: {_1} @msg `background` must be edges, corners or colors a `background` értéke edges, corners vagy colors lehet @msg `match` must be distance or channels a `match` értéke distance vagy channels lehet @msg `{key}` must be from 0 to 100 a `{key}` értéke 0 és 100 között lehet @@ -6815,7 +6863,10 @@ variable-list-end {0}, {1} {0} és {1} @msg the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate) az objektumnak nincs 3D effektusa (Kihúzás és élletörés, Forgatás tengely körül, Felfújás vagy Elforgatás) @msg `render` must be an object holding only `mode`, set to shaded or wireframe a `render` csak `mode` mezőt tartalmazó objektum lehet, shaded vagy wireframe értékkel @msg its 3D effect builds no solid a 3D effektusa nem hoz létre testet -@msg bevel must be none or one of {_1} a bevel értéke none vagy ezek egyike lehet: {_1} +@msg bevel must be none or one of {_1}, or custom with {BEVEL_PROFILE} a bevel értéke none, ezek egyike: {_1}, vagy custom lehet {BEVEL_PROFILE} megadásával +@msg bevel custom needs {BEVEL_PROFILE}, the bevel's points a bevel custom értékéhez {BEVEL_PROFILE} kell, az élletörés pontjai +@msg {BEVEL_NAME} must be a string {BEVEL_NAME}: karakterlánc kell +@msg {BEVEL_PROFILE} must be 2 to {most} [x, y] points, each share between 0 and 1, from [0, 0] (the cap's edge) to [1, 1] (the side wall) {BEVEL_PROFILE}: legalább 2 és legfeljebb {most} [x, y] pont kell, minden arány 0 és 1 között, [0, 0]-tól (a fedőlap éle) [1, 1]-ig (az oldalfal) @msg {_1} can't build solids from this art: its symbol instances, blends and clipping groups hold too many objects {_1}: ebből a rajzból nem hozható létre test: a szimbólumpéldányai, összemosásai és vágócsoportjai túl sok objektumot tartalmaznak @msg {label} can't build a solid from the instance of symbol "{symbol}": the symbol's art isn't available {label}: nem hozható létre test a(z) „{symbol}” szimbólum példányából: a szimbólum rajza nem érhető el @msg {_1}: the clipping path is too complex to cut the art with {_1}: a vágóútvonal túl összetett a rajz kivágásához @@ -10737,6 +10788,20 @@ breakText Glyphs Glifák @msg A panel is not joined to the rest by a crease. Egy panelt egyetlen bigvonal sem köt a többihez. @msg A fold line is on a non-printing layer. Egy hajtásvonal nem nyomtatható rétegen van. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Panelek: {panels}, zsanérok: {hinges}, hibák: {errors}, figyelmeztetések: {warnings} + Vector Packs Vektorcsomagok + Compass Rose Iránytűrózsa + Botanical Sprig Növényi ágacska + Facet Diamond Csiszolt gyémánt + Tide Crest Hullámhegy + Leaf Vine Leveles inda + Blossom Chain Virágfüzér + Pennant Garland Zászlófüzér + Lantern String Lámpásfüzér + Orbit Lines Pályavonalak + Petal Garland Sziromfüzér + Lattice Braid Rácsfonat + Facet Sweep Fazettás vonás + Artistic Brushes Művészi ecsetek Paint Festék Flat Sweep Lapos húzás Dry Drag Száraz húzás diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 61d4201dce..33ded71456 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -314,7 +314,10 @@ @msg the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate) objek tidak memiliki efek 3D (Ekstrusi & bevel, Revolusi, Gelembungkan, atau Putar) @msg `render` must be an object holding only `mode`, set to shaded or wireframe `render` harus berupa objek yang hanya berisi `mode`, bernilai shaded atau wireframe @msg its 3D effect builds no solid efek 3D-nya tidak membangun bentuk padat -@msg bevel must be none or one of {_1} bevel harus none atau salah satu dari {_1} +@msg bevel must be none or one of {_1}, or custom with {BEVEL_PROFILE} bevel harus none, salah satu dari {_1}, atau custom dengan {BEVEL_PROFILE} +@msg bevel custom needs {BEVEL_PROFILE}, the bevel's points bevel custom memerlukan {BEVEL_PROFILE}, yaitu titik-titik bevel +@msg {BEVEL_NAME} must be a string {BEVEL_NAME} harus berupa string +@msg {BEVEL_PROFILE} must be 2 to {most} [x, y] points, each share between 0 and 1, from [0, 0] (the cap's edge) to [1, 1] (the side wall) {BEVEL_PROFILE} harus berisi 2 sampai {most} titik [x, y], masing-masing bernilai antara 0 dan 1, dari [0, 0] (tepi tutup) hingga [1, 1] (dinding samping) @msg {_1} can't build solids from this art: its symbol instances, blends and clipping groups hold too many objects {_1} tidak dapat membangun bentuk padat dari karya ini: instans simbol, blend, dan grup klipingnya berisi terlalu banyak objek @msg {label} can't build a solid from the instance of symbol "{symbol}": the symbol's art isn't available {label} tidak dapat membangun bentuk padat dari instans simbol "{symbol}": karya simbol tidak tersedia @msg {_1}: the clipping path is too complex to cut the art with {_1}: jalur kliping terlalu rumit untuk memotong karya @@ -1386,6 +1389,8 @@ Contextual Task Bar Bilah tugas kontekstual Pin Bar Position Sematkan posisi bilah Reset Bar Position Atur ulang posisi bilah + Bar Actions Tindakan bilah + Reset Bar Actions Atur ulang tindakan bilah Tools Alat Toolbars Bilah alat Advanced Lanjutan @@ -1405,9 +1410,14 @@ {name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2} Wheel View Tampilan roda Box View Tampilan kotak + Show Out-of-Gamut Colors Tampilkan warna di luar gamut Box Channel Saluran kotak Color box Kotak warna Color Wheel Options Opsi roda warna + Show Document Colors Tampilkan warna dokumen + Document Colors Warna dokumen + Selection Colors Warna pilihan +@plural Used {n} time|Used {n} times Dipakai {n} kali Show Harmony Tampilkan harmoni Harmony Rule Aturan harmoni Harmony color Warna harmoni @@ -2571,6 +2581,10 @@ digits Malayalam Malayalam Rename Preset Ganti nama preset Save Image Trace Preset Simpan preset telusur gambar Delete Image Trace Preset Hapus preset telusur gambar + Tracing Presets… Preset penelusuran… + Import Image Trace Presets Impor preset telusur gambar + Export Image Trace Presets Ekspor preset telusur gambar + Replace the saved presets that have these names? Ganti preset tersimpan yang memiliki nama-nama ini? Method: Metode: Pad Perpanjang Repeats Jumlah ulangan @@ -4639,6 +4653,13 @@ theme Appearance Tampilan Pen Tool Alat pena Quick Pen Tool Alat pena cepat Quick Pen Pena cepat + Quick Pen Toolbar Bilah alat Pena cepat + Continuous Arc Busur bersambung + Sharp Corner Arc Busur sudut tajam + Flip Arc Balik busur + Hide Toolbar Sembunyikan bilah alat + Pin Toolbar Position Sematkan posisi bilah alat + Reset Toolbar Position Atur ulang posisi bilah alat Picas Pica Portuguese Portugis Preserve Appearance and Overprints Pertahankan tampilan dan overprint @@ -4752,6 +4773,11 @@ theme Appearance Tampilan Edit Arrowheads Edit mata panah Edit Arrowheads… Edit mata panah… Reload Arrowheads Muat ulang mata panah + Bevels Bentuk bevel + Edit Bevels Edit bentuk bevel + Edit Bevels… Edit bentuk bevel… + {name} (document) {name} (dokumen) + Reload Bevels Muat ulang bentuk bevel Stroke Options Opsi goresan Width Profiles Profil lebar Apply Graphic Style Terapkan gaya grafis @@ -4971,6 +4997,11 @@ axis Both Keduanya Image Gambar Ink Tinta Lab Lab + OKLCH Sliders Penggeser OKLCH + HSL Sliders Penggeser HSL + Chroma Kroma + The largest chroma sRGB holds at this lightness and hue Kroma terbesar yang dapat dimuat sRGB pada kecerahan dan rona ini + OKLCH needs sRGB as the working RGB space OKLCH memerlukan sRGB sebagai ruang RGB kerja Medium Sedang Name Nama None Nihil @@ -5062,6 +5093,7 @@ font-technology Variable Variabel Recent Commands Perintah terbaru No recent commands Tidak ada perintah terbaru Type to search commands, tools, panels and effects Ketik untuk mencari perintah, alat, panel, dan efek + Clear Recent Commands Kosongkan perintah terbaru Dashed Line Garis putus-putus Panel menu Menu panel Unembed… Lepaskan sematan… @@ -5181,9 +5213,14 @@ font-technology Variable Variabel Edit type set in fonts that aren't available? Edit teks dengan font yang tidak tersedia? Shows each slice's number in a box at its top left on the canvas; off, the slice outlines still show. Menampilkan nomor setiap irisan dalam kotak di sudut kiri atasnya di kanvas; saat nonaktif, garis tepi irisan tetap ditampilkan. The color of user and object slice outlines and their number boxes; auto slices use a dimmer shade of it. Warna garis tepi irisan pengguna dan objek serta kotak nomornya; irisan otomatis memakai nuansa yang lebih redup dari warna ini. + New type takes this language while Document Setup's language is English: USA and [Normal Character Style] sets none; type already in a document keeps its own language. Teks baru mendapat bahasa ini selama bahasa di Pengaturan dokumen adalah Inggris: USA dan [Gaya karakter normal] tidak menetapkan bahasa; teks yang sudah ada di dokumen mempertahankan bahasanya sendiri. + In paragraphs with Hyphenate on, a listed word is hyphenated only at the hyphens typed in it, or never when it has none, whatever its language or case. Di paragraf dengan Pemenggalan kata aktif, kata dalam daftar hanya diberi tanda penggal pada tanda hubung yang diketik di dalamnya, atau tidak pernah jika tidak ada, apa pun bahasa atau huruf besar-kecilnya. + On the desktop, this folder's .wasm plug-ins load at startup and when OK sets a new folder, except in Safe Mode; one that asks for permissions loads only after you grant them. The web version loads none. Di versi desktop, plug-in .wasm di folder ini dimuat saat memulai dan saat OK menetapkan folder baru, kecuali dalam Mode aman; plug-in yang meminta izin baru dimuat setelah Anda memberikannya. Versi web tidak memuat satu pun. + Large gives each filter or command plug-in run at least 250 million instructions, with the same time limit; Normal keeps the plug-in's own budget. Live effects, exporters and importers keep theirs. Besar memberi setiap jalannya plug-in filter atau perintah setidaknya 250 juta instruksi, dengan batas waktu yang sama; Normal mempertahankan anggaran plug-in itu sendiri. Efek langsung, pengekspor, dan pengimpor mempertahankan milik mereka. New type takes this language while Document Setup's language is English: USA; type already in a document keeps its own language. Teks baru mendapat bahasa ini selama bahasa di Pengaturan dokumen adalah Inggris: USA; teks yang sudah ada di dokumen mempertahankan bahasanya sendiri. In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its language or case. Di paragraf dengan Pemenggalan kata aktif, kata dalam daftar hanya dipenggal pada tanda hubung yang diketik di dalamnya, atau tidak di mana pun jika tidak ada, apa pun bahasa atau huruf besar-kecilnya. On the desktop, the .wasm plug-ins in this folder load at startup and when you click OK with a new folder here, except in Safe Mode; the web version does not load them. Di versi desktop, plug-in .wasm di folder ini dimuat saat memulai dan saat Anda mengeklik OK dengan folder baru di sini, kecuali dalam Mode aman; versi web tidak memuatnya. + Normal keeps each plug-in's own limits; with Large, a plug-in filter or command may run at least 250 million instructions besides those for its input. The time limit stays the same. Normal mempertahankan batas setiap plug-in sendiri; dengan Besar, filter atau perintah plug-in dapat menjalankan setidaknya 250 juta instruksi selain instruksi untuk masukannya. Batas waktu tetap sama. How many instructions each run of a plug-in object filter may use; Large allows more than Normal with the same 60-second limit. Heavy filters keep their own budget. Berapa banyak instruksi yang boleh dipakai setiap jalannya filter objek dari plug-in; Besar mengizinkan lebih banyak daripada Normal dengan batas 60 detik yang sama. Filter berat mempertahankan anggarannya sendiri. The first scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. Pilihan disk scratch pertama: Startup, None, atau jalur folder; VectorCraft menyimpannya, tetapi belum menggunakan disk scratch. The second scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. Pilihan disk scratch kedua: Startup, None, atau jalur folder; VectorCraft menyimpannya, tetapi belum menggunakan disk scratch. @@ -5195,13 +5232,15 @@ font-technology Variable Variabel Shows each tool group's name above its tools in the toolbar; off, the groups follow one another with nothing between them. Menampilkan nama setiap grup alat di atas alat-alatnya di bilah alat; jika nonaktif, grup-grup berurutan tanpa apa pun di antaranya. From now on, documents you open or create open as tabs; off, each opens in a floating window. Documents already open stay where they are. Mulai sekarang, dokumen yang Anda buka atau buat terbuka sebagai tab; jika nonaktif, masing-masing terbuka di jendela mengambang. Dokumen yang sudah terbuka tetap di tempatnya. Makes the document tabs taller and their names larger. Membuat tab dokumen lebih tinggi dan namanya lebih besar. - From the next start, the system draws the window's title bar where VectorCraft would otherwise draw its own. Mulai dari peluncuran berikutnya, sistem menggambar bilah judul jendela di tempat VectorCraft biasanya menggambar miliknya sendiri. - From the next start, VectorCraft draws the window's title bar even where the desktop would draw it, unless System Title Bar is on. Mulai dari peluncuran berikutnya, VectorCraft menggambar bilah judul jendela bahkan di tempat desktop akan menggambarnya, kecuali Bilah judul sistem aktif. + From the next start, the system draws the window's title bar where VectorCraft would otherwise draw its own; on Linux and the BSDs, the VECTORCRAFT_TITLEBAR variable takes precedence. Mulai dari peluncuran berikutnya, sistem menggambar bilah judul jendela di tempat VectorCraft biasanya menggambar miliknya sendiri; di Linux dan BSD, variabel VECTORCRAFT_TITLEBAR lebih diutamakan. + From the next start, VectorCraft draws the window's title bar even where the desktop would draw it, unless System Title Bar is on or the VECTORCRAFT_TITLEBAR variable chooses it. Mulai dari peluncuran berikutnya, VectorCraft menggambar bilah judul jendela bahkan di tempat desktop akan menggambarnya, kecuali Bilah judul sistem aktif atau variabel VECTORCRAFT_TITLEBAR memilihnya. Makes the interface larger or smaller; art on the canvas keeps its size at the same zoom. Memperbesar atau memperkecil antarmuka; gambar di kanvas mempertahankan ukurannya pada zoom yang sama. The tool pointers VectorCraft draws grow and shrink with UI Scaling; off, they keep their size. Penunjuk alat yang digambar VectorCraft membesar dan mengecil mengikuti Penskalaan UI; jika nonaktif, ukurannya tetap. The language of the interface; Auto uses the system's language. The dialog switches language as soon as you choose one. Bahasa antarmuka; Otomatis menggunakan bahasa sistem. Dialog berganti bahasa begitu Anda memilih salah satunya. Animated Zoom works only while this is on; off, Animated Zoom is dimmed and zooming does not animate. Zoom animasi hanya berfungsi selama ini aktif; jika nonaktif, Zoom animasi diredupkan dan zoom tidak dianimasikan. The wheel's zoom glides in, and the Zoom tool zooms as you drag sideways or hold it down; off, the Zoom tool zooms to the area you drag across. Zoom dengan roda meluncur halus, dan Alat zoom memperbesar saat Anda menyeret ke samping atau menahannya; jika nonaktif, Alat zoom memperbesar ke area yang Anda seret. + From the next start, the desktop version shows the canvas through this kind of graphics processor; the artwork is drawn on the CPU either way. Automatic prefers the integrated one on Windows and macOS. The web version does not use it. Mulai dari peluncuran berikutnya, versi desktop menampilkan kanvas melalui jenis prosesor grafis ini; karya seni selalu digambar di CPU. Otomatis mengutamakan prosesor terintegrasi di Windows dan macOS. Versi web tidak menggunakannya. + From the next start, the window shows each frame without waiting for the display's refresh where the graphics driver allows, at most 240 frames a second. Mulai dari peluncuran berikutnya, jendela menampilkan setiap bingkai tanpa menunggu penyegaran layar jika driver grafis mengizinkan, paling banyak 240 bingkai per detik. From the next start, the desktop version draws with this kind of graphics processor; Automatic prefers the one that drives the display. The web version does not use it. Mulai dari peluncuran berikutnya, versi desktop menggambar dengan jenis prosesor grafis ini; Otomatis mengutamakan yang menjalankan layar. Versi web tidak menggunakannya. From the next start, the window shows frames without waiting for the display to refresh, at most 240 a second; off, the display paces them. A present mode set at launch overrides it. Mulai dari peluncuran berikutnya, jendela menampilkan bingkai tanpa menunggu layar menyegarkan, paling banyak 240 per detik; jika nonaktif, layar mengatur lajunya. Mode presentasi yang diatur saat peluncuran menggantikannya. The most undo steps each document keeps; lowering it drops the oldest steps when you click OK. Steps can also go sooner when they use too much memory. Jumlah maksimum langkah urungkan yang disimpan setiap dokumen; angka yang lebih kecil menghapus langkah terlama saat Anda mengeklik OK. Langkah juga dapat hilang lebih awal jika memakai terlalu banyak memori. @@ -5220,6 +5259,9 @@ font-technology Variable Variabel Open Recent Files and the Home screen list at most this many recent files; 0 lists none, and VectorCraft still remembers up to 30. Buka berkas terbaru dan layar Home menampilkan paling banyak sejumlah ini berkas terbaru; 0 tidak menampilkan satu pun, dan VectorCraft tetap mengingat hingga 30. When a document opens, a linked EPS image that shows its saved preview keeps it instead of reading the EPS file again; changed files still follow Update Links. Saat dokumen dibuka, gambar EPS tertaut yang menampilkan pratinjau tersimpannya mempertahankannya alih-alih membaca berkas EPS lagi; berkas yang berubah tetap mengikuti Perbarui tautan. In Pixel Preview, images are drawn smoothed; off, their pixels show with hard edges. Outside Pixel Preview, images are always smoothed. Dalam Pratinjau piksel, gambar digambar halus; jika nonaktif, pikselnya tampil dengan tepi tajam. Di luar Pratinjau piksel, gambar selalu dihaluskan. + PDF Text Teks PDF + The text of a PDF you open or embed comes in as editable type, or as outlines that look the same on a computer without its fonts. Teks PDF yang Anda buka atau sematkan masuk sebagai teks yang dapat diedit, atau sebagai outline yang tampak sama di komputer tanpa fontnya. + Linked pages show the file's own text. Halaman tertaut menampilkan teks milik berkas itu sendiri. When a linked file changes, Automatically reads it again, Ask When Modified asks you first, and Manually leaves it and shows a note in the status bar. Saat berkas tertaut berubah, Otomatis membacanya lagi, Tanya saat diubah bertanya dulu kepada Anda, dan Secara manual membiarkannya lalu menampilkan catatan di bilah status. On the desktop, the folder New from Template… and Save as Template… start in; leave it blank for VectorCraft Templates in your documents folder. Di versi desktop, folder tempat Baru dari templat… dan Simpan sebagai templat… dimulai; biarkan kosong untuk VectorCraft Templates di folder dokumen Anda. Edit Original opens a linked file in the system's default app for its type; off, a linked raster image opens in PhotoCraft where it is installed. Edit asli membuka berkas tertaut di aplikasi bawaan sistem untuk jenisnya; jika nonaktif, gambar raster tertaut terbuka di PhotoCraft jika terpasang. @@ -5234,7 +5276,6 @@ font-technology Variable Variabel Output All Blacks as Rich Black draws pure CMYK black as RGB black in RGB and grayscale raster exports and Print as Bitmap; it does not change vector exports, CMYK JPEG, TIFF and PSD, or other printing. Keluarkan semua warna hitam sebagai rich black menggambar hitam CMYK murni sebagai hitam RGB dalam ekspor raster RGB dan skala abu-abu serta Cetak sebagai bitmap; opsi ini tidak mengubah ekspor vektor, JPEG, TIFF, dan PSD CMYK, atau pencetakan lain. On a touch screen, switches to the Touch workspace; turning this off, or losing the touch screen, goes back to the workspace it switched from. Pada layar sentuh, beralih ke ruang kerja sentuh; mematikan opsi ini atau hilangnya layar sentuh mengembalikan ruang kerja sebelum peralihan. A two-finger tap on the canvas undoes, or switches between selection and drawing tools in the Touch workspace, and a three-finger tap redoes; neither works in Presentation Mode. Ketukan dua jari di kanvas mengurungkan, atau di ruang kerja sentuh beralih antara alat seleksi dan alat gambar, dan ketukan tiga jari mengulangi; keduanya tidak berfungsi dalam mode presentasi. - New type takes this language while Document Setup's language is English: USA and [Normal Character Style] sets none; type already in a document keeps its own language. Teks baru mendapat bahasa ini selama bahasa di Pengaturan dokumen adalah Inggris: USA dan [Gaya karakter normal] tidak menetapkan bahasa; teks yang sudah ada di dokumen mempertahankan bahasanya sendiri. In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its case; Korean words take no hyphen, and Indian-language words do not break inside a character cluster. Di paragraf dengan Pemenggalan kata aktif, kata dalam daftar hanya dipenggal pada tanda hubung yang diketik di dalamnya, atau tidak di mana pun jika tidak ada, apa pun huruf besar-kecilnya; kata Korea tidak diberi tanda hubung, dan kata dalam bahasa India tidak dipenggal di dalam satu gugus karakter. Reset all preferences to their defaults? Atur ulang semua preferensi ke defaultnya? The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. Nilai default diterapkan saat Anda mengklik OK di Preferensi. Batal di sana mempertahankan preferensi Anda saat ini. @@ -5257,6 +5298,10 @@ font-technology Variable Variabel Circle Lingkaran Circle Tool Alat lingkaran Circle too large Lingkaran terlalu besar + Show Radii Tampilkan jari-jari + Show Diameter Tampilkan diameter + Anchors at Standard Positions Titik jangkar di posisi standar + Third Point by Dragging Titik ketiga dengan menyeret Clip to Art Pangkas ke karya seni Colorize Warnai Gamma Gamma @@ -6899,6 +6944,8 @@ mark-style Japanese Jepang @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` harus grayscale, rgb, hsb, cmyk atau websafe @msg `view` must be wheel or box `view` harus wheel atau box @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` harus hue, saturation, brightness, red, green atau blue +@msg `sliders` must be none, oklch or hsl `sliders` harus none, oklch, atau hsl +@msg OKLCH needs sRGB as the working RGB space OKLCH memerlukan sRGB sebagai ruang RGB kerja @msg the Color Picker is not open Pemilih Warna tidak terbuka @msg the screen color sampler is already open pengambil warna layar sudah terbuka @msg this system has no screen color sampler sistem ini tidak memiliki pengambil warna layar @@ -8586,6 +8633,20 @@ breakText Glyphs Glif @msg A joint does not close by {gap} pt. Sebuah sambungan tidak menutup sejauh {gap} pt. @msg Two panels pass through each other. Dua panel saling menembus. @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer harus "singleLine", "everyLine", "standardSingleLine", atau "standardEveryLine" + Vector Packs Paket Vektor + Compass Rose Mawar Kompas + Botanical Sprig Ranting Botani + Facet Diamond Berlian Berfaset + Tide Crest Puncak Gelombang + Leaf Vine Sulur Daun + Blossom Chain Rangkaian Bunga + Pennant Garland Untaian Panji + Lantern String Rangkaian Lentera + Orbit Lines Garis Orbit + Petal Garland Rangkaian Kelopak + Lattice Braid Anyaman Kisi + Facet Sweep Sapuan Berfaset + Artistic Brushes Kuas Artistik Paint Cat Flat Sweep Sapuan Datar Dry Drag Tarikan Kering @@ -9014,3 +9075,7 @@ file-filter Applications Aplikasi @msg the slices' descriptor has a reference of an unknown kind ({_1}) deskriptor irisan memiliki referensi dengan jenis yang tidak dikenal ({_1}) @msg the slices' descriptor has a value of an unknown type ({_1}) deskriptor irisan memiliki nilai dengan tipe yang tidak dikenal ({_1}) @msg the layers can't be read ({e}): the file was placed as its merged image lapisan tidak dapat dibaca ({e}): berkas ditempatkan sebagai gambar gabungannya +@msg object {_1} is an image changed by Perspective Distort or Free Distort, which this command does not work on objek {_1} adalah gambar yang diubah dengan Distorsi perspektif atau Distorsi bebas, dan perintah ini tidak dapat digunakan padanya +@msg image {_1} cannot be distorted this way: its corners would not make a convex shape gambar {_1} tidak dapat didistorsi dengan cara ini: sudut-sudutnya tidak akan membentuk bangun cembung +@msg image {_1} cannot be distorted this way: its corners would cross the warp's horizon gambar {_1} tidak dapat didistorsi dengan cara ini: sudut-sudutnya akan melewati cakrawala distorsi +@msg image {_1} cannot be distorted this way: its corners would be too close together for a perspective map gambar {_1} tidak dapat didistorsi dengan cara ini: sudut-sudutnya terlalu berdekatan untuk pemetaan perspektif diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 95850d3d5a..17b5623c1f 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -509,6 +509,11 @@ font-technology Variable Variabili Cusp Cuspide Straight segment Segmento diritto Circle too large Cerchio troppo grande + Show Radii Mostra raggi + Show Diameter Mostra diametro + Anchors at Standard Positions Punti di ancoraggio in posizioni standard + Third Point by Dragging Terzo punto trascinando + Gray Grigio Classic Defaults Valori predefiniti classici Clean Up… Pulisci… Clear Cancella @@ -612,9 +617,14 @@ font-technology Variable Variabili {name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2} Wheel View Vista ruota Box View Vista riquadro + Show Out-of-Gamut Colors Mostra colori fuori gamma Box Channel Canale del riquadro Color box Riquadro colore Color Wheel Options Opzioni ruota dei colori + Show Document Colors Mostra colori del documento + Document Colors Colori del documento + Selection Colors Colori della selezione +@plural Used {n} time|Used {n} times Usato {n} volta|Usato {n} volte Show Harmony Mostra armonia Harmony Rule Regola di armonia Harmony color Colore dell’armonia @@ -658,6 +668,8 @@ font-technology Variable Variabili Contextual Task Bar Barra attività contestuale Pin Bar Position Fissa posizione barra Reset Bar Position Ripristina posizione barra + Bar Actions Azioni barra + Reset Bar Actions Ripristina azioni barra Resize Ridimensiona Contrast Contrasto Control Controllo @@ -1944,6 +1956,10 @@ file-filter Templates Modelli Rename Preset Rinomina preset Save Image Trace Preset Salva preset ricalco immagine Delete Image Trace Preset Elimina preset ricalco immagine + Tracing Presets… Preset di ricalco… + Import Image Trace Presets Importa preset ricalco immagine + Export Image Trace Presets Esporta preset ricalco immagine + Replace the saved presets that have these names? Sostituire i preset salvati con questi nomi? Image Trace Presets Preset ricalco immagine Image: Immagine: Images: Immagini: @@ -2078,6 +2094,11 @@ file-filter Templates Modelli Knife Coltello Knockout Group Gruppo con foratura Lab Lab + OKLCH Sliders Cursori OKLCH + HSL Sliders Cursori HSL + Chroma Croma + The largest chroma sRGB holds at this lightness and hue Il croma più alto che sRGB contiene con questa luminosità e tonalità + OKLCH needs sRGB as the working RGB space OKLCH richiede sRGB come spazio di lavoro RGB Lab Spot Colors: Colori spot Lab: Lab Values Valori Lab Landscape Orizzontale @@ -2840,6 +2861,13 @@ file-filter Templates Modelli Pen Tool Strumento Penna Quick Pen Tool Strumento Penna rapida Quick Pen Penna rapida + Quick Pen Toolbar Barra degli strumenti Penna rapida + Continuous Arc Arco continuo + Sharp Corner Arc Arco ad angolo vivo + Flip Arc Capovolgi arco + Hide Toolbar Nascondi barra degli strumenti + Pin Toolbar Position Fissa posizione barra degli strumenti + Reset Toolbar Position Ripristina posizione barra degli strumenti Pencil Matita Pencil Tool Strumento Matita per slice per sezione @@ -3287,6 +3315,11 @@ digits Malayalam Malayalam Edit Arrowheads Modifica punte di freccia Edit Arrowheads… Modifica punte di freccia… Reload Arrowheads Ricarica punte di freccia + Bevels Smussi + Edit Bevels Modifica smussi + Edit Bevels… Modifica smussi… + {name} (document) {name} (documento) + Reload Bevels Ricarica smussi Rotate View Ruota vista Reset Rotate View Reimposta rotazione vista Rotate View to Selection Ruota vista in base alla selezione @@ -3425,9 +3458,14 @@ digits Malayalam Malayalam Edit type set in fonts that aren't available? Modificare il testo in font non disponibili? Shows each slice's number in a box at its top left on the canvas; off, the slice outlines still show. Mostra sull’area di lavoro il numero di ogni sezione in un riquadro nel suo angolo in alto a sinistra; se è disattivata, i contorni delle sezioni restano visibili. The color of user and object slice outlines and their number boxes; auto slices use a dimmer shade of it. Il colore dei contorni delle sezioni utente e oggetto e dei riquadri con il loro numero; le sezioni automatiche usano una tonalità più tenue di questo colore. + New type takes this language while Document Setup's language is English: USA and [Normal Character Style] sets none; type already in a document keeps its own language. Il nuovo testo prende questa lingua finché la lingua di Imposta documento è Inglese: Stati Uniti e [Stile carattere normale] non ne imposta una; il testo già presente in un documento mantiene la propria lingua. + In paragraphs with Hyphenate on, a listed word is hyphenated only at the hyphens typed in it, or never when it has none, whatever its language or case. Nei paragrafi con Sillaba attivo, una parola dell'elenco riceve il trattino di sillabazione solo ai trattini digitati al suo interno, o mai se non ne ha, qualunque sia la sua lingua o l'uso delle maiuscole. + On the desktop, this folder's .wasm plug-ins load at startup and when OK sets a new folder, except in Safe Mode; one that asks for permissions loads only after you grant them. The web version loads none. Nella versione desktop, i plug-in .wasm di questa cartella vengono caricati all'avvio e quando OK imposta una nuova cartella, tranne in modalità provvisoria; uno che chiede autorizzazioni viene caricato solo dopo che le hai concesse. La versione web non ne carica nessuno. + Large gives each filter or command plug-in run at least 250 million instructions, with the same time limit; Normal keeps the plug-in's own budget. Live effects, exporters and importers keep theirs. Grande dà a ogni esecuzione di un plug-in di filtro o di comando almeno 250 milioni di istruzioni, con lo stesso limite di tempo; Normale mantiene il budget proprio del plug-in. Effetti dinamici, esportatori e importatori mantengono il loro. New type takes this language while Document Setup's language is English: USA; type already in a document keeps its own language. Il nuovo testo prende questa lingua finché la lingua di Imposta documento è Inglese: Stati Uniti; il testo già presente in un documento mantiene la propria lingua. In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its language or case. Nei paragrafi con Sillaba attivo, una parola dell'elenco va a capo solo ai trattini digitati al suo interno, o in nessun punto se non ne ha, qualunque sia la sua lingua o l'uso delle maiuscole. On the desktop, the .wasm plug-ins in this folder load at startup and when you click OK with a new folder here, except in Safe Mode; the web version does not load them. Nella versione desktop, i plug-in .wasm di questa cartella vengono caricati all'avvio e quando fai clic su OK con una nuova cartella qui, tranne in modalità provvisoria; la versione web non li carica. + Normal keeps each plug-in's own limits; with Large, a plug-in filter or command may run at least 250 million instructions besides those for its input. The time limit stays the same. Normale mantiene i limiti propri di ogni plug-in; con Grande, un filtro o un comando di un plug-in può eseguire almeno 250 milioni di istruzioni oltre a quelle per il suo input. Il limite di tempo resta invariato. How many instructions each run of a plug-in object filter may use; Large allows more than Normal with the same 60-second limit. Heavy filters keep their own budget. Quante istruzioni può usare ogni esecuzione di un filtro di oggetti di un plug-in; Grande ne consente più di Normale con lo stesso limite di 60 secondi. I filtri pesanti mantengono il proprio budget. The first scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. La prima scelta del disco di memoria virtuale: Startup, None o il percorso di una cartella; VectorCraft la memorizza, ma non usa ancora dischi di memoria virtuale. The second scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. La seconda scelta del disco di memoria virtuale: Startup, None o il percorso di una cartella; VectorCraft la memorizza, ma non usa ancora dischi di memoria virtuale. @@ -3439,13 +3477,15 @@ digits Malayalam Malayalam Shows each tool group's name above its tools in the toolbar; off, the groups follow one another with nothing between them. Mostra il nome di ogni gruppo di strumenti sopra i suoi strumenti nella barra degli strumenti; se disattivata, i gruppi si susseguono senza nulla tra loro. From now on, documents you open or create open as tabs; off, each opens in a floating window. Documents already open stay where they are. D'ora in poi i documenti che apri o crei si aprono come schede; se disattivata, ognuno si apre in una finestra mobile. I documenti già aperti restano dove sono. Makes the document tabs taller and their names larger. Rende le schede dei documenti più alte e i loro nomi più grandi. - From the next start, the system draws the window's title bar where VectorCraft would otherwise draw its own. Dal prossimo avvio, il sistema disegna la barra del titolo della finestra dove altrimenti VectorCraft disegnerebbe la propria. - From the next start, VectorCraft draws the window's title bar even where the desktop would draw it, unless System Title Bar is on. Dal prossimo avvio, VectorCraft disegna la barra del titolo della finestra anche dove la disegnerebbe il desktop, a meno che Barra del titolo di sistema sia attiva. + From the next start, the system draws the window's title bar where VectorCraft would otherwise draw its own; on Linux and the BSDs, the VECTORCRAFT_TITLEBAR variable takes precedence. Dal prossimo avvio, il sistema disegna la barra del titolo della finestra dove altrimenti VectorCraft disegnerebbe la propria; su Linux e sui BSD ha la precedenza la variabile VECTORCRAFT_TITLEBAR. + From the next start, VectorCraft draws the window's title bar even where the desktop would draw it, unless System Title Bar is on or the VECTORCRAFT_TITLEBAR variable chooses it. Dal prossimo avvio, VectorCraft disegna la barra del titolo della finestra anche dove la disegnerebbe il desktop, a meno che Barra del titolo di sistema sia attiva o la variabile VECTORCRAFT_TITLEBAR la scelga. Makes the interface larger or smaller; art on the canvas keeps its size at the same zoom. Ingrandisce o rimpicciolisce l'interfaccia; la grafica nell'area di disegno mantiene le sue dimensioni allo stesso zoom. The tool pointers VectorCraft draws grow and shrink with UI Scaling; off, they keep their size. I puntatori degli strumenti disegnati da VectorCraft crescono e si riducono con la Scala interfaccia; se disattivata, mantengono le loro dimensioni. The language of the interface; Auto uses the system's language. The dialog switches language as soon as you choose one. La lingua dell'interfaccia; Auto usa la lingua del sistema. La finestra di dialogo cambia lingua appena ne scegli una. Animated Zoom works only while this is on; off, Animated Zoom is dimmed and zooming does not animate. Lo Zoom animato funziona solo mentre questa opzione è attiva; se disattivata, lo Zoom animato è attenuato e lo zoom non è animato. The wheel's zoom glides in, and the Zoom tool zooms as you drag sideways or hold it down; off, the Zoom tool zooms to the area you drag across. Lo zoom con la rotellina scorre in modo fluido, e lo Strumento Zoom ingrandisce mentre trascini di lato o lo tieni premuto; se disattivata, lo Strumento Zoom ingrandisce l'area che trascini. + From the next start, the desktop version shows the canvas through this kind of graphics processor; the artwork is drawn on the CPU either way. Automatic prefers the integrated one on Windows and macOS. The web version does not use it. Dal prossimo avvio, la versione desktop mostra la tela tramite questo tipo di processore grafico; la grafica viene sempre disegnata sulla CPU. Automatico preferisce quello integrato su Windows e macOS. La versione web non lo usa. + From the next start, the window shows each frame without waiting for the display's refresh where the graphics driver allows, at most 240 frames a second. Dal prossimo avvio, la finestra mostra ogni fotogramma senza attendere l’aggiornamento dello schermo dove il driver grafico lo consente, al massimo 240 fotogrammi al secondo. From the next start, the desktop version draws with this kind of graphics processor; Automatic prefers the one that drives the display. The web version does not use it. Dal prossimo avvio, la versione desktop disegna con questo tipo di processore grafico; Automatico preferisce quello che gestisce lo schermo. La versione web non lo usa. From the next start, the window shows frames without waiting for the display to refresh, at most 240 a second; off, the display paces them. A present mode set at launch overrides it. Dal prossimo avvio, la finestra mostra i fotogrammi senza attendere l'aggiornamento dello schermo, al massimo 240 al secondo; disattivato, è lo schermo a scandirli. Una modalità di presentazione impostata all'avvio ha la precedenza. The most undo steps each document keeps; lowering it drops the oldest steps when you click OK. Steps can also go sooner when they use too much memory. Il numero massimo di passaggi di annullamento che ogni documento conserva; un numero più basso rimuove i passaggi più vecchi quando fai clic su OK. I passaggi possono sparire anche prima se occupano troppa memoria. @@ -3464,6 +3504,9 @@ digits Malayalam Malayalam Open Recent Files and the Home screen list at most this many recent files; 0 lists none, and VectorCraft still remembers up to 30. Apri file recenti e la schermata Home elencano al massimo questo numero di file recenti; 0 non ne elenca nessuno, e VectorCraft ne ricorda comunque fino a 30. When a document opens, a linked EPS image that shows its saved preview keeps it instead of reading the EPS file again; changed files still follow Update Links. All’apertura di un documento, un’immagine EPS collegata che mostra la sua anteprima salvata la mantiene invece di rileggere il file EPS; i file modificati seguono comunque Aggiorna collegamenti. In Pixel Preview, images are drawn smoothed; off, their pixels show with hard edges. Outside Pixel Preview, images are always smoothed. In Anteprima pixel, le immagini sono disegnate smussate; se disattivata, i loro pixel hanno bordi netti. Fuori da Anteprima pixel, le immagini sono sempre smussate. + PDF Text Testo PDF + The text of a PDF you open or embed comes in as editable type, or as outlines that look the same on a computer without its fonts. Il testo di un PDF che apri o incorpori arriva come testo modificabile o come contorni che appaiono uguali su un computer senza i suoi font. + Linked pages show the file's own text. Le pagine collegate mostrano il testo del file stesso. When a linked file changes, Automatically reads it again, Ask When Modified asks you first, and Manually leaves it and shows a note in the status bar. Quando un file collegato cambia, Automaticamente lo rilegge, Chiedi se modificato te lo chiede prima, e Manualmente lo lascia com’è e mostra un avviso nella barra di stato. On the desktop, the folder New from Template… and Save as Template… start in; leave it blank for VectorCraft Templates in your documents folder. Nella versione desktop, la cartella da cui partono Nuovo da modello… e Salva come modello…; lasciala vuota per VectorCraft Templates nella tua cartella dei documenti. Edit Original opens a linked file in the system's default app for its type; off, a linked raster image opens in PhotoCraft where it is installed. Modifica originale apre un file collegato nell’app predefinita del sistema per il suo tipo; se disattivata, un’immagine raster collegata si apre in PhotoCraft, se installato. @@ -3478,7 +3521,6 @@ digits Malayalam Malayalam Output All Blacks as Rich Black draws pure CMYK black as RGB black in RGB and grayscale raster exports and Print as Bitmap; it does not change vector exports, CMYK JPEG, TIFF and PSD, or other printing. Riproduci tutti i neri come nero ricco disegna il nero CMYK puro come nero RGB nelle esportazioni raster RGB e in scala di grigi e con Stampa come bitmap; non cambia le esportazioni vettoriali, i JPEG, TIFF e PSD CMYK né le altre stampe. On a touch screen, switches to the Touch workspace; turning this off, or losing the touch screen, goes back to the workspace it switched from. Su uno schermo touch passa all'area di lavoro touch; disattivando l'opzione o se lo schermo touch non è più rilevato, torna all'area di lavoro precedente. A two-finger tap on the canvas undoes, or switches between selection and drawing tools in the Touch workspace, and a three-finger tap redoes; neither works in Presentation Mode. Un tocco con due dita sull'area di lavoro annulla o, nell'area di lavoro touch, alterna tra strumenti di selezione e di disegno, e un tocco con tre dita ripete; nessuno dei due funziona in modalità presentazione. - New type takes this language while Document Setup's language is English: USA and [Normal Character Style] sets none; type already in a document keeps its own language. Il nuovo testo prende questa lingua finché la lingua di Imposta documento è Inglese: Stati Uniti e [Stile carattere normale] non ne imposta una; il testo già presente in un documento mantiene la propria lingua. In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its case; Korean words take no hyphen, and Indian-language words do not break inside a character cluster. Nei paragrafi con Sillaba attivo, una parola dell'elenco va a capo solo ai trattini digitati al suo interno, o in nessun punto se non ne ha, qualunque sia l'uso delle maiuscole; le parole coreane non prendono trattino e le parole in lingue indiane non vanno a capo all'interno di un gruppo di caratteri. Reset all preferences to their defaults? Ripristinare tutte le preferenze ai valori predefiniti? The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. I valori predefiniti vengono applicati quando fai clic su OK in Preferenze. Annulla lì mantiene le preferenze attuali. @@ -3725,6 +3767,7 @@ digits Malayalam Malayalam Recent Commands Comandi recenti No recent commands Nessun comando recente Type to search commands, tools, panels and effects Digita per cercare comandi, strumenti, pannelli ed effetti + Clear Recent Commands Cancella comandi recenti Search commands Cerca comandi Search Commands… Cerca comandi… Secondary Secondario @@ -5210,6 +5253,8 @@ liquify-list-end {0}, {1} {0} e {1} @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` deve essere grayscale, rgb, hsb, cmyk o websafe @msg `view` must be wheel or box `view` deve essere wheel o box @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` deve essere hue, saturation, brightness, red, green o blue +@msg `sliders` must be none, oklch or hsl `sliders` deve essere none, oklch o hsl +@msg OKLCH needs sRGB as the working RGB space OKLCH richiede sRGB come spazio di lavoro RGB @msg `{k}` must be [x, y] `{k}` deve essere [x, y] @msg `{name}` has no options `{name}` non ha opzioni @msg `{name}` is a built-in workspace; choose another name `{name}` è un'area di lavoro integrata; scegli un altro nome @@ -5620,6 +5665,10 @@ liquify-list-end {0}, {1} {0} e {1} @msg this trace would make more than {max} anchor points, more than the document can show smoothly: raise Noise, lower Paths or Colors, or pick a lower-fidelity preset questo ricalco creerebbe più di {max} punti di ancoraggio, più di quanti il documento possa mostrare in modo fluido: aumenta Disturbo, riduci Tracciati o Colori, oppure scegli un preset a fedeltà inferiore @msg select an envelope seleziona un involucro @msg select an image seleziona un'immagine +@msg object {_1} is an image changed by Perspective Distort or Free Distort, which this command does not work on l'oggetto {_1} è un'immagine modificata con Distorsione prospettica o Distorsione libera, su cui questo comando non funziona +@msg image {_1} cannot be distorted this way: its corners would not make a convex shape l'immagine {_1} non può essere distorta così: i suoi angoli non formerebbero una forma convessa +@msg image {_1} cannot be distorted this way: its corners would cross the warp's horizon l'immagine {_1} non può essere distorta così: i suoi angoli supererebbero l'orizzonte della distorsione +@msg image {_1} cannot be distorted this way: its corners would be too close together for a perspective map l'immagine {_1} non può essere distorta così: i suoi angoli sarebbero troppo vicini per una proiezione prospettica @msg `background` must be edges, corners or colors `background` deve essere edges, corners o colors @msg `match` must be distance or channels `match` deve essere distance o channels @msg `{key}` must be from 0 to 100 `{key}` deve essere compreso tra 0 e 100 @@ -6443,7 +6492,10 @@ lighting Light Luce @msg the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate) l'oggetto non ha alcun effetto 3D (Estrusione e smusso, Rivoluzione, Gonfia o Ruota) @msg `render` must be an object holding only `mode`, set to shaded or wireframe `render` deve essere un oggetto che contiene solo `mode`, con valore shaded o wireframe @msg its 3D effect builds no solid il suo effetto 3D non costruisce alcun solido -@msg bevel must be none or one of {_1} bevel deve essere none o uno dei seguenti: {_1} +@msg bevel must be none or one of {_1}, or custom with {BEVEL_PROFILE} bevel deve essere none, uno dei seguenti: {_1}, oppure custom con {BEVEL_PROFILE} +@msg bevel custom needs {BEVEL_PROFILE}, the bevel's points bevel custom richiede {BEVEL_PROFILE}, i punti dello smusso +@msg {BEVEL_NAME} must be a string {BEVEL_NAME} deve essere una stringa +@msg {BEVEL_PROFILE} must be 2 to {most} [x, y] points, each share between 0 and 1, from [0, 0] (the cap's edge) to [1, 1] (the side wall) {BEVEL_PROFILE} deve contenere da 2 a {most} punti [x, y], ogni proporzione tra 0 e 1, da [0, 0] (il bordo della faccia) a [1, 1] (la parete laterale) @msg {_1} can't build solids from this art: its symbol instances, blends and clipping groups hold too many objects {_1} non può costruire solidi da questo disegno: le sue istanze di simbolo, fusioni e gruppi di ritaglio contengono troppi oggetti @msg {label} can't build a solid from the instance of symbol "{symbol}": the symbol's art isn't available {label} non può costruire un solido dall'istanza del simbolo «{symbol}»: il disegno del simbolo non è disponibile @msg {_1}: the clipping path is too complex to cut the art with {_1}: il tracciato di ritaglio è troppo complesso per ritagliare il disegno @@ -10423,6 +10475,20 @@ breakText Glyphs Glifi @msg A panel is not joined to the rest by a crease. Un pannello non è unito al resto da alcuna linea di cordonatura. @msg A fold line is on a non-printing layer. Una linea di piega si trova su un livello non stampabile. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Pannelli: {panels}, cerniere: {hinges}, errori: {errors}, avvisi: {warnings} + Vector Packs Pacchetti vettoriali + Compass Rose Rosa dei venti + Botanical Sprig Rametto botanico + Facet Diamond Diamante sfaccettato + Tide Crest Cresta dell'onda + Leaf Vine Tralcio di foglie + Blossom Chain Catena di fiori + Pennant Garland Ghirlanda di bandierine + Lantern String Fila di lanterne + Orbit Lines Linee orbitali + Petal Garland Ghirlanda di petali + Lattice Braid Intreccio a reticolo + Facet Sweep Tratto sfaccettato + Artistic Brushes Pennelli artistici Paint Pittura Flat Sweep Passata piatta Dry Drag Trascinamento secco diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index be63f4a0c9..31e6213b03 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -399,6 +399,10 @@ digits Malayalam マラヤーラム数字 Rename Preset プリセット名を変更 Save Image Trace Preset 画像トレースプリセットを保存 Delete Image Trace Preset 画像トレースプリセットを削除 + Tracing Presets… トレースプリセット… + Import Image Trace Presets 画像トレースプリセットを読み込み + Export Image Trace Presets 画像トレースプリセットを書き出し + Replace the saved presets that have these names? これらの名前の保存済みプリセットを置き換えますか? Text Wrap テキストの回り込み Text Wrap Options… テキストの回り込みオプション… Clipping Mask クリッピングマスク @@ -846,6 +850,8 @@ digits Malayalam マラヤーラム数字 Contextual Task Bar コンテキストタスクバー Pin Bar Position バーの位置を固定 Reset Bar Position バーの位置をリセット + Bar Actions バーのアクション + Reset Bar Actions バーのアクションをリセット Resize サイズを変更 Tools ツール Toolbars ツールバー @@ -866,9 +872,14 @@ digits Malayalam マラヤーラム数字 {name1} {value1}, {name2} {value2} {name1} {value1}、{name2} {value2} Wheel View ホイール表示 Box View ボックス表示 + Show Out-of-Gamut Colors 色域外のカラーを表示 Box Channel ボックスのチャンネル Color box カラーボックス Color Wheel Options カラーホイールオプション + Show Document Colors ドキュメントのカラーを表示 + Document Colors ドキュメントのカラー + Selection Colors 選択範囲のカラー +@plural Used {n} time|Used {n} times {n} 回使用 Show Harmony ハーモニーを表示 Harmony Rule ハーモニールール Harmony color ハーモニーカラー @@ -1412,6 +1423,11 @@ antiAlias Sharp シャープ Cusp 尖点 Straight segment 直線セグメント Circle too large 円が大きすぎます + Show Radii 半径を表示 + Show Diameter 直径を表示 + Anchors at Standard Positions アンカーポイントを標準位置に配置 + Third Point by Dragging 3 点目をドラッグで指定 + Gray グレー Clear All Tabs すべてのタブを消去 Above Text テキストの上 Position Panel Above Text テキストの上にパネルを配置 @@ -2935,6 +2951,13 @@ antiAlias Sharp シャープ Pen Tool ペンツール Quick Pen Tool クイックペンツール Quick Pen クイックペン + Quick Pen Toolbar クイックペンツールバー + Continuous Arc 連続円弧 + Sharp Corner Arc 鋭角円弧 + Flip Arc 円弧を反転 + Hide Toolbar ツールバーを隠す + Pin Toolbar Position ツールバーの位置を固定 + Reset Toolbar Position ツールバーの位置をリセット Pencil 鉛筆 Pencil Tool 鉛筆ツール Percent: パーセント: @@ -3267,6 +3290,11 @@ mark-style Japanese 日本式 Edit Arrowheads 矢印を編集 Edit Arrowheads… 矢印を編集… Reload Arrowheads 矢印を再読み込み + Bevels ベベル一覧 + Edit Bevels ベベルを編集 + Edit Bevels… ベベルを編集… + {name} (document) {name} (ドキュメント) + Reload Bevels ベベルを再読み込み Reset the rows to the artwork's colors 行をアートワークのカラーにリセット Color Theme Picker カラーテーマピッカー Undo Changes 変更を取り消し @@ -3398,9 +3426,13 @@ mark-style Japanese 日本式 Edit type set in fonts that aren't available? 使用できないフォントのテキストを編集しますか? Shows each slice's number in a box at its top left on the canvas; off, the slice outlines still show. カンバス上で、各スライスの番号をスライスの左上のボックスに表示します。オフでもスライスの輪郭は表示されます。 The color of user and object slice outlines and their number boxes; auto slices use a dimmer shade of it. ユーザースライスとオブジェクトスライスの輪郭、およびその番号のボックスの色です。自動スライスにはこの色の淡い色合いが使われます。 + In paragraphs with Hyphenate on, a listed word is hyphenated only at the hyphens typed in it, or never when it has none, whatever its language or case. ハイフネーションがオンの段落では、リストの単語は入力したハイフンの位置でのみハイフネーションされ、ハイフンがなければハイフネーションされません。言語や大文字小文字は問いません。 + On the desktop, this folder's .wasm plug-ins load at startup and when OK sets a new folder, except in Safe Mode; one that asks for permissions loads only after you grant them. The web version loads none. デスクトップ版では、このフォルダーの .wasm プラグインが起動時と、OK で新しいフォルダーを設定したときに読み込まれます (セーフモードを除く)。権限を求めるプラグインは、権限を許可した後にのみ読み込まれます。Web 版では読み込まれません。 + Large gives each filter or command plug-in run at least 250 million instructions, with the same time limit; Normal keeps the plug-in's own budget. Live effects, exporters and importers keep theirs. 大では、フィルターまたはコマンドのプラグインの各実行に、同じ制限時間で 2 億 5,000 万以上の命令を与えます。通常では、プラグイン独自の予算を使います。ライブ効果、書き出し、読み込みはそれぞれの予算を使います。 New type takes this language while Document Setup's language is English: USA; type already in a document keeps its own language. ドキュメント設定の言語が英語 (米国) の間は、新しいテキストにこの言語が設定されます。ドキュメント内の既存のテキストは自身の言語を保ちます。 In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its language or case. ハイフネーションがオンの段落では、リストの単語は入力したハイフンの位置でのみ分割され、ハイフンがなければ分割されません。言語や大文字小文字は問いません。 On the desktop, the .wasm plug-ins in this folder load at startup and when you click OK with a new folder here, except in Safe Mode; the web version does not load them. デスクトップ版では、このフォルダーの .wasm プラグインが起動時と、ここに新しいフォルダーを指定して OK をクリックしたときに読み込まれます (セーフモードを除く)。Web 版では読み込まれません。 + Normal keeps each plug-in's own limits; with Large, a plug-in filter or command may run at least 250 million instructions besides those for its input. The time limit stays the same. 通常では各プラグイン自身の制限が使われます。大では、プラグインのフィルターやコマンドは入力のための命令に加えて少なくとも 2 億 5000 万命令を実行できます。時間の制限は変わりません。 How many instructions each run of a plug-in object filter may use; Large allows more than Normal with the same 60-second limit. Heavy filters keep their own budget. プラグインのオブジェクトフィルターを 1 回実行するときに使える命令の数です。大では通常より多く使え、60 秒の制限は変わりません。重いフィルターは独自の予算を保ちます。 The first scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. 1 つ目の仮想記憶ディスクの選択です。Startup、None またはフォルダーのパスを指定します。VectorCraft は保存しますが、仮想記憶ディスクはまだ使用しません。 The second scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. 2 つ目の仮想記憶ディスクの選択です。Startup、None またはフォルダーのパスを指定します。VectorCraft は保存しますが、仮想記憶ディスクはまだ使用しません。 @@ -3412,13 +3444,15 @@ mark-style Japanese 日本式 Shows each tool group's name above its tools in the toolbar; off, the groups follow one another with nothing between them. ツールバーで、各ツールグループの名前をそのツールの上に表示します。オフの場合、グループは間に何も入らずに続けて並びます。 From now on, documents you open or create open as tabs; off, each opens in a floating window. Documents already open stay where they are. 今後開くまたは作成するドキュメントをタブで開きます。オフの場合は、それぞれフローティングウィンドウで開きます。すでに開いているドキュメントはそのままです。 Makes the document tabs taller and their names larger. ドキュメントのタブを高くし、名前を大きく表示します。 - From the next start, the system draws the window's title bar where VectorCraft would otherwise draw its own. 次回の起動から、VectorCraft が独自のタイトルバーを描画する場所で、代わりにシステムがウィンドウのタイトルバーを描画します。 - From the next start, VectorCraft draws the window's title bar even where the desktop would draw it, unless System Title Bar is on. 次回の起動から、デスクトップがタイトルバーを描画する場所でも VectorCraft がウィンドウのタイトルバーを描画します。ただし、システムのタイトルバーがオンの場合を除きます。 + From the next start, the system draws the window's title bar where VectorCraft would otherwise draw its own; on Linux and the BSDs, the VECTORCRAFT_TITLEBAR variable takes precedence. 次回の起動から、VectorCraft が独自のタイトルバーを描画する場所で、代わりにシステムがウィンドウのタイトルバーを描画します。Linux と BSD では VECTORCRAFT_TITLEBAR 変数が優先されます。 + From the next start, VectorCraft draws the window's title bar even where the desktop would draw it, unless System Title Bar is on or the VECTORCRAFT_TITLEBAR variable chooses it. 次回の起動から、デスクトップがタイトルバーを描画する場所でも VectorCraft がウィンドウのタイトルバーを描画します。ただし、システムのタイトルバーがオンの場合と、VECTORCRAFT_TITLEBAR 変数が選択する場合を除きます。 Makes the interface larger or smaller; art on the canvas keeps its size at the same zoom. インターフェイスを拡大または縮小します。同じズームでは、カンバス上のアートワークのサイズは変わりません。 The tool pointers VectorCraft draws grow and shrink with UI Scaling; off, they keep their size. VectorCraft が描画するツールのポインターを UI のスケーリングに合わせて拡大・縮小します。オフの場合はサイズを保ちます。 The language of the interface; Auto uses the system's language. The dialog switches language as soon as you choose one. インターフェイスの言語です。自動ではシステムの言語を使います。言語を選ぶとすぐにダイアログの表示が切り替わります。 Animated Zoom works only while this is on; off, Animated Zoom is dimmed and zooming does not animate. アニメーションズームは、これがオンのときだけ働きます。オフの場合、アニメーションズームは淡色表示になり、ズームはアニメーションしません。 The wheel's zoom glides in, and the Zoom tool zooms as you drag sideways or hold it down; off, the Zoom tool zooms to the area you drag across. ホイールによるズームはなめらかに動き、ズームツールは横にドラッグするか押したままにするとズームします。オフの場合、ズームツールはドラッグした範囲にズームします。 + From the next start, the desktop version shows the canvas through this kind of graphics processor; the artwork is drawn on the CPU either way. Automatic prefers the integrated one on Windows and macOS. The web version does not use it. 次回の起動から、デスクトップ版はこの種類のグラフィックプロセッサーを通してカンバスを表示します。アートワーク自体は常に CPU で描画されます。自動では Windows と macOS で内蔵のものが優先されます。Web 版では使われません。 + From the next start, the window shows each frame without waiting for the display's refresh where the graphics driver allows, at most 240 frames a second. 次回の起動から、グラフィックドライバーが許す場合、ウィンドウはディスプレイのリフレッシュを待たずに各フレームを表示します。最大で毎秒 240 フレームです。 From the next start, the desktop version draws with this kind of graphics processor; Automatic prefers the one that drives the display. The web version does not use it. 次回の起動から、デスクトップ版はこの種類のグラフィックプロセッサーで描画します。自動ではディスプレイを駆動しているものが優先されます。Web 版では使われません。 From the next start, the window shows frames without waiting for the display to refresh, at most 240 a second; off, the display paces them. A present mode set at launch overrides it. 次回の起動から、ウィンドウはディスプレイの更新を待たずにフレームを表示します。上限は毎秒 240 フレームです。オフにすると、ディスプレイがフレームの間隔を決めます。起動時に指定した表示モードが優先されます。 The most undo steps each document keeps; lowering it drops the oldest steps when you click OK. Steps can also go sooner when they use too much memory. 各ドキュメントが保持する取り消しステップの最大数です。値を下げると、OK をクリックしたときに古いステップから削除されます。メモリを使いすぎる場合は、さらに早く削除されることがあります。 @@ -3437,6 +3471,9 @@ mark-style Japanese 日本式 Open Recent Files and the Home screen list at most this many recent files; 0 lists none, and VectorCraft still remembers up to 30. 最近使用したファイルを開くとホーム画面に表示する最近のファイルの最大数です。0 では表示しませんが、VectorCraft は最大 30 個まで覚えています。 When a document opens, a linked EPS image that shows its saved preview keeps it instead of reading the EPS file again; changed files still follow Update Links. ドキュメントを開くとき、保存済みのプレビューを表示しているリンクされた EPS 画像は、EPS ファイルを読み直さずにそのプレビューを保ちます。変更されたファイルには引き続きリンクを更新の設定が適用されます。 In Pixel Preview, images are drawn smoothed; off, their pixels show with hard edges. Outside Pixel Preview, images are always smoothed. ピクセルプレビューで画像を滑らかに描画します。オフの場合、ピクセルの端がはっきり表示されます。ピクセルプレビュー以外では画像は常に滑らかです。 + PDF Text PDF のテキスト + The text of a PDF you open or embed comes in as editable type, or as outlines that look the same on a computer without its fonts. 開く PDF や埋め込む PDF のテキストを、編集可能なテキストとして、またはフォントのないコンピューターでも同じに見えるアウトラインとして読み込みます。 + Linked pages show the file's own text. リンクしたページにはファイル自体のテキストが表示されます。 When a linked file changes, Automatically reads it again, Ask When Modified asks you first, and Manually leaves it and shows a note in the status bar. リンクされたファイルが変更されたとき、自動では読み直し、変更時に確認では先に確認し、手動ではそのままにしてステータスバーにメモを表示します。 On the desktop, the folder New from Template… and Save as Template… start in; leave it blank for VectorCraft Templates in your documents folder. デスクトップ版で、テンプレートから新規…とテンプレートとして保存…が最初に開くフォルダーです。空欄にすると書類フォルダー内の VectorCraft Templates を使います。 Edit Original opens a linked file in the system's default app for its type; off, a linked raster image opens in PhotoCraft where it is installed. オリジナルを編集で、リンクされたファイルを種類に応じたシステムの既定のアプリで開きます。オフの場合、リンクされたラスター画像はインストールされていれば PhotoCraft で開きます。 @@ -3597,6 +3634,7 @@ mark-style Japanese 日本式 Recent Commands 最近使ったコマンド No recent commands 最近使ったコマンドはありません Type to search commands, tools, panels and effects 入力してコマンド、ツール、パネル、効果を検索 + Clear Recent Commands 最近使ったコマンドを消去 Search commands コマンドを検索 Secondary セカンダリ Select All Art on Layer レイヤー上のすべてのアートを選択 @@ -4416,6 +4454,11 @@ file-filter Templates テンプレート Keep the pasted color as a new swatch with a numbered name. ペーストしたカラーを、番号付きの名前で新規スウォッチとして残します。 Keep: 保持: Lab Lab + OKLCH Sliders OKLCH スライダー + HSL Sliders HSL スライダー + Chroma クロマ + The largest chroma sRGB holds at this lightness and hue この明度と色相で sRGB に収まる最大のクロマ + OKLCH needs sRGB as the working RGB space OKLCH には作業用 RGB スペースとして sRGB が必要です Lab Values Lab 値 Large List View 大きいリスト表示 Large Thumbnail View 大きいサムネール表示 @@ -5640,6 +5683,8 @@ variable-list-end {0}, {1} {0}、{1} @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` には grayscale、rgb、hsb、cmyk、websafe のいずれかを指定してください @msg `view` must be wheel or box `view` には wheel、box のいずれかを指定してください @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` には hue、saturation、brightness、red、green、blue のいずれかを指定してください +@msg `sliders` must be none, oklch or hsl `sliders` には none、oklch、hsl のいずれかを指定してください +@msg OKLCH needs sRGB as the working RGB space OKLCH には作業用 RGB スペースとして sRGB が必要です @msg `{key}` must be true or false `{key}` には true または false を指定してください @msg `top` and `below` can't both be true `top` と `below` を同時に true にすることはできません @msg `select` must be true or false `select` には true または false を指定してください @@ -5674,6 +5719,10 @@ variable-list-end {0}, {1} {0}、{1} @msg no such view 指定された表示が見つかりません @msg printing isn't available here この環境ではプリントできません @msg select an image 画像を選択してください +@msg object {_1} is an image changed by Perspective Distort or Free Distort, which this command does not work on オブジェクト {_1} は遠近変形または自由変形で変更された画像のため、このコマンドは使用できません +@msg image {_1} cannot be distorted this way: its corners would not make a convex shape 角が凸形状にならないため、画像 {_1} はこのように変形できません +@msg image {_1} cannot be distorted this way: its corners would cross the warp's horizon 角が変形の地平線を越えるため、画像 {_1} はこのように変形できません +@msg image {_1} cannot be distorted this way: its corners would be too close together for a perspective map 角が近すぎて遠近法で配置できないため、画像 {_1} はこのように変形できません @msg `background` must be edges, corners or colors `background` は edges、corners または colors にしてください @msg `match` must be distance or channels `match` は distance または channels にしてください @msg `{key}` must be from 0 to 100 `{key}` は 0 から 100 までの値にしてください @@ -6492,7 +6541,10 @@ lighting Light ライト @msg the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate) オブジェクトに 3D 効果 (押し出しとベベル、回転体、膨張、回転) がありません @msg `render` must be an object holding only `mode`, set to shaded or wireframe `render` は `mode` だけを持ち、その値が shaded または wireframe のオブジェクトにしてください @msg its 3D effect builds no solid 3D 効果からソリッドが作成されません -@msg bevel must be none or one of {_1} bevel には none または {_1} のいずれかを指定してください +@msg bevel must be none or one of {_1}, or custom with {BEVEL_PROFILE} bevel には none、{_1} のいずれか、または {BEVEL_PROFILE} を付けた custom を指定してください +@msg bevel custom needs {BEVEL_PROFILE}, the bevel's points bevel custom にはベベルのポイントを表す {BEVEL_PROFILE} が必要です +@msg {BEVEL_NAME} must be a string {BEVEL_NAME} は文字列にしてください +@msg {BEVEL_PROFILE} must be 2 to {most} [x, y] points, each share between 0 and 1, from [0, 0] (the cap's edge) to [1, 1] (the side wall) {BEVEL_PROFILE} には 2 個から {most} 個の [x, y] ポイントを、各値を 0 から 1 までの割合として、[0, 0] (端面の縁) から [1, 1] (側面の壁) まで指定してください @msg {_1} can't build solids from this art: its symbol instances, blends and clipping groups hold too many objects {_1} はこのアートからソリッドを作成できません。シンボルインスタンス、ブレンド、クリッピンググループに含まれるオブジェクトが多すぎます @msg {label} can't build a solid from the instance of symbol "{symbol}": the symbol's art isn't available {label} はシンボル「{symbol}」のインスタンスからソリッドを作成できません。シンボルのアートを使用できません @msg {_1}: the clipping path is too complex to cut the art with {_1}: クリッピングパスが複雑すぎるため、アートを切り抜けません @@ -10486,6 +10538,20 @@ breakText Glyphs 字形 @msg A panel is not joined to the rest by a crease. パネルがどの筋入れ線でも他とつながっていません。 @msg A fold line is on a non-printing layer. 折り線が印刷しないレイヤーにあります。 @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} パネル: {panels}、ヒンジ: {hinges}、エラー: {errors}、警告: {warnings} + Vector Packs ベクターパック + Compass Rose 羅針盤のバラ + Botanical Sprig 植物の小枝 + Facet Diamond 多面体ダイヤ + Tide Crest 波の頂 + Leaf Vine 葉のつる + Blossom Chain 花の連なり + Pennant Garland 三角旗のガーランド + Lantern String ランタンの連なり + Orbit Lines 軌道線 + Petal Garland 花びらのガーランド + Lattice Braid 格子編み + Facet Sweep 多面体のストローク + Artistic Brushes アートブラシ Paint ペイント Flat Sweep 平筆の一掃き Dry Drag ドライドラッグ diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index b12f3b1b17..fe14db5457 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -2920,6 +2920,8 @@ Contextual Task Bar კონტექსტური ამოცანების ზოლი Pin Bar Position ზოლის პოზიციის ჩამაგრება Reset Bar Position ზოლის პოზიციის ჩამოყრა + Bar Actions ზოლის მოქმედებები + Reset Bar Actions ზოლის მოქმედებების ჩამოყრა Tools ხელსაწყოები Toolbars ხელსაწყოთა ზოლები Advanced დამატებითი @@ -2939,9 +2941,14 @@ {name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2} Wheel View წრის ხედი Box View კვადრატის ხედი + Show Out-of-Gamut Colors ფერთა გამის გარეთ მყოფი ფერების ჩვენება Box Channel კვადრატის არხი Color box ფერის კვადრატი Color Wheel Options ფერთა წრის პარამეტრები + Show Document Colors დოკუმენტის ფერების ჩვენება + Document Colors დოკუმენტის ფერები + Selection Colors მონიშნულის ფერები +@plural Used {n} time|Used {n} times გამოყენებულია {n}-ჯერ Show Harmony ჰარმონიის ჩვენება Harmony Rule ჰარმონიის წესი Harmony color ჰარმონიის ფერი @@ -4074,6 +4081,10 @@ digits Malayalam მალაიალამური Rename Preset პრესეტის სახელის შეცვლა Save Image Trace Preset გამოსახულების ვექტორიზაციის პრესეტის შენახვა Delete Image Trace Preset გამოსახულების ვექტორიზაციის პრესეტის წაშლა + Tracing Presets… ვექტორიზაციის პრესეტები… + Import Image Trace Presets გამოსახულების ვექტორიზაციის პრესეტების იმპორტირება + Export Image Trace Presets გამოსახულების ვექტორიზაციის პრესეტების ექსპორტირება + Replace the saved presets that have these names? ჩავანაცვლოთ ამ სახელების მქონე შენახული პრესეტები? Cancel Image Trace გამოსახულების ვექტორიზაციის გაუქმება Method: მეთოდი: Pad გაგრძელება @@ -6053,6 +6064,13 @@ theme Appearance იერსახე Pen Tool კალმის ხელსაწყო Quick Pen Tool სწრაფი კალმის ხელსაწყო Quick Pen სწრაფი კალამი + Quick Pen Toolbar სწრაფი კალმის ხელსაწყოთა ზოლი + Continuous Arc უწყვეტი რკალი + Sharp Corner Arc მახვილკუთხიანი რკალი + Flip Arc რკალის არეკვლა + Hide Toolbar ხელსაწყოთა ზოლის დამალვა + Pin Toolbar Position ხელსაწყოთა ზოლის პოზიციის ჩამაგრება + Reset Toolbar Position ხელსაწყოთა ზოლის პოზიციის ჩამოყრა Picas პიკები Portuguese პორტუგალიური Preserve Appearance and Overprints იერსახისა და ზედდაბეჭდვების შენარჩუნება @@ -6167,6 +6185,11 @@ theme Appearance იერსახე Edit Arrowheads ისრის წვერების რედაქტირება Edit Arrowheads… ისრის წვერების რედაქტირება… Reload Arrowheads ისრის წვერების ხელახლა ჩატვირთვა + Bevels წაკვეთები + Edit Bevels წაკვეთების რედაქტირება + Edit Bevels… წაკვეთების რედაქტირება… + {name} (document) {name} (დოკუმენტი) + Reload Bevels წაკვეთების ხელახლა ჩატვირთვა Stroke Options კონტურის პარამეტრები Width Profiles სიგანის პროფილები Apply Graphic Style გრაფიკული სტილის გამოყენება @@ -6363,6 +6386,11 @@ axis Both ორივე Image გამოსახულება Ink მელანი Lab Lab + OKLCH Sliders OKLCH სლაიდერები + HSL Sliders HSL სლაიდერები + Chroma ქრომა + The largest chroma sRGB holds at this lightness and hue უდიდესი ქრომა, რომელსაც sRGB იტევს ამ სიღიავესა და ფერის ტონზე + OKLCH needs sRGB as the working RGB space OKLCH-ს სამუშაო RGB სივრცედ sRGB სჭირდება Medium საშუალო Name სახელი None არცერთი @@ -6452,6 +6480,7 @@ font-technology Variable ცვლადი Recent Commands ბოლოდროინდელი ბრძანებები No recent commands ბოლოდროინდელი ბრძანებები არ არის Type to search commands, tools, panels and effects აკრიფეთ ბრძანებების, ხელსაწყოების, პანელებისა და ეფექტების მოსაძებნად + Clear Recent Commands ბოლო ბრძანებების სიის გასუფთავება Dashed Line ტირეებიანი ხაზი Panel menu პანელის მენიუ Unembed… ჩაშენების მოხსნა… @@ -6572,9 +6601,14 @@ font-technology Variable ცვლადი Edit type set in fonts that aren't available? დავარედაქტიროთ მიუწვდომელი შრიფტებით აწყობილი ტექსტი? Shows each slice's number in a box at its top left on the canvas; off, the slice outlines still show. ტილოზე თითოეული ნაჭრის ნომერს აჩვენებს ჩარჩოში მის ზედა მარცხენა კუთხეში; გამორთულისას ნაჭრების კონტურები კვლავ ჩანს. The color of user and object slice outlines and their number boxes; auto slices use a dimmer shade of it. მომხმარებლისა და ობიექტის ნაჭრების კონტურებისა და მათი ნომრების ჩარჩოების ფერი; ავტომატური ნაჭრები ამ ფერის უფრო მკრთალ ელფერს იყენებს. + In paragraphs with Hyphenate on, a listed word is hyphenated only at the hyphens typed in it, or never when it has none, whatever its language or case. აბზაცებში, სადაც სიტყვების გადატანა ჩართულია, სიაში მოცემული სიტყვა გადატანის დეფისს მხოლოდ მასში აკრეფილ დეფისებთან იღებს, ან არასდროს, თუ ისინი არ აქვს, მიუხედავად ენისა და რეგისტრისა. + On the desktop, this folder's .wasm plug-ins load at startup and when OK sets a new folder, except in Safe Mode; one that asks for permissions loads only after you grant them. The web version loads none. დესკტოპზე ამ საქაღალდის .wasm პლაგინები იტვირთება გაშვებისას და ახალი საქაღალდის OK-ით დაყენებისას, უსაფრთხო რეჟიმის გარდა; ნებართვების მომთხოვნი კი მათი მიცემის შემდეგ. ვებში არ იტვირთება. + Large gives each filter or command plug-in run at least 250 million instructions, with the same time limit; Normal keeps the plug-in's own budget. Live effects, exporters and importers keep theirs. დიდი ფილტრის ან ბრძანების პლაგინის გაშვებას მინიმუმ 250 მილიონ ინსტრუქციას აძლევს, იგივე დროის ლიმიტით; ჩვეულებრივი ბიუჯეტს ტოვებს. ცოცხალი ეფექტები, ექსპორტერები და იმპორტერები არ იცვლება. New type takes this language while Document Setup's language is English: USA; type already in a document keeps its own language. ახალი ტექსტი იღებს ამ ენას, სანამ დოკუმენტის პარამეტრების ენაა ინგლისური: აშშ; დოკუმენტში უკვე არსებული ტექსტი ინარჩუნებს თავის ენას. + New type takes this language while Document Setup's language is English: USA and [Normal Character Style] sets none; type already in a document keeps its own language. ახალი ტექსტი იღებს ამ ენას, სანამ დოკუმენტის პარამეტრების ენაა ინგლისური: აშშ და [ჩვეულებრივი სიმბოლოს სტილი] ენას არ ადგენს; დოკუმენტში უკვე არსებული ტექსტი ინარჩუნებს თავის ენას. In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its language or case. აბზაცებში, სადაც სიტყვების გადატანა ჩართულია, სიაში მოცემული სიტყვა მხოლოდ მასში აკრეფილ დეფისებთან გადაიტანება, ან არსად, თუ ისინი არ აქვს, მიუხედავად ენისა და რეგისტრისა. On the desktop, the .wasm plug-ins in this folder load at startup and when you click OK with a new folder here, except in Safe Mode; the web version does not load them. დესკტოპის ვერსიაში ამ საქაღალდის .wasm პლაგინები იტვირთება გაშვებისას და როცა აქ ახალი საქაღალდით OK-ს დააწკაპუნებთ, გარდა უსაფრთხო რეჟიმისა; ვებ-ვერსია მათ არ ტვირთავს. + Normal keeps each plug-in's own limits; with Large, a plug-in filter or command may run at least 250 million instructions besides those for its input. The time limit stays the same. ჩვეულებრივი ინარჩუნებს თითოეული პლაგინის საკუთარ ლიმიტებს; დიდით პლაგინის ფილტრს ან ბრძანებას შეუძლია შეასრულოს მინიმუმ 250 მილიონი ინსტრუქცია მისი შეყვანისთვის საჭირო ინსტრუქციების გარდა. დროის ლიმიტი იგივე რჩება. How many instructions each run of a plug-in object filter may use; Large allows more than Normal with the same 60-second limit. Heavy filters keep their own budget. რამდენი ინსტრუქციის გამოყენება შეუძლია პლაგინის ობიექტების ფილტრის თითოეულ გაშვებას; დიდი ჩვეულებრივზე მეტს უშვებს, იმავე 60-წამიანი ლიმიტით. მძიმე ფილტრები საკუთარ ბიუჯეტს ინარჩუნებენ. The first scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. სამუშაო დისკის პირველი არჩევანი: Startup, None ან საქაღალდის მისამართი; VectorCraft მას ინახავს, მაგრამ სამუშაო დისკებს ჯერ არ იყენებს. The second scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. სამუშაო დისკის მეორე არჩევანი: Startup, None ან საქაღალდის მისამართი; VectorCraft მას ინახავს, მაგრამ სამუშაო დისკებს ჯერ არ იყენებს. @@ -6586,13 +6620,15 @@ font-technology Variable ცვლადი Shows each tool group's name above its tools in the toolbar; off, the groups follow one another with nothing between them. ხელსაწყოთა ზოლში თითოეული ხელსაწყოების ჯგუფის სახელს მისი ხელსაწყოების ზემოთ აჩვენებს; გამორთულისას ჯგუფები ერთმანეთს მიჰყვება და მათ შორის არაფერია. From now on, documents you open or create open as tabs; off, each opens in a floating window. Documents already open stay where they are. ამიერიდან თქვენ მიერ გახსნილი ან შექმნილი დოკუმენტები ჩანართებად იხსნება; გამორთულისას თითოეული მცურავ ფანჯარაში იხსნება. უკვე გახსნილი დოკუმენტები თავის ადგილას რჩება. Makes the document tabs taller and their names larger. დოკუმენტების ჩანართებს უფრო მაღალს, მათ სახელებს კი უფრო დიდს ხდის. - From the next start, the system draws the window's title bar where VectorCraft would otherwise draw its own. შემდეგი გაშვებიდან სისტემა ხატავს ფანჯრის სათაურის ზოლს იქ, სადაც VectorCraft სხვა შემთხვევაში საკუთარს დახატავდა. - From the next start, VectorCraft draws the window's title bar even where the desktop would draw it, unless System Title Bar is on. შემდეგი გაშვებიდან VectorCraft ფანჯრის სათაურის ზოლს იქაც ხატავს, სადაც მას სამუშაო გარემო დახატავდა, თუ სისტემის სათაურის ზოლი არ არის ჩართული. + From the next start, the system draws the window's title bar where VectorCraft would otherwise draw its own; on Linux and the BSDs, the VECTORCRAFT_TITLEBAR variable takes precedence. შემდეგი გაშვებიდან სისტემა ხატავს ფანჯრის სათაურის ზოლს იქ, სადაც VectorCraft სხვა შემთხვევაში საკუთარს დახატავდა; Linux-სა და BSD-ზე უპირატესობა VECTORCRAFT_TITLEBAR ცვლადს აქვს. + From the next start, VectorCraft draws the window's title bar even where the desktop would draw it, unless System Title Bar is on or the VECTORCRAFT_TITLEBAR variable chooses it. შემდეგი გაშვებიდან VectorCraft ფანჯრის სათაურის ზოლს იქაც ხატავს, სადაც მას სამუშაო გარემო დახატავდა, თუ სისტემის სათაურის ზოლი არ არის ჩართული და მას VECTORCRAFT_TITLEBAR ცვლადი არ ირჩევს. Makes the interface larger or smaller; art on the canvas keeps its size at the same zoom. ინტერფეისს ადიდებს ან ამცირებს; ტილოზე არსებული ნახატი იმავე მასშტაბზე ზომას ინარჩუნებს. The tool pointers VectorCraft draws grow and shrink with UI Scaling; off, they keep their size. VectorCraft-ის მიერ დახატული ხელსაწყოების მაჩვენებლები ინტერფეისის მასშტაბირებასთან ერთად იზრდება და მცირდება; გამორთულისას ზომას ინარჩუნებს. The language of the interface; Auto uses the system's language. The dialog switches language as soon as you choose one. ინტერფეისის ენა; ავტომატური სისტემის ენას იყენებს. დიალოგი ენას იცვლის, როგორც კი რომელიმეს აირჩევთ. Animated Zoom works only while this is on; off, Animated Zoom is dimmed and zooming does not animate. ანიმირებული მასშტაბირება მუშაობს მხოლოდ მაშინ, როცა ეს ჩართულია; გამორთულისას ანიმირებული მასშტაბირება მკრთალია და მასშტაბირება არ ანიმირდება. The wheel's zoom glides in, and the Zoom tool zooms as you drag sideways or hold it down; off, the Zoom tool zooms to the area you drag across. ბორბლით მასშტაბირება რბილად სრიალებს, მასშტაბის ხელსაწყო კი ადიდებს, როცა გვერდზე გადაათრევთ ან დაჭერილს გაჩერებთ; გამორთულისას ის ადიდებს არეს, რომელზეც გადაათრევთ. + From the next start, the desktop version shows the canvas through this kind of graphics processor; the artwork is drawn on the CPU either way. Automatic prefers the integrated one on Windows and macOS. The web version does not use it. შემდეგი გაშვებიდან დესკტოპის ვერსია ტილოს აჩვენებს ამ ტიპის გრაფიკული პროცესორით; ნამუშევარი ყოველთვის CPU-ზე იხატება. ავტომატური Windows-სა და macOS-ზე ინტეგრირებულს ანიჭებს უპირატესობას. ვებ-ვერსია მას არ იყენებს. + From the next start, the window shows each frame without waiting for the display's refresh where the graphics driver allows, at most 240 frames a second. შემდეგი გაშვებიდან ფანჯარა აჩვენებს თითოეულ კადრს ეკრანის განახლების მოლოდინის გარეშე, სადაც გრაფიკული დრაივერი ამის საშუალებას იძლევა, წამში არაუმეტეს 240 კადრისა. From the next start, the desktop version draws with this kind of graphics processor; Automatic prefers the one that drives the display. The web version does not use it. შემდეგი გაშვებიდან დესკტოპის ვერსია ხატავს ამ ტიპის გრაფიკული პროცესორით; ავტომატური უპირატესობას ანიჭებს ეკრანის მმართველს. ვებ-ვერსია მას არ იყენებს. From the next start, the window shows frames without waiting for the display to refresh, at most 240 a second; off, the display paces them. A present mode set at launch overrides it. შემდეგი გაშვებიდან ფანჯარა აჩვენებს კადრებს ეკრანის განახლების მოლოდინის გარეშე, წამში არაუმეტეს 240-ისა; გამორთულისას ტემპს ეკრანი განსაზღვრავს. უპირატესობა აქვს გაშვებისას დაყენებულ ჩვენების რეჟიმს. The most undo steps each document keeps; lowering it drops the oldest steps when you click OK. Steps can also go sooner when they use too much memory. გაუქმების ნაბიჯების მაქსიმალური რაოდენობა თითო დოკუმენტში; მცირე რიცხვი OK-ზე დაწკაპუნებისას შლის უძველეს ნაბიჯებს. ნაბიჯები შეიძლება ადრეც წაიშალოს, თუ ბევრ მეხსიერებას იკავებს. @@ -6611,6 +6647,9 @@ font-technology Variable ცვლადი Open Recent Files and the Home screen list at most this many recent files; 0 lists none, and VectorCraft still remembers up to 30. „ბოლოს გახსნილი ფაილების გახსნა“ და „საწყისი ეკრანი“ აჩვენებს მაქსიმუმ ამდენ ბოლო ფაილს; 0 არცერთს არ აჩვენებს, VectorCraft კი მაინც იმახსოვრებს 30-მდე ფაილს. When a document opens, a linked EPS image that shows its saved preview keeps it instead of reading the EPS file again; changed files still follow Update Links. დოკუმენტის გახსნისას მიბმული EPS გამოსახულება, რომელიც თავის შენახულ გადახედვას აჩვენებს, ინარჩუნებს მას EPS ფაილის ხელახლა წაკითხვის ნაცვლად; შეცვლილი ფაილები კვლავ „ბმულების განახლებას“ მისდევს. In Pixel Preview, images are drawn smoothed; off, their pixels show with hard edges. Outside Pixel Preview, images are always smoothed. „პიქსელების წინასწარ ნახვაში“ გამოსახულებები გლუვად იხატება; გამორთულისას მათი პიქსელები მკვეთრი კიდეებით ჩანს. მის გარეთ გამოსახულებები ყოველთვის გლუვდება. + PDF Text PDF-ის ტექსტი + The text of a PDF you open or embed comes in as editable type, or as outlines that look the same on a computer without its fonts. PDF-ის ტექსტი, რომელსაც ხსნით ან ჩაშენებთ, შემოდის რედაქტირებად ტექსტად ან კონტურებად, რომლებიც ერთნაირად ჩანს კომპიუტერზე მისი შრიფტების გარეშე. + Linked pages show the file's own text. მიბმული გვერდები ფაილის საკუთარ ტექსტს აჩვენებს. When a linked file changes, Automatically reads it again, Ask When Modified asks you first, and Manually leaves it and shows a note in the status bar. როცა მიბმული ფაილი იცვლება, „ავტომატურად“ მას ხელახლა კითხულობს, „შეკითხვა ცვლილებისას“ ჯერ გეკითხებათ, „ხელით“ კი უცვლელად ტოვებს და სტატუსის ზოლში შენიშვნას აჩვენებს. On the desktop, the folder New from Template… and Save as Template… start in; leave it blank for VectorCraft Templates in your documents folder. დესკტოპის ვერსიაში საქაღალდე, საიდანაც „შაბლონიდან შექმნა…“ და „შაბლონად შენახვა…“ იწყება; დატოვეთ ცარიელი თქვენი დოკუმენტების საქაღალდეში არსებული VectorCraft Templates-ისთვის. Edit Original opens a linked file in the system's default app for its type; off, a linked raster image opens in PhotoCraft where it is installed. „ორიგინალის რედაქტირება“ მიბმულ ფაილს მისი ტიპისთვის სისტემის ნაგულისხმევ აპში ხსნის; გამორთულისას მიბმული რასტრული გამოსახულება PhotoCraft-ში იხსნება, თუ ის დაინსტალირებულია. @@ -6625,7 +6664,6 @@ font-technology Variable ცვლადი Output All Blacks as Rich Black draws pure CMYK black as RGB black in RGB and grayscale raster exports and Print as Bitmap; it does not change vector exports, CMYK JPEG, TIFF and PSD, or other printing. ყველა შავის მდიდარ შავად გამოტანა სუფთა CMYK შავს RGB შავად ხატავს RGB და ნაცრისფერი გრადაციების რასტრულ ექსპორტებში და ბიტმაპად ბეჭდვისას; ის არ ცვლის ვექტორულ ექსპორტებს, CMYK JPEG-ს, TIFF-სა და PSD-ს ან სხვა ბეჭდვას. On a touch screen, switches to the Touch workspace; turning this off, or losing the touch screen, goes back to the workspace it switched from. სენსორულ ეკრანზე გადადის სენსორულ სამუშაო სივრცეზე; პარამეტრის გამორთვისას ან სენსორული ეკრანის დაკარგვისას ბრუნდება წინა სამუშაო სივრცეზე. A two-finger tap on the canvas undoes, or switches between selection and drawing tools in the Touch workspace, and a three-finger tap redoes; neither works in Presentation Mode. ტილოზე ორი თითით შეხება აბრუნებს მოქმედებას, სენსორულ სამუშაო სივრცეში კი მონიშვნისა და ხატვის ხელსაწყოებს შორის გადართავს; სამი თითით შეხება ხელახლა ასრულებს. პრეზენტაციის რეჟიმში არცერთი არ მუშაობს. - New type takes this language while Document Setup's language is English: USA and [Normal Character Style] sets none; type already in a document keeps its own language. ახალი ტექსტი იღებს ამ ენას, სანამ დოკუმენტის პარამეტრების ენაა ინგლისური: აშშ და [ჩვეულებრივი სიმბოლოს სტილი] ენას არ ადგენს; დოკუმენტში უკვე არსებული ტექსტი ინარჩუნებს თავის ენას. In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its case; Korean words take no hyphen, and Indian-language words do not break inside a character cluster. გადატანის ჩართვისას სიის სიტყვა მხოლოდ აკრეფილ დეფისებთან გადაიტანება, ან არსად, თუ არ აქვს, რეგისტრის მიუხედავად; კორეულ სიტყვებს დეფისი არ ემატება, ინდური ენების სიტყვები კი სიმბოლოთა ჯგუფის შიგნით არ გადაიტანება. Reset all preferences to their defaults? დავაბრუნოთ ყველა პარამეტრი ნაგულისხმევ მნიშვნელობებზე? The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. ნაგულისხმევი მნიშვნელობები გამოიყენება, როცა პარამეტრებში OK-ს დააჭერთ. იქ გაუქმება ინარჩუნებს თქვენს მიმდინარე პარამეტრებს. @@ -6648,6 +6686,10 @@ font-technology Variable ცვლადი Cusp წვეტი Straight segment სწორი სეგმენტი Circle too large წრე ზედმეტად დიდია + Show Radii რადიუსების ჩვენება + Show Diameter დიამეტრის ჩვენება + Anchors at Standard Positions საყრდენი წერტილები სტანდარტულ პოზიციებზე + Third Point by Dragging მესამე წერტილი გადათრევით Clip to Art ნახატზე მოჭრა Colorize გაფერადება Gamma გამა @@ -7339,6 +7381,10 @@ font-technology Variable ცვლადი @msg this trace would make more than {max} anchor points, more than the document can show smoothly: raise Noise, lower Paths or Colors, or pick a lower-fidelity preset ეს ვექტორიზაცია {max}-ზე მეტ საყრდენ წერტილს შექმნიდა, რასაც დოკუმენტი შეუფერხებლად ვერ აჩვენებს: გაზარდეთ ხმაური, შეამცირეთ ტრაექტორიები ან ფერები, ან აირჩიეთ ნაკლები სიზუსტის პრესეტი @msg select an envelope მონიშნეთ გარსი @msg select an image მონიშნეთ გამოსახულება +@msg object {_1} is an image changed by Perspective Distort or Free Distort, which this command does not work on ობიექტი {_1} არის პერსპექტიული დეფორმაციით ან თავისუფალი დეფორმაციით შეცვლილი გამოსახულება, რომელზეც ეს ბრძანება არ მუშაობს +@msg image {_1} cannot be distorted this way: its corners would not make a convex shape გამოსახულება {_1} ასე ვერ დეფორმირდება: მისი კუთხეები ამოზნექილ ფორმას ვერ შექმნის +@msg image {_1} cannot be distorted this way: its corners would cross the warp's horizon გამოსახულება {_1} ასე ვერ დეფორმირდება: მისი კუთხეები დეფორმაციის ჰორიზონტს გადაკვეთს +@msg image {_1} cannot be distorted this way: its corners would be too close together for a perspective map გამოსახულება {_1} ასე ვერ დეფორმირდება: მისი კუთხეები პერსპექტიული ასახვისთვის ერთმანეთთან ძალიან ახლოს იქნება @msg `background` must be edges, corners or colors `background` უნდა იყოს edges, corners ან colors @msg `match` must be distance or channels `match` უნდა იყოს distance ან channels @msg `{key}` must be from 0 to 100 `{key}` უნდა იყოს 0-დან 100-მდე @@ -8155,7 +8201,10 @@ arrowhead Feather ბუმბული @msg the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate) ობიექტს არ აქვს 3D ეფექტი (ამოწევა და წაკვეთა, ბრუნვა, გაბერვა ან შემობრუნება) @msg `render` must be an object holding only `mode`, set to shaded or wireframe `render` უნდა იყოს ობიექტი, რომელიც შეიცავს მხოლოდ `mode`-ს, მნიშვნელობით shaded ან wireframe @msg its 3D effect builds no solid მისი 3D ეფექტი სხეულს არ ქმნის -@msg bevel must be none or one of {_1} bevel უნდა იყოს none ან ერთ-ერთი: {_1} +@msg bevel must be none or one of {_1}, or custom with {BEVEL_PROFILE} bevel უნდა იყოს none, ერთ-ერთი: {_1}, ან custom და {BEVEL_PROFILE} +@msg bevel custom needs {BEVEL_PROFILE}, the bevel's points bevel custom მოითხოვს {BEVEL_PROFILE}, წაკვეთის წერტილები +@msg {BEVEL_NAME} must be a string {BEVEL_NAME} უნდა იყოს სტრიქონი +@msg {BEVEL_PROFILE} must be 2 to {most} [x, y] points, each share between 0 and 1, from [0, 0] (the cap's edge) to [1, 1] (the side wall) {BEVEL_PROFILE} უნდა შეიცავდეს 2-დან {most}-მდე [x, y] წერტილს, თითოეული წილი 0-სა და 1-ს შორის, [0, 0]-დან (ბოლო წახნაგის კიდე) [1, 1]-მდე (გვერდითი კედელი) @msg {_1} can't build solids from this art: its symbol instances, blends and clipping groups hold too many objects {_1}: ამ ნახატიდან სხეულების შექმნა შეუძლებელია: მისი სიმბოლოს ეგზემპლარები, გადასვლები და მომჭრელი ჯგუფები ზედმეტად ბევრ ობიექტს შეიცავს @msg {label} can't build a solid from the instance of symbol "{symbol}": the symbol's art isn't available {label}: სიმბოლოს „{symbol}“ ეგზემპლარიდან სხეულის შექმნა შეუძლებელია: სიმბოლოს ნახატი მიუწვდომელია @msg {_1}: the clipping path is too complex to cut the art with {_1}: მომჭრელი ტრაექტორია ზედმეტად რთულია ნახატის მოსაჭრელად @@ -8776,6 +8825,8 @@ liquify-list-end {0}, {1} {0} და {1} @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` უნდა იყოს grayscale, rgb, hsb, cmyk ან websafe @msg `view` must be wheel or box `view` უნდა იყოს wheel ან box @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` უნდა იყოს hue, saturation, brightness, red, green ან blue +@msg `sliders` must be none, oklch or hsl `sliders` უნდა იყოს none, oklch ან hsl +@msg OKLCH needs sRGB as the working RGB space OKLCH-ს სამუშაო RGB სივრცედ sRGB სჭირდება @msg this is a PostScript file (an .ai saved in an older format or without PDF compatibility, or an EPS file), not a PDF: File › Open and File › Place read it as EPS ეს PostScript ფაილია (ძველ ფორმატში ან PDF-თან თავსებადობის გარეშე შენახული .ai, ან EPS ფაილი) და არა PDF: ფაილი › გახსნა და ფაილი › განთავსება მას EPS-ად კითხულობს # Upstream sync 2026-10-16 (3): Intertwine, symbol registration, gradient span, data sets, Batch. Intertwine გადახლართვა @@ -11034,6 +11085,20 @@ font-script Japanese იაპონური @msg A joint does not close by {gap} pt. შეერთება არ იხურება {gap} pt-ით. @msg Two panels pass through each other. ორი პანელი ერთმანეთში გადის. @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer უნდა იყოს "singleLine", "everyLine", "standardSingleLine" ან "standardEveryLine" + Vector Packs ვექტორული პაკეტები + Compass Rose კომპასის ვარდი + Botanical Sprig ბოტანიკური ტოტი + Facet Diamond წახნაგოვანი ბრილიანტი + Tide Crest ტალღის ქედი + Leaf Vine ფოთლების ვაზი + Blossom Chain ყვავილების ჯაჭვი + Pennant Garland ალმების გირლანდა + Lantern String ფარნების ჯაჭვი + Orbit Lines ორბიტული ხაზები + Petal Garland ფურცლების გირლანდა + Lattice Braid ბადის ნაწნავი + Facet Sweep წახნაგოვანი მონასმი + Artistic Brushes მხატვრული ფუნჯები Paint საღებავი Flat Sweep ბრტყელი მოსმა Dry Drag მშრალი მოსმა diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 62c01a01d5..1d10c26313 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -392,6 +392,10 @@ digits Malayalam 말라얄람어 Rename Preset 프리셋 이름 바꾸기 Save Image Trace Preset 이미지 추적 프리셋 저장 Delete Image Trace Preset 이미지 추적 프리셋 삭제 + Tracing Presets… 추적 프리셋… + Import Image Trace Presets 이미지 추적 프리셋 가져오기 + Export Image Trace Presets 이미지 추적 프리셋 내보내기 + Replace the saved presets that have these names? 이 이름을 가진 저장된 프리셋을 대체하시겠습니까? Text Wrap 문자 감싸기 Text Wrap Options… 문자 감싸기 옵션… Clipping Mask 클리핑 마스크 @@ -839,6 +843,8 @@ digits Malayalam 말라얄람어 Contextual Task Bar 상황별 작업 표시줄 Pin Bar Position 표시줄 위치 고정 Reset Bar Position 표시줄 위치 재설정 + Bar Actions 표시줄 동작 + Reset Bar Actions 표시줄 동작 재설정 Resize 크기 조절 Tools 도구 Toolbars 도구 모음 @@ -859,9 +865,14 @@ digits Malayalam 말라얄람어 {name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2} Wheel View 휠 보기 Box View 상자 보기 + Show Out-of-Gamut Colors 색상 범위를 벗어난 색상 표시 Box Channel 상자 채널 Color box 색상 상자 Color Wheel Options 색상환 옵션 + Show Document Colors 문서 색상 표시 + Document Colors 문서 색상 + Selection Colors 선택 영역 색상 +@plural Used {n} time|Used {n} times {n}회 사용 Show Harmony 하모니 표시 Harmony Rule 하모니 규칙 Harmony color 하모니 색상 @@ -1402,6 +1413,11 @@ antiAlias Sharp 날카롭게 Cusp 뾰족점 Straight segment 직선 세그먼트 Circle too large 원이 너무 큽니다 + Show Radii 반지름 표시 + Show Diameter 지름 표시 + Anchors at Standard Positions 표준 위치에 앵커 포인트 + Third Point by Dragging 드래그로 세 번째 점 지정 + Gray 회색 Clear All Tabs 모든 탭 지우기 Above Text 문자 위 Position Panel Above Text 패널을 문자 위에 배치 @@ -2925,6 +2941,13 @@ antiAlias Sharp 날카롭게 Pen Tool 펜 도구 Quick Pen Tool 빠른 펜 도구 Quick Pen 빠른 펜 + Quick Pen Toolbar 빠른 펜 도구 모음 + Continuous Arc 연속 호 + Sharp Corner Arc 뾰족한 모서리 호 + Flip Arc 호 뒤집기 + Hide Toolbar 도구 모음 숨기기 + Pin Toolbar Position 도구 모음 위치 고정 + Reset Toolbar Position 도구 모음 위치 재설정 Pencil 연필 Pencil Tool 연필 도구 Percent: 퍼센트: @@ -3256,6 +3279,11 @@ mark-style Japanese 일본식 Edit Arrowheads 화살촉 편집 Edit Arrowheads… 화살촉 편집… Reload Arrowheads 화살촉 다시 불러오기 + Bevels 베벨 목록 + Edit Bevels 베벨 편집 + Edit Bevels… 베벨 편집… + {name} (document) {name}(문서) + Reload Bevels 베벨 다시 불러오기 Reset the rows to the artwork's colors 행을 아트웍 색상으로 재설정 Color Theme Picker 색상 테마 피커 Undo Changes 변경 내용 실행 취소 @@ -3387,9 +3415,14 @@ mark-style Japanese 일본식 Edit type set in fonts that aren't available? 사용할 수 없는 글꼴로 설정된 문자를 편집하시겠습니까? Shows each slice's number in a box at its top left on the canvas; off, the slice outlines still show. 캔버스에서 각 슬라이스의 번호를 왼쪽 위의 상자에 표시합니다. 끄더라도 슬라이스 윤곽선은 계속 표시됩니다. The color of user and object slice outlines and their number boxes; auto slices use a dimmer shade of it. 사용자 슬라이스와 개체 슬라이스의 윤곽선 및 번호 상자의 색상입니다. 자동 슬라이스에는 이 색상의 더 흐린 색조가 사용됩니다. + In paragraphs with Hyphenate on, a listed word is hyphenated only at the hyphens typed in it, or never when it has none, whatever its language or case. 하이픈 넣기가 켜진 단락에서는 목록의 단어에 입력한 하이픈 위치에서만 하이픈이 들어가며, 하이픈이 없으면 하이픈이 들어가지 않습니다. 언어나 대소문자는 상관없습니다. + On the desktop, this folder's .wasm plug-ins load at startup and when OK sets a new folder, except in Safe Mode; one that asks for permissions loads only after you grant them. The web version loads none. 데스크톱 버전에서는 이 폴더의 .wasm 플러그인이 시작할 때와 확인으로 새 폴더를 설정할 때 로드됩니다(안전 모드 제외). 권한을 요청하는 플러그인은 권한을 허용한 뒤에만 로드됩니다. 웹 버전은 로드하지 않습니다. + Large gives each filter or command plug-in run at least 250 million instructions, with the same time limit; Normal keeps the plug-in's own budget. Live effects, exporters and importers keep theirs. 크게는 필터 또는 명령 플러그인의 각 실행에 같은 시간 제한으로 최소 2억 5천만 개의 명령어를 줍니다. 표준은 플러그인 자체의 예산을 유지합니다. 라이브 효과, 내보내기와 가져오기는 각자의 예산을 유지합니다. New type takes this language while Document Setup's language is English: USA; type already in a document keeps its own language. 문서 설정의 언어가 영어: 미국인 동안 새 텍스트는 이 언어를 받습니다. 문서에 이미 있는 텍스트는 자체 언어를 유지합니다. + New type takes this language while Document Setup's language is English: USA and [Normal Character Style] sets none; type already in a document keeps its own language. 문서 설정의 언어가 영어: 미국이고 [기본 문자 스타일]이 언어를 지정하지 않는 동안 새 텍스트는 이 언어를 받습니다. 문서에 이미 있는 텍스트는 자체 언어를 유지합니다. In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its language or case. 하이픈 넣기가 켜진 단락에서는 목록의 단어가 입력한 하이픈 위치에서만 나뉘며, 하이픈이 없으면 나뉘지 않습니다. 언어나 대소문자는 상관없습니다. On the desktop, the .wasm plug-ins in this folder load at startup and when you click OK with a new folder here, except in Safe Mode; the web version does not load them. 데스크톱 버전에서는 이 폴더의 .wasm 플러그인이 시작할 때와 여기에 새 폴더를 지정하고 확인을 클릭할 때 로드됩니다(안전 모드 제외). 웹 버전은 로드하지 않습니다. + Normal keeps each plug-in's own limits; with Large, a plug-in filter or command may run at least 250 million instructions besides those for its input. The time limit stays the same. 표준은 각 플러그인 자체의 제한을 유지합니다. 크게에서는 플러그인 필터나 명령이 입력에 필요한 명령어 외에 최소 2억 5천만 개의 명령어를 실행할 수 있습니다. 시간 제한은 그대로입니다. How many instructions each run of a plug-in object filter may use; Large allows more than Normal with the same 60-second limit. Heavy filters keep their own budget. 플러그인의 개체 필터를 한 번 실행할 때 쓸 수 있는 명령어 수입니다. 크게는 표준보다 많이 허용하며 60초 제한은 같습니다. 무거운 필터는 자체 예산을 유지합니다. The first scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. 첫 번째 스크래치 디스크 선택: Startup, None 또는 폴더 경로. VectorCraft는 이 값을 저장하지만 아직 스크래치 디스크를 사용하지 않습니다. The second scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. 두 번째 스크래치 디스크 선택: Startup, None 또는 폴더 경로. VectorCraft는 이 값을 저장하지만 아직 스크래치 디스크를 사용하지 않습니다. @@ -3401,13 +3434,15 @@ mark-style Japanese 일본식 Shows each tool group's name above its tools in the toolbar; off, the groups follow one another with nothing between them. 도구 모음에서 각 도구 그룹의 이름을 해당 도구 위에 표시합니다. 끄면 그룹 사이에 아무것도 없이 이어집니다. From now on, documents you open or create open as tabs; off, each opens in a floating window. Documents already open stay where they are. 지금부터 열거나 만드는 문서는 탭으로 열립니다. 끄면 각 문서가 플로팅 창에서 열립니다. 이미 열린 문서는 그대로 있습니다. Makes the document tabs taller and their names larger. 문서 탭을 더 높게, 이름을 더 크게 표시합니다. - From the next start, the system draws the window's title bar where VectorCraft would otherwise draw its own. 다음 시작부터는 VectorCraft가 자체 제목 표시줄을 그렸을 곳에서 시스템이 창의 제목 표시줄을 그립니다. - From the next start, VectorCraft draws the window's title bar even where the desktop would draw it, unless System Title Bar is on. 다음 시작부터는 데스크톱이 제목 표시줄을 그리는 곳에서도 VectorCraft가 창의 제목 표시줄을 그립니다. 단, 시스템 제목 표시줄이 켜져 있으면 그렇지 않습니다. + From the next start, the system draws the window's title bar where VectorCraft would otherwise draw its own; on Linux and the BSDs, the VECTORCRAFT_TITLEBAR variable takes precedence. 다음 시작부터는 VectorCraft가 자체 제목 표시줄을 그렸을 곳에서 시스템이 창의 제목 표시줄을 그립니다. Linux와 BSD에서는 VECTORCRAFT_TITLEBAR 변수가 우선합니다. + From the next start, VectorCraft draws the window's title bar even where the desktop would draw it, unless System Title Bar is on or the VECTORCRAFT_TITLEBAR variable chooses it. 다음 시작부터는 데스크톱이 제목 표시줄을 그리는 곳에서도 VectorCraft가 창의 제목 표시줄을 그립니다. 단, 시스템 제목 표시줄이 켜져 있거나 VECTORCRAFT_TITLEBAR 변수가 선택하면 그렇지 않습니다. Makes the interface larger or smaller; art on the canvas keeps its size at the same zoom. 인터페이스를 크게 또는 작게 만듭니다. 같은 확대/축소에서 캔버스의 아트는 크기가 그대로입니다. The tool pointers VectorCraft draws grow and shrink with UI Scaling; off, they keep their size. VectorCraft가 그리는 도구 포인터가 UI 배율에 따라 커지고 작아집니다. 끄면 크기가 그대로 유지됩니다. The language of the interface; Auto uses the system's language. The dialog switches language as soon as you choose one. 인터페이스의 언어입니다. 자동은 시스템 언어를 사용합니다. 언어를 고르면 대화 상자가 바로 그 언어로 바뀝니다. Animated Zoom works only while this is on; off, Animated Zoom is dimmed and zooming does not animate. 애니메이션 확대/축소는 이 옵션이 켜져 있을 때만 작동합니다. 끄면 애니메이션 확대/축소가 흐리게 표시되고 확대/축소에 애니메이션이 없습니다. The wheel's zoom glides in, and the Zoom tool zooms as you drag sideways or hold it down; off, the Zoom tool zooms to the area you drag across. 휠로 확대/축소하면 부드럽게 움직이고, 확대/축소 도구는 옆으로 드래그하거나 누르고 있으면 확대/축소합니다. 끄면 확대/축소 도구는 드래그한 영역으로 확대합니다. + From the next start, the desktop version shows the canvas through this kind of graphics processor; the artwork is drawn on the CPU either way. Automatic prefers the integrated one on Windows and macOS. The web version does not use it. 다음 시작부터 데스크톱 버전은 이 종류의 그래픽 프로세서를 통해 캔버스를 표시합니다. 아트워크는 항상 CPU에서 그려집니다. 자동은 Windows와 macOS에서 내장 프로세서를 우선합니다. 웹 버전은 사용하지 않습니다. + From the next start, the window shows each frame without waiting for the display's refresh where the graphics driver allows, at most 240 frames a second. 다음 시작부터 그래픽 드라이버가 허용하는 경우 창은 디스플레이 새로 고침을 기다리지 않고 각 프레임을 표시하며, 초당 최대 240프레임입니다. From the next start, the desktop version draws with this kind of graphics processor; Automatic prefers the one that drives the display. The web version does not use it. 다음 시작부터 데스크톱 버전은 이 종류의 그래픽 프로세서로 그립니다. 자동은 디스플레이를 구동하는 프로세서를 우선합니다. 웹 버전은 사용하지 않습니다. From the next start, the window shows frames without waiting for the display to refresh, at most 240 a second; off, the display paces them. A present mode set at launch overrides it. 다음 시작부터 창은 디스플레이 새로 고침을 기다리지 않고 프레임을 표시하며, 초당 최대 240프레임입니다. 끄면 디스플레이가 프레임 속도를 정합니다. 시작할 때 지정한 표시 모드가 우선합니다. The most undo steps each document keeps; lowering it drops the oldest steps when you click OK. Steps can also go sooner when they use too much memory. 각 문서가 보관하는 실행 취소 단계의 최대 수입니다. 낮추면 확인을 클릭할 때 가장 오래된 단계가 삭제됩니다. 메모리를 너무 많이 쓰면 단계가 더 일찍 삭제될 수도 있습니다. @@ -3426,6 +3461,9 @@ mark-style Japanese 일본식 Open Recent Files and the Home screen list at most this many recent files; 0 lists none, and VectorCraft still remembers up to 30. 최근 파일 열기와 홈 화면에 표시하는 최근 파일의 최대 개수입니다. 0이면 표시하지 않지만 VectorCraft는 여전히 최대 30개를 기억합니다. When a document opens, a linked EPS image that shows its saved preview keeps it instead of reading the EPS file again; changed files still follow Update Links. 문서를 열 때 저장된 미리 보기를 표시하는 연결된 EPS 이미지는 EPS 파일을 다시 읽지 않고 그 미리 보기를 유지합니다. 변경된 파일은 계속 링크 업데이트 설정을 따릅니다. In Pixel Preview, images are drawn smoothed; off, their pixels show with hard edges. Outside Pixel Preview, images are always smoothed. 픽셀 미리 보기에서 이미지를 매끄럽게 그립니다. 끄면 픽셀 가장자리가 선명하게 보입니다. 픽셀 미리 보기 밖에서는 이미지가 항상 매끄럽습니다. + PDF Text PDF 텍스트 + The text of a PDF you open or embed comes in as editable type, or as outlines that look the same on a computer without its fonts. 열거나 포함하는 PDF의 텍스트를 편집 가능한 텍스트로, 또는 글꼴이 없는 컴퓨터에서도 똑같이 보이는 윤곽선으로 가져옵니다. + Linked pages show the file's own text. 연결된 페이지는 파일 자체의 텍스트를 표시합니다. When a linked file changes, Automatically reads it again, Ask When Modified asks you first, and Manually leaves it and shows a note in the status bar. 연결된 파일이 바뀌면 자동으로는 다시 읽고, 수정 시 확인은 먼저 묻고, 수동은 그대로 두고 상태 표시줄에 메모를 표시합니다. On the desktop, the folder New from Template… and Save as Template… start in; leave it blank for VectorCraft Templates in your documents folder. 데스크톱 버전에서 템플릿에서 새로 만들기…와 템플릿으로 저장…이 처음 여는 폴더입니다. 비워 두면 문서 폴더의 VectorCraft Templates를 사용합니다. Edit Original opens a linked file in the system's default app for its type; off, a linked raster image opens in PhotoCraft where it is installed. 원본 편집은 연결된 파일을 해당 유형에 대한 시스템 기본 앱에서 엽니다. 끄면 연결된 래스터 이미지는 PhotoCraft가 설치되어 있을 때 PhotoCraft에서 열립니다. @@ -3440,7 +3478,6 @@ mark-style Japanese 일본식 Output All Blacks as Rich Black draws pure CMYK black as RGB black in RGB and grayscale raster exports and Print as Bitmap; it does not change vector exports, CMYK JPEG, TIFF and PSD, or other printing. 모든 검정을 리치 블랙으로 출력은 RGB 및 그레이스케일 래스터 내보내기와 비트맵으로 인쇄에서 순수 CMYK 검정을 RGB 검정으로 그리며, 벡터 내보내기, CMYK JPEG, TIFF 및 PSD, 기타 인쇄는 바꾸지 않습니다. On a touch screen, switches to the Touch workspace; turning this off, or losing the touch screen, goes back to the workspace it switched from. 터치 스크린에서는 터치 작업 영역으로 전환합니다. 이 설정을 끄거나 터치 스크린이 사라지면 전환하기 전의 작업 영역으로 돌아갑니다. A two-finger tap on the canvas undoes, or switches between selection and drawing tools in the Touch workspace, and a three-finger tap redoes; neither works in Presentation Mode. 캔버스를 두 손가락으로 탭하면 실행 취소하거나 터치 작업 영역에서 선택 도구와 그리기 도구를 전환하고, 세 손가락으로 탭하면 다시 실행합니다. 프레젠테이션 모드에서는 둘 다 작동하지 않습니다. - New type takes this language while Document Setup's language is English: USA and [Normal Character Style] sets none; type already in a document keeps its own language. 문서 설정의 언어가 영어: 미국이고 [기본 문자 스타일]이 언어를 지정하지 않는 동안 새 텍스트는 이 언어를 받습니다. 문서에 이미 있는 텍스트는 자체 언어를 유지합니다. In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its case; Korean words take no hyphen, and Indian-language words do not break inside a character cluster. 하이픈 넣기가 켜진 단락에서는 목록의 단어가 입력한 하이픈 위치에서만 나뉘며, 하이픈이 없으면 나뉘지 않습니다. 대소문자는 상관없습니다. 한국어 단어에는 하이픈이 붙지 않으며, 인도 언어의 단어는 문자 묶음 안에서 나뉘지 않습니다. Reset all preferences to their defaults? 모든 환경 설정을 기본값으로 재설정하시겠습니까? The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. 기본값은 환경 설정에서 확인을 클릭하면 적용됩니다. 그곳에서 취소를 누르면 현재 환경 설정이 유지됩니다. @@ -3588,6 +3625,7 @@ mark-style Japanese 일본식 Recent Commands 최근 명령 No recent commands 최근 명령 없음 Type to search commands, tools, panels and effects 입력하여 명령, 도구, 패널 및 효과 검색 + Clear Recent Commands 최근 명령 목록 지우기 Search commands 명령 검색 Secondary 보조 Select All Art on Layer 레이어의 모든 아트웍 선택 @@ -4406,6 +4444,11 @@ file-filter Templates 템플릿 Keep the pasted color as a new swatch with a numbered name. 붙여넣은 색상을 번호가 붙은 이름의 새 견본으로 보관합니다. Keep: 유지: Lab Lab + OKLCH Sliders OKLCH 슬라이더 + HSL Sliders HSL 슬라이더 + Chroma 크로마 + The largest chroma sRGB holds at this lightness and hue 이 명도와 색조에서 sRGB가 담을 수 있는 최대 크로마 + OKLCH needs sRGB as the working RGB space OKLCH를 사용하려면 작업 RGB 공간이 sRGB여야 합니다 Lab Values Lab 값 Large List View 큰 목록 보기 Large Thumbnail View 큰 축소판 보기 @@ -5569,6 +5612,8 @@ variable-list-end {0}, {1} {0} 및 {1} @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode`은(는) grayscale, rgb, hsb, cmyk, websafe 중 하나여야 합니다 @msg `view` must be wheel or box `view`은(는) wheel, box 중 하나여야 합니다 @msg `channel` must be hue, saturation, brightness, red, green or blue `channel`은(는) hue, saturation, brightness, red, green, blue 중 하나여야 합니다 +@msg `sliders` must be none, oklch or hsl `sliders`는 none, oklch 또는 hsl이어야 합니다 +@msg OKLCH needs sRGB as the working RGB space OKLCH를 사용하려면 작업 RGB 공간이 sRGB여야 합니다 @msg `{key}` must be true or false `{key}`은(는) true 또는 false여야 합니다 @msg `top` and `below` can't both be true `top`과 `below`를 동시에 true로 지정할 수 없습니다 @msg `select` must be true or false `select`은(는) true 또는 false여야 합니다 @@ -5603,6 +5648,10 @@ variable-list-end {0}, {1} {0} 및 {1} @msg no such view 해당 보기가 없습니다 @msg printing isn't available here 여기서는 인쇄할 수 없습니다 @msg select an image 이미지를 선택하세요 +@msg object {_1} is an image changed by Perspective Distort or Free Distort, which this command does not work on 개체 {_1}은(는) 원근 왜곡 또는 자유 왜곡으로 변경된 이미지이므로 이 명령을 사용할 수 없습니다 +@msg image {_1} cannot be distorted this way: its corners would not make a convex shape 이미지 {_1}을(를) 이렇게 왜곡할 수 없습니다: 모서리가 볼록한 모양을 이루지 않습니다 +@msg image {_1} cannot be distorted this way: its corners would cross the warp's horizon 이미지 {_1}을(를) 이렇게 왜곡할 수 없습니다: 모서리가 왜곡의 지평선을 넘습니다 +@msg image {_1} cannot be distorted this way: its corners would be too close together for a perspective map 이미지 {_1}을(를) 이렇게 왜곡할 수 없습니다: 모서리가 원근 매핑을 하기에 너무 가깝습니다 @msg `background` must be edges, corners or colors `background`는 edges, corners 또는 colors여야 합니다 @msg `match` must be distance or channels `match`는 distance 또는 channels여야 합니다 @msg `{key}` must be from 0 to 100 `{key}`는 0에서 100 사이여야 합니다 @@ -6413,7 +6462,10 @@ lighting Light 광원 @msg the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate) 개체에 3D 효과(돌출 및 경사, 회전체, 부풀리기 또는 회전)가 없습니다 @msg `render` must be an object holding only `mode`, set to shaded or wireframe `render`는 값이 shaded 또는 wireframe인 `mode`만 있는 객체여야 합니다 @msg its 3D effect builds no solid 3D 효과가 입체를 만들지 않습니다 -@msg bevel must be none or one of {_1} bevel은 none 또는 {_1} 중 하나여야 합니다 +@msg bevel must be none or one of {_1}, or custom with {BEVEL_PROFILE} bevel은 none, {_1} 중 하나 또는 {BEVEL_PROFILE}을(를) 함께 지정한 custom이어야 합니다 +@msg bevel custom needs {BEVEL_PROFILE}, the bevel's points bevel custom에는 베벨의 포인트인 {BEVEL_PROFILE}이(가) 필요합니다 +@msg {BEVEL_NAME} must be a string {BEVEL_NAME}은(는) 문자열이어야 합니다 +@msg {BEVEL_PROFILE} must be 2 to {most} [x, y] points, each share between 0 and 1, from [0, 0] (the cap's edge) to [1, 1] (the side wall) {BEVEL_PROFILE}은(는) 2개에서 {most}개의 [x, y] 포인트여야 하며, 각 값은 0과 1 사이의 비율이고 [0, 0](끝면의 가장자리)에서 [1, 1](옆면 벽)까지여야 합니다 @msg {_1} can't build solids from this art: its symbol instances, blends and clipping groups hold too many objects {_1}은(는) 이 아트로 입체를 만들 수 없습니다. 심볼 인스턴스, 블렌드, 클리핑 그룹에 개체가 너무 많습니다 @msg {label} can't build a solid from the instance of symbol "{symbol}": the symbol's art isn't available {label}은(는) 심볼 “{symbol}”의 인스턴스로 입체를 만들 수 없습니다. 심볼의 아트를 사용할 수 없습니다 @msg {_1}: the clipping path is too complex to cut the art with {_1}: 클리핑 패스가 너무 복잡하여 아트를 자를 수 없습니다 @@ -10386,6 +10438,20 @@ breakText Glyphs 글리프 @msg A panel is not joined to the rest by a crease. 패널이 어떤 오시선으로도 나머지와 연결되어 있지 않습니다. @msg A fold line is on a non-printing layer. 접는 선이 인쇄되지 않는 레이어에 있습니다. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} 패널: {panels}, 힌지: {hinges}, 오류: {errors}, 경고: {warnings} + Vector Packs 벡터 팩 + Compass Rose 나침반 장미 + Botanical Sprig 식물 가지 + Facet Diamond 패싯 다이아몬드 + Tide Crest 파도 마루 + Leaf Vine 잎 덩굴 + Blossom Chain 꽃사슬 + Pennant Garland 깃발 장식 + Lantern String 등불 줄 + Orbit Lines 궤도 선 + Petal Garland 꽃잎 화환 + Lattice Braid 격자 땋기 + Facet Sweep 면 분할 붓질 + Artistic Brushes 예술 브러시 Paint 페인트 Flat Sweep 평평한 붓질 Dry Drag 마른 붓질 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index a9d7e5802b..9d65ae28f6 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -1376,6 +1376,8 @@ liquify-list-end {0}, {1} {0} en {1} Contextual Task Bar Contextuele taakbalk Pin Bar Position Balkpositie vastzetten Reset Bar Position Balkpositie herstellen + Bar Actions Balkacties + Reset Bar Actions Balkacties herstellen Tools Gereedschappen Toolbars Werkbalken Advanced Geavanceerd @@ -1395,9 +1397,14 @@ liquify-list-end {0}, {1} {0} en {1} {name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2} Wheel View Wielweergave Box View Vakweergave + Show Out-of-Gamut Colors Kleuren buiten gamut tonen Box Channel Kanaal van het vak Color box Kleurvak Color Wheel Options Opties voor kleurenwiel + Show Document Colors Documentkleuren tonen + Document Colors Documentkleuren + Selection Colors Kleuren van de selectie +@plural Used {n} time|Used {n} times {n} keer gebruikt|{n} keer gebruikt Show Harmony Harmonie tonen Harmony Rule Harmonieregel Harmony color Harmoniekleur @@ -2561,6 +2568,10 @@ digits Malayalam Malayalam Rename Preset Voorinstelling hernoemen Save Image Trace Preset Voorinstelling voor afbeeldingtracering opslaan Delete Image Trace Preset Voorinstelling voor afbeeldingtracering verwijderen + Tracing Presets… Traceervoorinstellingen… + Import Image Trace Presets Voorinstellingen voor afbeeldingtracering importeren + Export Image Trace Presets Voorinstellingen voor afbeeldingtracering exporteren + Replace the saved presets that have these names? Opgeslagen voorinstellingen met deze namen vervangen? Method: Methode: Pad Doortrekken Repeats Herhalingen @@ -4640,6 +4651,13 @@ theme Appearance Vormgeving Pen Tool Pen-gereedschap Quick Pen Tool Snelpen-gereedschap Quick Pen Snelpen + Quick Pen Toolbar Snelpen-werkbalk + Continuous Arc Doorlopende boog + Sharp Corner Arc Boog met scherpe hoek + Flip Arc Boog spiegelen + Hide Toolbar Werkbalk verbergen + Pin Toolbar Position Werkbalkpositie vastzetten + Reset Toolbar Position Werkbalkpositie herstellen Picas Pica's Portuguese Portugees Preserve Appearance and Overprints Vormgeving en overprint behouden @@ -4755,6 +4773,11 @@ theme Appearance Vormgeving Edit Arrowheads Pijlpunten bewerken Edit Arrowheads… Pijlpunten bewerken… Reload Arrowheads Pijlpunten opnieuw laden + Bevels Afschuiningen + Edit Bevels Afschuiningen bewerken + Edit Bevels… Afschuiningen bewerken… + {name} (document) {name} (document) + Reload Bevels Afschuiningen opnieuw laden Stroke Options Lijnopties Width Profiles Breedteprofielen Apply Graphic Style Grafische stijl toepassen @@ -4974,6 +4997,11 @@ axis Both Beide Image Afbeelding Ink Inkt Lab Lab + OKLCH Sliders OKLCH-schuifregelaars + HSL Sliders HSL-schuifregelaars + Chroma Chroma + The largest chroma sRGB holds at this lightness and hue De grootste chroma die sRGB bij deze helderheid en tint bevat + OKLCH needs sRGB as the working RGB space OKLCH vereist sRGB als werk-RGB-ruimte Medium Gemiddeld Name Naam None Geen @@ -5065,6 +5093,7 @@ font-technology Variable Variabel Recent Commands Recente opdrachten No recent commands Geen recente opdrachten Type to search commands, tools, panels and effects Typ om opdrachten, gereedschappen, panelen en effecten te zoeken + Clear Recent Commands Recente opdrachten wissen Dashed Line Streepjeslijn Panel menu Paneelmenu Unembed… Insluiten ongedaan maken… @@ -5184,9 +5213,14 @@ font-technology Variable Variabel Edit type set in fonts that aren't available? Tekst in lettertypen bewerken die niet beschikbaar zijn? Shows each slice's number in a box at its top left on the canvas; off, the slice outlines still show. Toont op het canvas het nummer van elke slice in een vakje linksboven in de slice; staat dit uit, dan blijven de omtrekken van de slices zichtbaar. The color of user and object slice outlines and their number boxes; auto slices use a dimmer shade of it. De kleur van de omtrekken van gebruikers- en objectslices en van hun nummervakjes; automatische slices gebruiken een vagere tint ervan. + New type takes this language while Document Setup's language is English: USA and [Normal Character Style] sets none; type already in a document keeps its own language. Nieuwe tekst krijgt deze taal zolang de taal in Documentinstellingen Engels: VS is en [Normale tekenstijl] geen taal instelt; tekst die al in een document staat, behoudt zijn eigen taal. + In paragraphs with Hyphenate on, a listed word is hyphenated only at the hyphens typed in it, or never when it has none, whatever its language or case. In alinea's met Afbreken aan krijgt een opgesomd woord alleen een afbreekstreepje bij de koppeltekens die erin getypt zijn, of nooit als het er geen heeft, ongeacht taal of hoofdletters. + On the desktop, this folder's .wasm plug-ins load at startup and when OK sets a new folder, except in Safe Mode; one that asks for permissions loads only after you grant them. The web version loads none. In de desktopversie worden de .wasm-plug-ins in deze map geladen bij het starten en wanneer OK een nieuwe map instelt, behalve in de veilige modus; een plug-in die om machtigingen vraagt, laadt pas nadat u ze hebt verleend. De webversie laadt er geen. + Large gives each filter or command plug-in run at least 250 million instructions, with the same time limit; Normal keeps the plug-in's own budget. Live effects, exporters and importers keep theirs. Groot geeft elke uitvoering van een filter- of opdrachtplug-in minstens 250 miljoen instructies, met dezelfde tijdslimiet; Normaal houdt het eigen budget van de plug-in. Live-effecten, exporteurs en importeurs houden het hunne. New type takes this language while Document Setup's language is English: USA; type already in a document keeps its own language. Nieuwe tekst krijgt deze taal zolang de taal in Documentinstellingen Engels: VS is; tekst die al in een document staat, behoudt zijn eigen taal. In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its language or case. In alinea's met Afbreken aan wordt een opgesomd woord alleen afgebroken bij de koppeltekens die erin getypt zijn, of nergens als het er geen heeft, ongeacht taal of hoofdletters. On the desktop, the .wasm plug-ins in this folder load at startup and when you click OK with a new folder here, except in Safe Mode; the web version does not load them. In de desktopversie worden de .wasm-plug-ins in deze map geladen bij het starten en wanneer u hier met een nieuwe map op OK klikt, behalve in de veilige modus; de webversie laadt ze niet. + Normal keeps each plug-in's own limits; with Large, a plug-in filter or command may run at least 250 million instructions besides those for its input. The time limit stays the same. Normaal behoudt de eigen limieten van elke plug-in; met Groot mag een filter of opdracht van een plug-in ten minste 250 miljoen instructies uitvoeren naast die voor de invoer. De tijdslimiet blijft gelijk. How many instructions each run of a plug-in object filter may use; Large allows more than Normal with the same 60-second limit. Heavy filters keep their own budget. Hoeveel instructies elke uitvoering van een objectfilter uit een plug-in mag gebruiken; Groot staat er meer toe dan Normaal, met dezelfde limiet van 60 seconden. Zware filters houden hun eigen budget. The first scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. De eerste keuze voor de scratchschijf: Startup, None of een mappad; VectorCraft slaat deze op, maar gebruikt nog geen scratchschijven. The second scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. De tweede keuze voor de scratchschijf: Startup, None of een mappad; VectorCraft slaat deze op, maar gebruikt nog geen scratchschijven. @@ -5198,13 +5232,15 @@ font-technology Variable Variabel Shows each tool group's name above its tools in the toolbar; off, the groups follow one another with nothing between them. Toont de naam van elke gereedschapgroep boven de gereedschappen in de werkbalk; uit volgen de groepen elkaar op zonder iets ertussen. From now on, documents you open or create open as tabs; off, each opens in a floating window. Documents already open stay where they are. Voortaan openen documenten die u opent of maakt als tabbladen; uit opent elk in een zwevend venster. Documenten die al open zijn, blijven waar ze zijn. Makes the document tabs taller and their names larger. Maakt de tabbladen van documenten hoger en hun namen groter. - From the next start, the system draws the window's title bar where VectorCraft would otherwise draw its own. Vanaf de volgende start tekent het systeem de titelbalk van het venster waar VectorCraft anders zijn eigen zou tekenen. - From the next start, VectorCraft draws the window's title bar even where the desktop would draw it, unless System Title Bar is on. Vanaf de volgende start tekent VectorCraft de titelbalk van het venster ook waar het bureaublad die zou tekenen, tenzij Systeemtitelbalk aan staat. + From the next start, the system draws the window's title bar where VectorCraft would otherwise draw its own; on Linux and the BSDs, the VECTORCRAFT_TITLEBAR variable takes precedence. Vanaf de volgende start tekent het systeem de titelbalk van het venster waar VectorCraft anders zijn eigen zou tekenen; op Linux en de BSD's gaat de variabele VECTORCRAFT_TITLEBAR voor. + From the next start, VectorCraft draws the window's title bar even where the desktop would draw it, unless System Title Bar is on or the VECTORCRAFT_TITLEBAR variable chooses it. Vanaf de volgende start tekent VectorCraft de titelbalk van het venster ook waar het bureaublad die zou tekenen, tenzij Systeemtitelbalk aan staat of de variabele VECTORCRAFT_TITLEBAR die kiest. Makes the interface larger or smaller; art on the canvas keeps its size at the same zoom. Maakt de gebruikersinterface groter of kleiner; illustraties op het canvas houden bij dezelfde zoom hun grootte. The tool pointers VectorCraft draws grow and shrink with UI Scaling; off, they keep their size. De gereedschapsaanwijzers die VectorCraft tekent, groeien en krimpen mee met UI-schaling; uit houden ze hun grootte. The language of the interface; Auto uses the system's language. The dialog switches language as soon as you choose one. De taal van de gebruikersinterface; Automatisch gebruikt de taal van het systeem. Het dialoogvenster wisselt van taal zodra u er een kiest. Animated Zoom works only while this is on; off, Animated Zoom is dimmed and zooming does not animate. Geanimeerd zoomen werkt alleen zolang dit aan staat; uit is Geanimeerd zoomen gedimd en wordt zoomen niet geanimeerd. The wheel's zoom glides in, and the Zoom tool zooms as you drag sideways or hold it down; off, the Zoom tool zooms to the area you drag across. Zoomen met het wieltje glijdt soepel, en het Zoom-gereedschap zoomt terwijl u opzij sleept of het ingedrukt houdt; uit zoomt het Zoom-gereedschap in op het gebied waarover u sleept. + From the next start, the desktop version shows the canvas through this kind of graphics processor; the artwork is drawn on the CPU either way. Automatic prefers the integrated one on Windows and macOS. The web version does not use it. Vanaf de volgende start toont de desktopversie het canvas via dit soort grafische processor; de illustratie wordt hoe dan ook op de CPU getekend. Automatisch kiest op Windows en macOS bij voorkeur de geïntegreerde. De webversie gebruikt het niet. + From the next start, the window shows each frame without waiting for the display's refresh where the graphics driver allows, at most 240 frames a second. Vanaf de volgende start toont het venster elk beeld zonder op de verversing van het beeldscherm te wachten, waar het grafische stuurprogramma dat toestaat, met hoogstens 240 beelden per seconde. From the next start, the desktop version draws with this kind of graphics processor; Automatic prefers the one that drives the display. The web version does not use it. Vanaf de volgende start tekent de desktopversie met dit soort grafische processor; Automatisch kiest bij voorkeur de processor die het beeldscherm aanstuurt. De webversie gebruikt het niet. From the next start, the window shows frames without waiting for the display to refresh, at most 240 a second; off, the display paces them. A present mode set at launch overrides it. Vanaf de volgende start toont het venster beelden zonder op de verversing van het beeldscherm te wachten, hoogstens 240 per seconde; uit bepaalt het beeldscherm het tempo. Een presentatiemodus die bij het starten is ingesteld, gaat voor. The most undo steps each document keeps; lowering it drops the oldest steps when you click OK. Steps can also go sooner when they use too much memory. Het grootste aantal ongedaanmaakstappen dat elk document bewaart; een lager getal verwijdert de oudste stappen wanneer u op OK klikt. Stappen kunnen ook eerder verdwijnen als ze te veel geheugen gebruiken. @@ -5223,6 +5259,9 @@ font-technology Variable Variabel Open Recent Files and the Home screen list at most this many recent files; 0 lists none, and VectorCraft still remembers up to 30. Recente bestanden openen en het Home-scherm tonen hoogstens zoveel recente bestanden; 0 toont er geen, en VectorCraft onthoudt er nog steeds tot 30. When a document opens, a linked EPS image that shows its saved preview keeps it instead of reading the EPS file again; changed files still follow Update Links. Bij het openen van een document houdt een gekoppelde EPS-afbeelding die haar opgeslagen voorvertoning toont die vast, in plaats van het EPS-bestand opnieuw te lezen; gewijzigde bestanden volgen nog steeds Koppelingen bijwerken. In Pixel Preview, images are drawn smoothed; off, their pixels show with hard edges. Outside Pixel Preview, images are always smoothed. In Pixelvoorbeeld worden afbeeldingen vloeiend getekend; uit tonen hun pixels harde randen. Buiten Pixelvoorbeeld worden afbeeldingen altijd vloeiend getekend. + PDF Text PDF-tekst + The text of a PDF you open or embed comes in as editable type, or as outlines that look the same on a computer without its fonts. De tekst van een PDF die u opent of insluit, komt binnen als bewerkbare tekst of als omlijningen die er op een computer zonder de lettertypen ervan hetzelfde uitzien. + Linked pages show the file's own text. Gekoppelde pagina's tonen de eigen tekst van het bestand. When a linked file changes, Automatically reads it again, Ask When Modified asks you first, and Manually leaves it and shows a note in the status bar. Als een gekoppeld bestand verandert, leest Automatisch het opnieuw, vraagt Vragen bij wijziging het u eerst, en laat Handmatig het zoals het is met een melding in de statusbalk. On the desktop, the folder New from Template… and Save as Template… start in; leave it blank for VectorCraft Templates in your documents folder. In de desktopversie de map waarin Nieuw van sjabloon… en Opslaan als sjabloon… beginnen; laat leeg voor VectorCraft Templates in uw documentenmap. Edit Original opens a linked file in the system's default app for its type; off, a linked raster image opens in PhotoCraft where it is installed. Origineel bewerken opent een gekoppeld bestand in de standaardapp van het systeem voor dat type; uit opent een gekoppelde rasterafbeelding in PhotoCraft als dat geïnstalleerd is. @@ -5237,7 +5276,6 @@ font-technology Variable Variabel Output All Blacks as Rich Black draws pure CMYK black as RGB black in RGB and grayscale raster exports and Print as Bitmap; it does not change vector exports, CMYK JPEG, TIFF and PSD, or other printing. Alle zwarttinten uitvoeren als rijk zwart tekent zuiver CMYK-zwart als RGB-zwart in RGB- en grijswaarden-rasterexports en met Afdrukken als bitmap; het verandert niets aan vectorexports, CMYK-JPEG, -TIFF en -PSD of ander afdrukken. On a touch screen, switches to the Touch workspace; turning this off, or losing the touch screen, goes back to the workspace it switched from. Op een aanraakscherm wordt naar de Touch-werkruimte gewisseld; uitschakelen of het wegvallen van het aanraakscherm zet de werkruimte van daarvoor terug. A two-finger tap on the canvas undoes, or switches between selection and drawing tools in the Touch workspace, and a three-finger tap redoes; neither works in Presentation Mode. Tikken met twee vingers op het canvas maakt ongedaan of wisselt in de Touch-werkruimte tussen selectie- en tekengereedschap, en tikken met drie vingers voert opnieuw uit; geen van beide werkt in de presentatiemodus. - New type takes this language while Document Setup's language is English: USA and [Normal Character Style] sets none; type already in a document keeps its own language. Nieuwe tekst krijgt deze taal zolang de taal in Documentinstellingen Engels: VS is en [Normale tekenstijl] geen taal instelt; tekst die al in een document staat, behoudt zijn eigen taal. In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its case; Korean words take no hyphen, and Indian-language words do not break inside a character cluster. In alinea's met Afbreken aan wordt een opgesomd woord alleen afgebroken bij de koppeltekens die erin getypt zijn, of nergens als het er geen heeft, ongeacht hoofdletters; Koreaanse woorden krijgen geen afbreekstreepje, en woorden in Indiase talen worden niet binnen een tekengroep afgebroken. Reset all preferences to their defaults? Alle voorkeuren terugzetten naar de standaardwaarden? The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. De standaardwaarden worden toegepast wanneer u in Voorkeuren op OK klikt. Annuleren daar behoudt uw huidige voorkeuren. @@ -5260,6 +5298,10 @@ font-technology Variable Variabel Cusp Keerpunt Straight segment Recht segment Circle too large Cirkel te groot + Show Radii Stralen tonen + Show Diameter Diameter tonen + Anchors at Standard Positions Ankerpunten op standaardposities + Third Point by Dragging Derde punt door slepen Clip to Art Clippen op artwork Colorize Inkleuren Gamma Gamma @@ -5953,6 +5995,10 @@ imageTrace Outline Contour @msg this trace would make more than {max} anchor points, more than the document can show smoothly: raise Noise, lower Paths or Colors, or pick a lower-fidelity preset deze tracering zou meer dan {max} ankerpunten opleveren, meer dan het document vloeiend kan tonen: verhoog Ruis, verlaag Paden of Kleuren, of kies een voorinstelling met een lagere getrouwheid @msg select an envelope selecteer een omvorming @msg select an image selecteer een afbeelding +@msg object {_1} is an image changed by Perspective Distort or Free Distort, which this command does not work on object {_1} is een afbeelding die met Perspectief vervormen of Vrij vervormen is gewijzigd, en deze opdracht werkt daar niet op +@msg image {_1} cannot be distorted this way: its corners would not make a convex shape afbeelding {_1} kan niet zo worden vervormd: de hoeken zouden geen convexe vorm maken +@msg image {_1} cannot be distorted this way: its corners would cross the warp's horizon afbeelding {_1} kan niet zo worden vervormd: de hoeken zouden de horizon van de vervorming overschrijden +@msg image {_1} cannot be distorted this way: its corners would be too close together for a perspective map afbeelding {_1} kan niet zo worden vervormd: de hoeken zouden te dicht bij elkaar liggen voor een perspectivische afbeelding @msg select an object in perspective selecteer een object in perspectief @msg select artwork (or a colour group) to recolor selecteer een illustratie (of een kleurgroep) om te herkleuren @msg select at least two objects selecteer minstens twee objecten @@ -8580,7 +8626,10 @@ mark-style Japanese Japans @msg the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate) het object heeft geen 3D-effect (Extruderen en afschuinen, Draaien, Opblazen of Roteren) @msg `render` must be an object holding only `mode`, set to shaded or wireframe `render` moet een object zijn met alleen `mode`, ingesteld op shaded of wireframe @msg its 3D effect builds no solid het 3D-effect ervan maakt geen massief object -@msg bevel must be none or one of {_1} bevel moet none of een van {_1} zijn +@msg bevel must be none or one of {_1}, or custom with {BEVEL_PROFILE} bevel moet none, een van {_1} of custom met {BEVEL_PROFILE} zijn +@msg bevel custom needs {BEVEL_PROFILE}, the bevel's points bevel custom heeft {BEVEL_PROFILE} nodig, de punten van de afschuining +@msg {BEVEL_NAME} must be a string {BEVEL_NAME} moet een tekenreeks zijn +@msg {BEVEL_PROFILE} must be 2 to {most} [x, y] points, each share between 0 and 1, from [0, 0] (the cap's edge) to [1, 1] (the side wall) {BEVEL_PROFILE} moet 2 tot {most} punten [x, y] bevatten, elk aandeel tussen 0 en 1, van [0, 0] (de rand van de bovenkant) tot [1, 1] (de zijwand) @msg {_1} can't build solids from this art: its symbol instances, blends and clipping groups hold too many objects {_1} kan van deze illustratie geen massieve objecten maken: de symboolinstanties, vermengingen en knipgroepen ervan bevatten te veel objecten @msg {label} can't build a solid from the instance of symbol "{symbol}": the symbol's art isn't available {label} kan geen massief object maken van de instantie van symbool "{symbol}": de illustratie van het symbool is niet beschikbaar @msg {_1}: the clipping path is too complex to cut the art with {_1}: het knippad is te complex om de illustratie mee uit te knippen @@ -8892,6 +8941,8 @@ mark-style Japanese Japans @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` moet grayscale, rgb, hsb, cmyk of websafe zijn @msg `view` must be wheel or box `view` moet wheel of box zijn @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` moet hue, saturation, brightness, red, green of blue zijn +@msg `sliders` must be none, oklch or hsl `sliders` moet none, oklch of hsl zijn +@msg OKLCH needs sRGB as the working RGB space OKLCH vereist sRGB als werk-RGB-ruimte @msg the Color Picker is not open de kleurenkiezer is niet open @msg the screen color sampler is already open de schermkleurkiezer is al open @msg this system has no screen color sampler dit systeem heeft geen schermkleurkiezer @@ -10787,6 +10838,20 @@ breakText Glyphs Glyphs @msg A panel is not joined to the rest by a crease. Een paneel is door geen rillijn met de rest verbonden. @msg A fold line is on a non-printing layer. Een vouwlijn staat op een laag die niet wordt afgedrukt. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Panelen: {panels}, scharnieren: {hinges}, fouten: {errors}, waarschuwingen: {warnings} + Vector Packs Vectorpakketten + Compass Rose Kompasroos + Botanical Sprig Botanisch takje + Facet Diamond Gefacetteerde diamant + Tide Crest Golfkam + Leaf Vine Bladrank + Blossom Chain Bloemenketting + Pennant Garland Vlaggetjesslinger + Lantern String Lantaarnslinger + Orbit Lines Baanlijnen + Petal Garland Bloemblaadjesslinger + Lattice Braid Rastervlecht + Facet Sweep Gefacetteerde streek + Artistic Brushes Artistieke penselen Paint Verf Flat Sweep Vlakke streek Dry Drag Droge sleep diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 400f0374a2..aaaff09fdf 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -758,6 +758,8 @@ Contextual Task Bar Kontekstowy pasek zadań Pin Bar Position Przypnij położenie paska Reset Bar Position Resetuj położenie paska + Bar Actions Akcje paska + Reset Bar Actions Resetuj akcje paska Resize Zmień rozmiar Tools Narzędzia Toolbars Paski narzędzi @@ -778,9 +780,14 @@ {name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2} Wheel View Widok koła Box View Widok kwadratu + Show Out-of-Gamut Colors Pokaż kolory poza gamutem Box Channel Kanał kwadratu Color box Kwadrat koloru Color Wheel Options Opcje koła kolorów + Show Document Colors Pokaż kolory dokumentu + Document Colors Kolory dokumentu + Selection Colors Kolory zaznaczenia +@plural Used {n} time|Used {n} times Użyty {n} raz|Użyty {n} razy|Użyty {n} razy Show Harmony Pokaż harmonię Harmony Rule Reguła harmonii Harmony color Kolor harmonii @@ -2041,6 +2048,10 @@ digits Malayalam Malajalam Rename Preset Zmień nazwę ustawienia Save Image Trace Preset Zapisz ustawienie obrysu obrazu Delete Image Trace Preset Usuń ustawienie obrysu obrazu + Tracing Presets… Ustawienia obrysu… + Import Image Trace Presets Importuj ustawienia obrysu obrazu + Export Image Trace Presets Eksportuj ustawienia obrysu obrazu + Replace the saved presets that have these names? Zastąpić zapisane ustawienia o tych nazwach? Method: Metoda: Pad Przedłuż Repeats Liczba powtórzeń @@ -4180,6 +4191,13 @@ theme Appearance Wygląd Pen Tool Narzędzie Pióro Quick Pen Tool Narzędzie Szybkie pióro Quick Pen Szybkie pióro + Quick Pen Toolbar Pasek narzędzi szybkiego pióra + Continuous Arc Łuk ciągły + Sharp Corner Arc Łuk z ostrym narożnikiem + Flip Arc Odwróć łuk + Hide Toolbar Ukryj pasek narzędzi + Pin Toolbar Position Przypnij położenie paska narzędzi + Reset Toolbar Position Resetuj położenie paska narzędzi Picas Pica Portuguese Portugalski Preserve Appearance and Overprints Zachowaj wygląd i nadruki @@ -4295,6 +4313,11 @@ theme Appearance Wygląd Edit Arrowheads Edytuj groty strzałek Edit Arrowheads… Edytuj groty strzałek… Reload Arrowheads Wczytaj ponownie groty strzałek + Bevels Fazy + Edit Bevels Edytuj fazy + Edit Bevels… Edytuj fazy… + {name} (document) {name} (dokument) + Reload Bevels Wczytaj ponownie fazy Stroke Options Opcje obrysu Width Profiles Profile szerokości Apply Graphic Style Zastosuj styl graficzny @@ -4501,6 +4524,11 @@ axis Both Obie Image Obraz Ink Farba Lab Lab + OKLCH Sliders Suwaki OKLCH + HSL Sliders Suwaki HSL + Chroma Chroma + The largest chroma sRGB holds at this lightness and hue Największa chroma, jaką sRGB mieści przy tej jasności i barwie + OKLCH needs sRGB as the working RGB space OKLCH wymaga sRGB jako roboczej przestrzeni RGB Medium Średni Name Nazwa None Brak @@ -4594,6 +4622,7 @@ font-technology Variable Zmienne Recent Commands Ostatnie polecenia No recent commands Brak ostatnich poleceń Type to search commands, tools, panels and effects Pisz, aby szukać poleceń, narzędzi, paneli i efektów + Clear Recent Commands Wyczyść listę ostatnich poleceń Dashed Line Linia przerywana Panel menu Menu panelu Unembed… Wyodrębnij… @@ -4714,8 +4743,12 @@ font-technology Variable Zmienne Shows each slice's number in a box at its top left on the canvas; off, the slice outlines still show. Pokazuje na obszarze roboczym numer każdego plasterka w ramce w jego lewym górnym rogu; po wyłączeniu kontury plasterków nadal są widoczne. The color of user and object slice outlines and their number boxes; auto slices use a dimmer shade of it. Kolor konturów plasterków użytkownika i obiektów oraz ramek z ich numerami; plasterki automatyczne używają bledszego odcienia tego koloru. New type takes this language while Document Setup's language is English: USA; type already in a document keeps its own language. Nowy tekst otrzymuje ten język, dopóki językiem w Ustawieniach dokumentu jest Angielski: USA; tekst, który już jest w dokumencie, zachowuje swój język. + In paragraphs with Hyphenate on, a listed word is hyphenated only at the hyphens typed in it, or never when it has none, whatever its language or case. W akapitach z włączoną opcją Dziel wyrazy wyraz z listy dostaje dywiz przeniesienia tylko w miejscach wpisanych w nim łączników albo nigdy, jeśli ich nie ma, bez względu na język i wielkość liter. + On the desktop, this folder's .wasm plug-ins load at startup and when OK sets a new folder, except in Safe Mode; one that asks for permissions loads only after you grant them. The web version loads none. W wersji na komputer wtyczki .wasm z tego folderu są wczytywane przy uruchomieniu i gdy OK ustawi nowy folder, z wyjątkiem trybu awaryjnego; wtyczka, która prosi o uprawnienia, wczytuje się dopiero po ich przyznaniu. Wersja internetowa nie wczytuje żadnej. + Large gives each filter or command plug-in run at least 250 million instructions, with the same time limit; Normal keeps the plug-in's own budget. Live effects, exporters and importers keep theirs. Duże daje każdemu uruchomieniu wtyczki filtra lub polecenia co najmniej 250 milionów instrukcji przy tym samym limicie czasu; Normalny zachowuje własny budżet wtyczki. Efekty na żywo, eksportery i importery zachowują swój. In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its language or case. W akapitach z włączoną opcją Dziel wyrazy wyraz z listy jest dzielony tylko w miejscach wpisanych w nim łączników albo wcale, jeśli ich nie ma, bez względu na język i wielkość liter. On the desktop, the .wasm plug-ins in this folder load at startup and when you click OK with a new folder here, except in Safe Mode; the web version does not load them. W wersji na komputer wtyczki .wasm z tego folderu są wczytywane przy uruchomieniu i po kliknięciu OK z nowym folderem tutaj, z wyjątkiem trybu awaryjnego; wersja internetowa ich nie wczytuje. + Normal keeps each plug-in's own limits; with Large, a plug-in filter or command may run at least 250 million instructions besides those for its input. The time limit stays the same. Normalny zachowuje własne limity każdej wtyczki; przy ustawieniu Duże filtr lub polecenie wtyczki może wykonać co najmniej 250 milionów instrukcji oprócz tych na swoje dane wejściowe. Limit czasu pozostaje bez zmian. How many instructions each run of a plug-in object filter may use; Large allows more than Normal with the same 60-second limit. Heavy filters keep their own budget. Ile instrukcji może zużyć każde uruchomienie filtra obiektów z wtyczki; Duże pozwala na więcej niż Normalny przy tym samym limicie 60 sekund. Ciężkie filtry zachowują własny budżet. The first scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. Pierwszy wybór dysku roboczego: Startup, None lub ścieżka folderu; VectorCraft go zapisuje, ale jeszcze nie używa dysków roboczych. The second scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. Drugi wybór dysku roboczego: Startup, None lub ścieżka folderu; VectorCraft go zapisuje, ale jeszcze nie używa dysków roboczych. @@ -4728,21 +4761,24 @@ font-technology Variable Zmienne From now on, documents you open or create open as tabs; off, each opens in a floating window. Documents already open stay where they are. Od teraz dokumenty, które otwierasz lub tworzysz, otwierają się jako karty; po wyłączeniu każdy otwiera się w pływającym oknie. Już otwarte dokumenty zostają na swoim miejscu. Makes the document tabs taller and their names larger. Sprawia, że karty dokumentów są wyższe, a ich nazwy większe. From the next start, the system draws the window's title bar where VectorCraft would otherwise draw its own. Od następnego uruchomienia system rysuje pasek tytułu okna tam, gdzie VectorCraft w przeciwnym razie rysowałby własny. - From the next start, VectorCraft draws the window's title bar even where the desktop would draw it, unless System Title Bar is on. Od następnego uruchomienia VectorCraft rysuje pasek tytułu okna nawet tam, gdzie narysowałoby go środowisko pulpitu, chyba że Systemowy pasek tytułu jest włączony. + From the next start, the system draws the window's title bar where VectorCraft would otherwise draw its own; on Linux and the BSDs, the VECTORCRAFT_TITLEBAR variable takes precedence. Od następnego uruchomienia system rysuje pasek tytułu okna tam, gdzie VectorCraft w przeciwnym razie rysowałby własny; w systemach Linux i BSD pierwszeństwo ma zmienna VECTORCRAFT_TITLEBAR. + From the next start, VectorCraft draws the window's title bar even where the desktop would draw it, unless System Title Bar is on or the VECTORCRAFT_TITLEBAR variable chooses it. Od następnego uruchomienia VectorCraft rysuje pasek tytułu okna nawet tam, gdzie narysowałoby go środowisko pulpitu, chyba że Systemowy pasek tytułu jest włączony lub wybiera go zmienna VECTORCRAFT_TITLEBAR. Makes the interface larger or smaller; art on the canvas keeps its size at the same zoom. Powiększa lub pomniejsza interfejs; kompozycja na płótnie zachowuje rozmiar przy tym samym powiększeniu. The tool pointers VectorCraft draws grow and shrink with UI Scaling; off, they keep their size. Wskaźniki narzędzi rysowane przez VectorCraft rosną i maleją wraz ze Skalowaniem interfejsu; po wyłączeniu zachowują swój rozmiar. The language of the interface; Auto uses the system's language. The dialog switches language as soon as you choose one. Język interfejsu; Auto używa języka systemu. Okno dialogowe zmienia język, gdy tylko go wybierzesz. Animated Zoom works only while this is on; off, Animated Zoom is dimmed and zooming does not animate. Animowane powiększanie działa tylko wtedy, gdy to jest włączone; po wyłączeniu Animowane powiększanie jest wyszarzone, a powiększanie nie jest animowane. The wheel's zoom glides in, and the Zoom tool zooms as you drag sideways or hold it down; off, the Zoom tool zooms to the area you drag across. Powiększanie kółkiem przebiega płynnie, a Narzędzie Lupka powiększa, gdy przeciągasz w bok lub je przytrzymujesz; po wyłączeniu Narzędzie Lupka powiększa obszar, przez który przeciągniesz. From the next start, the desktop version draws with this kind of graphics processor; Automatic prefers the one that drives the display. The web version does not use it. Od następnego uruchomienia wersja na komputer rysuje tym rodzajem procesora graficznego; Automatycznie wybiera najpierw ten, który obsługuje ekran. Wersja internetowa go nie używa. + From the next start, the desktop version shows the canvas through this kind of graphics processor; the artwork is drawn on the CPU either way. Automatic prefers the integrated one on Windows and macOS. The web version does not use it. Od następnego uruchomienia wersja na komputer wyświetla obszar roboczy przez ten rodzaj procesora graficznego; kompozycja jest zawsze rysowana na CPU. Automatycznie w systemach Windows i macOS wybiera najpierw zintegrowany. Wersja internetowa go nie używa. + From the next start, the window shows each frame without waiting for the display's refresh where the graphics driver allows, at most 240 frames a second. Od następnego uruchomienia okno wyświetla każdą klatkę bez czekania na odświeżenie ekranu, jeśli pozwala na to sterownik grafiki, najwyżej 240 klatek na sekundę. From the next start, the window shows frames without waiting for the display to refresh, at most 240 a second; off, the display paces them. A present mode set at launch overrides it. Od następnego uruchomienia okno pokazuje klatki bez czekania na odświeżenie ekranu, najwyżej 240 na sekundę; po wyłączeniu tempo wyznacza ekran. Tryb prezentacji ustawiony przy uruchomieniu ma pierwszeństwo. The most undo steps each document keeps; lowering it drops the oldest steps when you click OK. Steps can also go sooner when they use too much memory. Największa liczba kroków cofania, które zachowuje każdy dokument; mniejsza liczba usuwa najstarsze kroki po kliknięciu OK. Kroki mogą też zniknąć wcześniej, gdy zajmują zbyt dużo pamięci. Shows the artwork changing while you drag; off, outlines follow the drag and the artwork changes when you release. A ruler guide always moves as you drag. Pokazuje zmiany kompozycji podczas przeciągania; po wyłączeniu kontury podążają za przeciąganiem, a kompozycja zmienia się po puszczeniu. Linia pomocnicza z linijki zawsze porusza się podczas przeciągania. How many worker threads draw the artwork; -1 uses one fewer than the cores VectorCraft may use, at most 8, and 0 uses none. The web version always uses none. Ile wątków roboczych rysuje kompozycję; -1 używa o jeden mniej niż rdzeni, których VectorCraft może używać, najwyżej 8, a 0 żadnego. Wersja internetowa nigdy żadnego nie używa. From the next start on a Wayland desktop, X11 (XWayland) opens the window through XWayland; the other choices do so only when a pen is attached. Od następnego uruchomienia na pulpicie Wayland X11 (XWayland) otwiera okno przez XWayland; inne wybory robią to tylko wtedy, gdy podłączone jest pióro. + Converts the artwork and artboards on the canvas to the display's color profile where the system does not already do so; off, the canvas is drawn in sRGB. Konwertuje kompozycję i obszary kompozycji na płótnie do profilu kolorów ekranu tam, gdzie system tego jeszcze nie robi; po wyłączeniu płótno jest rysowane w sRGB. From the next start, the desktop version shows frames without waiting for the display's refresh, at most 240 a second; off, the display paces them. Od następnego uruchomienia wersja na komputer wyświetla klatki bez czekania na odświeżenie ekranu, najwyżej 240 na sekundę; po wyłączeniu tempo wyznacza ekran. The larger budget raises each object filter run's base instructions fivefold and keeps the same allowance per input byte; heavy filters, live effects, exporters and importers keep their own limits. Większy budżet pięciokrotnie zwiększa podstawową liczbę instrukcji każdego uruchomienia filtra obiektów i zachowuje ten sam dodatek na bajt danych wejściowych; ciężkie filtry, efekty na żywo, eksportery i importery zachowują własne limity. - Converts the artwork and artboards on the canvas to the display's color profile where the system does not already do so; off, the canvas is drawn in sRGB. Konwertuje kompozycję i obszary kompozycji na płótnie do profilu kolorów ekranu tam, gdzie system tego jeszcze nie robi; po wyłączeniu płótno jest rysowane w sRGB. On the desktop, a save to a file is written in the background while you keep editing; off, you wait until it is written. W wersji na komputer zapis do pliku odbywa się w tle, gdy dalej edytujesz; po wyłączeniu czekasz, aż zostanie zapisany. On the desktop, exports to files and packages are written in the background while you keep editing, except 3D exports; off, you wait for them. W wersji na komputer eksporty do plików i pakiety są zapisywane w tle, gdy dalej edytujesz, z wyjątkiem eksportów 3D; po wyłączeniu na nie czekasz. Every few minutes, keeps a recovery copy of each document with unsaved changes made since its last copy; off, no timed copies are made. Co kilka minut zachowuje kopię odzyskiwania każdego dokumentu z niezapisanymi zmianami od jego ostatniej kopii; po wyłączeniu kopie okresowe nie powstają. @@ -4752,6 +4788,9 @@ font-technology Variable Zmienne Open Recent Files and the Home screen list at most this many recent files; 0 lists none, and VectorCraft still remembers up to 30. Otwórz ostatnie pliki i Strona startowa pokazują najwyżej tyle ostatnich plików; 0 nie pokazuje żadnego, a VectorCraft nadal pamięta do 30. When a document opens, a linked EPS image that shows its saved preview keeps it instead of reading the EPS file again; changed files still follow Update Links. Przy otwieraniu dokumentu połączony obraz EPS, który pokazuje swój zapisany podgląd, zachowuje go zamiast ponownie czytać plik EPS; zmienione pliki nadal podlegają ustawieniu Aktualizuj łącza. In Pixel Preview, images are drawn smoothed; off, their pixels show with hard edges. Outside Pixel Preview, images are always smoothed. W Podglądzie pikseli obrazy są rysowane wygładzone; po wyłączeniu ich piksele mają ostre krawędzie. Poza Podglądem pikseli obrazy są zawsze wygładzane. + PDF Text Tekst PDF + The text of a PDF you open or embed comes in as editable type, or as outlines that look the same on a computer without its fonts. Tekst otwieranego lub osadzanego pliku PDF trafia do dokumentu jako edytowalny tekst albo jako kontury, które wyglądają tak samo na komputerze bez jego czcionek. + Linked pages show the file's own text. Połączone strony pokazują własny tekst pliku. When a linked file changes, Automatically reads it again, Ask When Modified asks you first, and Manually leaves it and shows a note in the status bar. Gdy połączony plik się zmieni, Automatycznie wczytuje go ponownie, Pytaj przy modyfikacji najpierw pyta, a Ręcznie zostawia go bez zmian i pokazuje uwagę na pasku stanu. On the desktop, the folder New from Template… and Save as Template… start in; leave it blank for VectorCraft Templates in your documents folder. W wersji na komputer folder, w którym zaczynają Nowy z szablonu… i Zapisz jako szablon…; zostaw puste, aby użyć VectorCraft Templates w folderze dokumentów. Edit Original opens a linked file in the system's default app for its type; off, a linked raster image opens in PhotoCraft where it is installed. Edytuj oryginał otwiera połączony plik w domyślnej aplikacji systemu dla jego typu; po wyłączeniu połączony obraz rastrowy otwiera się w PhotoCraft, jeśli jest zainstalowany. @@ -4789,6 +4828,11 @@ font-technology Variable Zmienne Cusp Ostrze Straight segment Prosty segment Circle too large Okrąg jest za duży + Show Radii Pokaż promienie + Show Diameter Pokaż średnicę + Anchors at Standard Positions Punkty kontrolne w standardowych położeniach + Third Point by Dragging Trzeci punkt przez przeciągnięcie + Gray Szary Clip to Art Przytnij do kompozycji Colorize Koloruj Gamma Gamma @@ -5313,6 +5357,8 @@ liquify-list-end {0}, {1} {0} i {1} @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` musi mieć wartość grayscale, rgb, hsb, cmyk lub websafe @msg `view` must be wheel or box `view` musi mieć wartość wheel lub box @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` musi mieć wartość hue, saturation, brightness, red, green lub blue +@msg `sliders` must be none, oklch or hsl `sliders` musi mieć wartość none, oklch lub hsl +@msg OKLCH needs sRGB as the working RGB space OKLCH wymaga sRGB jako roboczej przestrzeni RGB @msg `{k}` must be [x, y] `{k}` musi mieć postać [x, y] @msg `{name}` has no options `{name}` nie ma opcji @msg `{name}` is a built-in workspace; choose another name `{name}` to wbudowany obszar roboczy; wybierz inną nazwę @@ -5725,6 +5771,10 @@ liquify-list-end {0}, {1} {0} i {1} @msg this trace would make more than {max} anchor points, more than the document can show smoothly: raise Noise, lower Paths or Colors, or pick a lower-fidelity preset ten obrys utworzyłby ponad {max} punktów kontrolnych, więcej niż dokument może płynnie wyświetlić: zwiększ Szum, zmniejsz Ścieżki lub Kolory albo wybierz ustawienie o niższej wierności @msg select an envelope zaznacz kopertę @msg select an image zaznacz obraz +@msg object {_1} is an image changed by Perspective Distort or Free Distort, which this command does not work on obiekt {_1} to obraz zmieniony przez Zniekształcenie perspektywiczne lub Swobodne zniekształcanie, na którym to polecenie nie działa +@msg image {_1} cannot be distorted this way: its corners would not make a convex shape obrazu {_1} nie można tak zniekształcić: jego narożniki nie utworzyłyby kształtu wypukłego +@msg image {_1} cannot be distorted this way: its corners would cross the warp's horizon obrazu {_1} nie można tak zniekształcić: jego narożniki przekroczyłyby horyzont zniekształcenia +@msg image {_1} cannot be distorted this way: its corners would be too close together for a perspective map obrazu {_1} nie można tak zniekształcić: jego narożniki byłyby zbyt blisko siebie dla odwzorowania perspektywicznego @msg `background` must be edges, corners or colors `background` musi mieć wartość edges, corners lub colors @msg `match` must be distance or channels `match` musi mieć wartość distance lub channels @msg `{key}` must be from 0 to 100 `{key}` musi mieścić się w zakresie od 0 do 100 @@ -6654,7 +6704,10 @@ mark-style Japanese Japońskie @msg the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate) obiekt nie ma efektu 3D (Wyciągnięcie i fazowanie, Obrót, Nadmuchanie ani Obróć) @msg `render` must be an object holding only `mode`, set to shaded or wireframe `render` musi być obiektem zawierającym tylko `mode` o wartości shaded lub wireframe @msg its 3D effect builds no solid jego efekt 3D nie tworzy żadnej bryły -@msg bevel must be none or one of {_1} bevel musi mieć wartość none lub jedną z: {_1} +@msg bevel must be none or one of {_1}, or custom with {BEVEL_PROFILE} bevel musi mieć wartość none, jedną z: {_1}, albo custom z {BEVEL_PROFILE} +@msg bevel custom needs {BEVEL_PROFILE}, the bevel's points bevel custom wymaga {BEVEL_PROFILE}, punktów fazy +@msg {BEVEL_NAME} must be a string {BEVEL_NAME} musi być ciągiem znaków +@msg {BEVEL_PROFILE} must be 2 to {most} [x, y] points, each share between 0 and 1, from [0, 0] (the cap's edge) to [1, 1] (the side wall) {BEVEL_PROFILE} musi zawierać od 2 do {most} punktów [x, y], każdy udział od 0 do 1, od [0, 0] (krawędź ściany czołowej) do [1, 1] (ściana boczna) @msg {_1} can't build solids from this art: its symbol instances, blends and clipping groups hold too many objects {_1} nie może utworzyć brył z tej kompozycji: jej wystąpienia symboli, przejścia i grupy przycinające zawierają zbyt wiele obiektów @msg {label} can't build a solid from the instance of symbol "{symbol}": the symbol's art isn't available {label} nie może utworzyć bryły z wystąpienia symbolu „{symbol}”: kompozycja symbolu jest niedostępna @msg {_1}: the clipping path is too complex to cut the art with {_1}: ścieżka przycinająca jest zbyt złożona, aby przyciąć nią kompozycję @@ -10611,6 +10664,20 @@ breakText Glyphs Glify @msg A panel is not joined to the rest by a crease. Panel nie jest połączony z resztą żadną linią bigowania. @msg A fold line is on a non-printing layer. Linia zgięcia znajduje się na warstwie niedrukowanej. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Panele: {panels}, zawiasy: {hinges}, błędy: {errors}, ostrzeżenia: {warnings} + Vector Packs Pakiety wektorowe + Compass Rose Róża wiatrów + Botanical Sprig Gałązka botaniczna + Facet Diamond Fasetowany diament + Tide Crest Grzbiet fali + Leaf Vine Liściasta winorośl + Blossom Chain Łańcuch kwiatów + Pennant Garland Girlanda proporczyków + Lantern String Łańcuch lampionów + Orbit Lines Linie orbitalne + Petal Garland Girlanda płatków + Lattice Braid Plecionka kratowa + Facet Sweep Fasetowane pociągnięcie + Artistic Brushes Pędzle artystyczne Paint Farba Flat Sweep Płaskie pociągnięcie Dry Drag Suche przeciągnięcie diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 947c56ff9e..0dfd797bee 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -474,6 +474,10 @@ antiAlias Sharp Nítido Cusp Cúspide Straight segment Segmento reto Circle too large Círculo grande demais + Show Radii Mostrar Raios + Show Diameter Mostrar Diâmetro + Anchors at Standard Positions Pontos de Ancoragem em Posições Padrão + Third Point by Dragging Terceiro Ponto Arrastando Clean Up… Limpar… Clear Limpar Clear All Tabs Limpar Todas as Paradas de Tabulação @@ -549,9 +553,14 @@ antiAlias Sharp Nítido {name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2} Wheel View Exibição em Roda Box View Exibição em Caixa + Show Out-of-Gamut Colors Mostrar Cores Fora do Gamut Box Channel Canal da Caixa Color box Caixa de cor Color Wheel Options Opções da Roda de Cores + Show Document Colors Mostrar Cores do Documento + Document Colors Cores do Documento + Selection Colors Cores da Seleção +@plural Used {n} time|Used {n} times Usada {n} vez|Usada {n} vezes Show Harmony Mostrar Harmonia Harmony Rule Regra de Harmonia Harmony color Cor da harmonia @@ -601,6 +610,8 @@ antiAlias Sharp Nítido Contextual Task Bar Barra de Tarefas Contextual Pin Bar Position Fixar Posição da Barra Reset Bar Position Redefinir Posição da Barra + Bar Actions Ações da Barra + Reset Bar Actions Redefinir Ações da Barra Resize Redimensionar Control Controle Convert Converter @@ -2308,6 +2319,13 @@ antiAlias Sharp Nítido Pen Tool Ferramenta Caneta Quick Pen Tool Ferramenta Caneta rápida Quick Pen Caneta rápida + Quick Pen Toolbar Barra de Ferramentas da Caneta rápida + Continuous Arc Arco Contínuo + Sharp Corner Arc Arco de Canto Agudo + Flip Arc Virar Arco + Hide Toolbar Ocultar Barra de Ferramentas + Pin Toolbar Position Fixar Posição da Barra de Ferramentas + Reset Toolbar Position Redefinir Posição da Barra de Ferramentas Pencil Lápis Pencil Tool Ferramenta Lápis Percent: Porcentagem: @@ -2705,6 +2723,11 @@ digits Malayalam Malaiala Edit Arrowheads Editar Pontas de Seta Edit Arrowheads… Editar Pontas de Seta… Reload Arrowheads Recarregar Pontas de Seta + Bevels Chanfros + Edit Bevels Editar Chanfros + Edit Bevels… Editar Chanfros… + {name} (document) {name} (documento) + Reload Bevels Recarregar Chanfros Rotate View Girar Visualização Reset Rotate View Redefinir Visualização Girada Rotate View to Selection Girar Visualização para a Seleção @@ -2841,9 +2864,14 @@ digits Malayalam Malaiala Edit type set in fonts that aren't available? Editar o texto em fontes que não estão disponíveis? Shows each slice's number in a box at its top left on the canvas; off, the slice outlines still show. Mostra na tela o número de cada fatia em uma caixa no canto superior esquerdo dela; quando desativado, os contornos das fatias continuam visíveis. The color of user and object slice outlines and their number boxes; auto slices use a dimmer shade of it. A cor dos contornos das fatias de usuário e de objeto e das caixas com seus números; as fatias automáticas usam um tom mais apagado dessa cor. + In paragraphs with Hyphenate on, a listed word is hyphenated only at the hyphens typed in it, or never when it has none, whatever its language or case. Em parágrafos com Hifenizar ativado, uma palavra da lista recebe hífen de divisão apenas nos hifens digitados nela, ou nunca se não tiver nenhum, qualquer que seja o idioma ou o uso de maiúsculas. + On the desktop, this folder's .wasm plug-ins load at startup and when OK sets a new folder, except in Safe Mode; one that asks for permissions loads only after you grant them. The web version loads none. Na versão para desktop, os plug-ins .wasm desta pasta são carregados ao iniciar e quando OK define uma nova pasta, exceto no Modo de Segurança; um que pede permissões só é carregado depois que você as concede. A versão web não carrega nenhum. + Large gives each filter or command plug-in run at least 250 million instructions, with the same time limit; Normal keeps the plug-in's own budget. Live effects, exporters and importers keep theirs. Grande dá a cada execução de um plug-in de filtro ou de comando pelo menos 250 milhões de instruções, com o mesmo limite de tempo; Normal mantém o orçamento próprio do plug-in. Efeitos dinâmicos, exportadores e importadores mantêm o seu. New type takes this language while Document Setup's language is English: USA; type already in a document keeps its own language. O texto novo recebe este idioma enquanto o idioma da Configuração do Documento for Inglês: EUA; o texto que já está em um documento mantém o próprio idioma. + New type takes this language while Document Setup's language is English: USA and [Normal Character Style] sets none; type already in a document keeps its own language. O texto novo recebe este idioma enquanto o idioma da Configuração do Documento for Inglês: EUA e o [Estilo de Caractere Normal] não definir nenhum; o texto que já está em um documento mantém o próprio idioma. In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its language or case. Em parágrafos com Hifenizar ativado, uma palavra da lista é dividida apenas nos hifens digitados nela, ou em nenhum ponto se não tiver nenhum, qualquer que seja o idioma ou o uso de maiúsculas. On the desktop, the .wasm plug-ins in this folder load at startup and when you click OK with a new folder here, except in Safe Mode; the web version does not load them. Na versão para desktop, os plug-ins .wasm desta pasta são carregados ao iniciar e quando você clica em OK com uma nova pasta aqui, exceto no Modo de Segurança; a versão web não os carrega. + Normal keeps each plug-in's own limits; with Large, a plug-in filter or command may run at least 250 million instructions besides those for its input. The time limit stays the same. Normal mantém os limites próprios de cada plug-in; com Grande, um filtro ou comando de plug-in pode executar pelo menos 250 milhões de instruções além das de sua entrada. O limite de tempo continua o mesmo. How many instructions each run of a plug-in object filter may use; Large allows more than Normal with the same 60-second limit. Heavy filters keep their own budget. Quantas instruções cada execução de um filtro de objetos de um plug-in pode usar; Grande permite mais que Normal com o mesmo limite de 60 segundos. Filtros pesados mantêm seu próprio orçamento. The first scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. A primeira opção de disco de cópia: Startup, None ou o caminho de uma pasta; o VectorCraft a armazena, mas ainda não usa discos de cópia. The second scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. A segunda opção de disco de cópia: Startup, None ou o caminho de uma pasta; o VectorCraft a armazena, mas ainda não usa discos de cópia. @@ -2855,13 +2883,15 @@ digits Malayalam Malaiala Shows each tool group's name above its tools in the toolbar; off, the groups follow one another with nothing between them. Mostra o nome de cada grupo de ferramentas acima das ferramentas dele na barra de ferramentas; desativado, os grupos seguem um após o outro sem nada entre eles. From now on, documents you open or create open as tabs; off, each opens in a floating window. Documents already open stay where they are. De agora em diante, os documentos que você abre ou cria abrem como guias; desativado, cada um abre em uma janela flutuante. Documentos já abertos ficam onde estão. Makes the document tabs taller and their names larger. Deixa as guias dos documentos mais altas e os nomes delas maiores. - From the next start, the system draws the window's title bar where VectorCraft would otherwise draw its own. A partir da próxima inicialização, o sistema desenha a barra de título da janela onde, de outra forma, o VectorCraft desenharia a sua própria. - From the next start, VectorCraft draws the window's title bar even where the desktop would draw it, unless System Title Bar is on. A partir da próxima inicialização, o VectorCraft desenha a barra de título da janela mesmo onde a área de trabalho a desenharia, a menos que Barra de título do sistema esteja ativada. + From the next start, the system draws the window's title bar where VectorCraft would otherwise draw its own; on Linux and the BSDs, the VECTORCRAFT_TITLEBAR variable takes precedence. A partir da próxima inicialização, o sistema desenha a barra de título da janela onde, de outra forma, o VectorCraft desenharia a sua própria; no Linux e nos BSDs, a variável VECTORCRAFT_TITLEBAR tem prioridade. + From the next start, VectorCraft draws the window's title bar even where the desktop would draw it, unless System Title Bar is on or the VECTORCRAFT_TITLEBAR variable chooses it. A partir da próxima inicialização, o VectorCraft desenha a barra de título da janela mesmo onde a área de trabalho a desenharia, a menos que Barra de título do sistema esteja ativada ou a variável VECTORCRAFT_TITLEBAR a escolha. Makes the interface larger or smaller; art on the canvas keeps its size at the same zoom. Aumenta ou diminui a interface; a arte na tela mantém o tamanho com o mesmo zoom. The tool pointers VectorCraft draws grow and shrink with UI Scaling; off, they keep their size. Os ponteiros de ferramenta que o VectorCraft desenha crescem e diminuem com a Escala da Interface; desativado, mantêm o tamanho. The language of the interface; Auto uses the system's language. The dialog switches language as soon as you choose one. O idioma da interface; Automático usa o idioma do sistema. A caixa de diálogo troca de idioma assim que você escolhe um. Animated Zoom works only while this is on; off, Animated Zoom is dimmed and zooming does not animate. O Zoom Animado só funciona enquanto isto está ativado; desativado, o Zoom Animado fica esmaecido e o zoom não é animado. The wheel's zoom glides in, and the Zoom tool zooms as you drag sideways or hold it down; off, the Zoom tool zooms to the area you drag across. O zoom com a roda desliza suavemente, e a Ferramenta Zoom amplia enquanto você arrasta para o lado ou a mantém pressionada; desativado, a Ferramenta Zoom amplia a área que você arrasta. + From the next start, the desktop version shows the canvas through this kind of graphics processor; the artwork is drawn on the CPU either way. Automatic prefers the integrated one on Windows and macOS. The web version does not use it. A partir da próxima inicialização, a versão para desktop mostra a área de desenho por meio deste tipo de processador gráfico; a arte é sempre desenhada na CPU. Automático prefere o integrado no Windows e no macOS. A versão web não o usa. + From the next start, the window shows each frame without waiting for the display's refresh where the graphics driver allows, at most 240 frames a second. A partir da próxima inicialização, a janela mostra cada quadro sem esperar a atualização da tela quando o driver gráfico permite, no máximo 240 quadros por segundo. From the next start, the desktop version draws with this kind of graphics processor; Automatic prefers the one that drives the display. The web version does not use it. A partir da próxima inicialização, a versão para desktop desenha com este tipo de processador gráfico; Automático prefere o que controla a tela. A versão web não o usa. From the next start, the window shows frames without waiting for the display to refresh, at most 240 a second; off, the display paces them. A present mode set at launch overrides it. A partir da próxima inicialização, a janela mostra os quadros sem esperar a tela atualizar, no máximo 240 por segundo; desativado, a tela dita o ritmo. Um modo de apresentação definido na inicialização tem prioridade. The most undo steps each document keeps; lowering it drops the oldest steps when you click OK. Steps can also go sooner when they use too much memory. O número máximo de etapas de desfazer que cada documento guarda; um número menor remove as etapas mais antigas quando você clica em OK. Etapas também podem sair antes quando usam memória demais. @@ -2880,6 +2910,9 @@ digits Malayalam Malaiala Open Recent Files and the Home screen list at most this many recent files; 0 lists none, and VectorCraft still remembers up to 30. Abrir Arquivos Recentes e a tela Início listam no máximo este número de arquivos recentes; 0 não lista nenhum, e o VectorCraft continua lembrando até 30. When a document opens, a linked EPS image that shows its saved preview keeps it instead of reading the EPS file again; changed files still follow Update Links. Ao abrir um documento, uma imagem EPS vinculada que mostra sua visualização salva a mantém em vez de ler o arquivo EPS de novo; arquivos alterados continuam seguindo Atualizar Links. In Pixel Preview, images are drawn smoothed; off, their pixels show with hard edges. Outside Pixel Preview, images are always smoothed. Em Visualização de Pixels, as imagens são desenhadas suavizadas; desativado, seus pixels aparecem com bordas duras. Fora da Visualização de Pixels, as imagens são sempre suavizadas. + PDF Text Texto do PDF + The text of a PDF you open or embed comes in as editable type, or as outlines that look the same on a computer without its fonts. O texto de um PDF que você abre ou incorpora entra como texto editável ou como contornos que aparecem iguais em um computador sem as fontes dele. + Linked pages show the file's own text. Páginas vinculadas mostram o próprio texto do arquivo. When a linked file changes, Automatically reads it again, Ask When Modified asks you first, and Manually leaves it and shows a note in the status bar. Quando um arquivo vinculado muda, Automaticamente o lê de novo, Perguntar Quando Modificado pergunta antes, e Manualmente o deixa como está e mostra um aviso na barra de status. On the desktop, the folder New from Template… and Save as Template… start in; leave it blank for VectorCraft Templates in your documents folder. Na versão para desktop, a pasta em que Novo a partir de Modelo… e Salvar como Modelo… começam; deixe em branco para VectorCraft Templates na sua pasta de documentos. Edit Original opens a linked file in the system's default app for its type; off, a linked raster image opens in PhotoCraft where it is installed. Editar Original abre um arquivo vinculado no app padrão do sistema para seu tipo; desativado, uma imagem raster vinculada abre no PhotoCraft quando ele está instalado. @@ -2894,7 +2927,6 @@ digits Malayalam Malaiala Output All Blacks as Rich Black draws pure CMYK black as RGB black in RGB and grayscale raster exports and Print as Bitmap; it does not change vector exports, CMYK JPEG, TIFF and PSD, or other printing. Gerar Todos os Pretos como Preto Rico desenha o preto CMYK puro como preto RGB nas exportações raster RGB e em escala de cinza e com Imprimir como Bitmap; não altera exportações vetoriais, JPEG, TIFF e PSD CMYK nem outras impressões. On a touch screen, switches to the Touch workspace; turning this off, or losing the touch screen, goes back to the workspace it switched from. Em uma tela sensível ao toque, muda para o espaço de trabalho de toque; desativar a opção ou perder a tela sensível ao toque volta ao espaço de trabalho anterior. A two-finger tap on the canvas undoes, or switches between selection and drawing tools in the Touch workspace, and a three-finger tap redoes; neither works in Presentation Mode. Um toque com dois dedos na tela de desenho desfaz ou, no espaço de trabalho de toque, alterna entre ferramentas de seleção e de desenho, e um toque com três dedos refaz; nenhum funciona no Modo de Apresentação. - New type takes this language while Document Setup's language is English: USA and [Normal Character Style] sets none; type already in a document keeps its own language. O texto novo recebe este idioma enquanto o idioma da Configuração do Documento for Inglês: EUA e o [Estilo de Caractere Normal] não definir nenhum; o texto que já está em um documento mantém o próprio idioma. In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its case; Korean words take no hyphen, and Indian-language words do not break inside a character cluster. Em parágrafos com Hifenizar ativado, uma palavra da lista é dividida apenas nos hifens digitados nela, ou em nenhum ponto se não tiver nenhum, qualquer que seja o uso de maiúsculas; palavras coreanas não recebem hífen, e palavras em línguas indianas não são divididas dentro de um grupo de caracteres. Reset all preferences to their defaults? Redefinir todas as preferências para o padrão? The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. Os padrões são aplicados quando você clica em OK em Preferências. Cancelar ali mantém suas preferências atuais. @@ -3104,6 +3136,7 @@ digits Malayalam Malaiala Recent Commands Comandos recentes No recent commands Nenhum comando recente Type to search commands, tools, panels and effects Digite para pesquisar comandos, ferramentas, painéis e efeitos + Clear Recent Commands Limpar Comandos Recentes Search commands Pesquisar comandos Secondary Secundária Section Symbol Símbolo de Seção @@ -4093,6 +4126,10 @@ font-technology Variable Variáveis Rename Preset Renomear Predefinido Save Image Trace Preset Salvar Predefinido de Rastreamento de Imagem Delete Image Trace Preset Excluir Predefinido de Rastreamento de Imagem + Tracing Presets… Predefinições de vetorização… + Import Image Trace Presets Importar Predefinidos de Rastreamento de Imagem + Export Image Trace Presets Exportar Predefinidos de Rastreamento de Imagem + Replace the saved presets that have these names? Substituir os predefinidos salvos que têm esses nomes? Japanese Japonês Keep a link to an image file instead of only embedding it Manter um link para o arquivo de imagem em vez de apenas incorporá-lo Latin Latim @@ -4866,6 +4903,10 @@ axis Both Ambos @msg this trace would make more than {max} anchor points, more than the document can show smoothly: raise Noise, lower Paths or Colors, or pick a lower-fidelity preset esta vetorização geraria mais de {max} pontos de ancoragem, mais do que o documento consegue exibir com fluidez: aumente Ruído, reduza Traçados ou Cores, ou escolha uma predefinição de menor fidelidade @msg select an envelope selecione um envelope @msg select an image selecione uma imagem +@msg object {_1} is an image changed by Perspective Distort or Free Distort, which this command does not work on o objeto {_1} é uma imagem alterada por Distorção de Perspectiva ou Distorção Livre, com a qual este comando não funciona +@msg image {_1} cannot be distorted this way: its corners would not make a convex shape a imagem {_1} não pode ser distorcida assim: seus cantos não formariam uma forma convexa +@msg image {_1} cannot be distorted this way: its corners would cross the warp's horizon a imagem {_1} não pode ser distorcida assim: seus cantos cruzariam o horizonte da distorção +@msg image {_1} cannot be distorted this way: its corners would be too close together for a perspective map a imagem {_1} não pode ser distorcida assim: seus cantos ficariam próximos demais para um mapeamento em perspectiva @msg `background` must be edges, corners or colors `background` deve ser edges, corners ou colors @msg `match` must be distance or channels `match` deve ser distance ou channels @msg `{key}` must be from 0 to 100 `{key}` deve estar entre 0 e 100 @@ -5718,6 +5759,11 @@ variable-list-end {0}, {1} {0} e {1} @plural agrees with {n} default shortcut|agrees with {n} default shortcuts coincide com {n} atalho padrão|coincide com {n} atalhos padrão @plural {n} part of the file wasn't read|{n} parts of the file weren't read {n} parte do arquivo não foi lida|{n} partes do arquivo não foram lidas Lab Lab + OKLCH Sliders Controles Deslizantes OKLCH + HSL Sliders Controles Deslizantes HSL + Chroma Croma + The largest chroma sRGB holds at this lightness and hue O maior croma que o sRGB comporta nesta luminosidade e neste tom + OKLCH needs sRGB as the working RGB space OKLCH requer sRGB como espaço de trabalho RGB Lab Values Valores Lab Large List View Exibição em Lista Grande Large Thumbnail View Exibição em Miniaturas Grandes @@ -6780,7 +6826,10 @@ mark-style Japanese Japonesas @msg the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate) o objeto não tem efeito 3D (Extrusão e Bisel, Revolver, Inflar ou Girar) @msg `render` must be an object holding only `mode`, set to shaded or wireframe `render` deve ser um objeto que contenha apenas `mode`, com o valor shaded ou wireframe @msg its 3D effect builds no solid seu efeito 3D não constrói nenhum sólido -@msg bevel must be none or one of {_1} bevel deve ser none ou um de {_1} +@msg bevel must be none or one of {_1}, or custom with {BEVEL_PROFILE} bevel deve ser none, um de {_1}, ou custom com {BEVEL_PROFILE} +@msg bevel custom needs {BEVEL_PROFILE}, the bevel's points bevel custom precisa de {BEVEL_PROFILE}, os pontos do chanfro +@msg {BEVEL_NAME} must be a string {BEVEL_NAME} deve ser uma string +@msg {BEVEL_PROFILE} must be 2 to {most} [x, y] points, each share between 0 and 1, from [0, 0] (the cap's edge) to [1, 1] (the side wall) {BEVEL_PROFILE} deve ter de 2 a {most} pontos [x, y], cada proporção entre 0 e 1, de [0, 0] (a borda da tampa) a [1, 1] (a parede lateral) @msg {_1} can't build solids from this art: its symbol instances, blends and clipping groups hold too many objects {_1} não pode construir sólidos a partir desta arte: suas instâncias de símbolo, mesclagens e grupos de recorte contêm objetos demais @msg {label} can't build a solid from the instance of symbol "{symbol}": the symbol's art isn't available {label} não pode construir um sólido a partir da instância do símbolo “{symbol}”: a arte do símbolo não está disponível @msg {_1}: the clipping path is too complex to cut the art with {_1}: o caminho de recorte é complexo demais para recortar a arte @@ -6931,6 +6980,8 @@ mark-style Japanese Japonesas @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` deve ser grayscale, rgb, hsb, cmyk ou websafe @msg `view` must be wheel or box `view` deve ser wheel ou box @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` deve ser hue, saturation, brightness, red, green ou blue +@msg `sliders` must be none, oklch or hsl `sliders` deve ser none, oklch ou hsl +@msg OKLCH needs sRGB as the working RGB space OKLCH requer sRGB como espaço de trabalho RGB @msg the image can't be read as a texture a imagem não pode ser lida como textura # User Interface › Accent Color @@ -10820,6 +10871,20 @@ swatch Yellow Green Verde-amarelado @msg A panel is not joined to the rest by a crease. Um painel não está unido ao restante por nenhuma linha de vinco. @msg A fold line is on a non-printing layer. Uma linha de dobra está em uma camada não imprimível. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Painéis: {panels}, dobradiças: {hinges}, erros: {errors}, avisos: {warnings} + Vector Packs Pacotes vetoriais + Compass Rose Rosa dos ventos + Botanical Sprig Ramo botânico + Facet Diamond Diamante facetado + Tide Crest Crista da onda + Leaf Vine Trepadeira de folhas + Blossom Chain Corrente de flores + Pennant Garland Guirlanda de bandeirolas + Lantern String Cordão de lanternas + Orbit Lines Linhas orbitais + Petal Garland Guirlanda de pétalas + Lattice Braid Trança em grade + Facet Sweep Traço facetado + Artistic Brushes Pincéis artísticos Paint Pintura Flat Sweep Pincelada plana Dry Drag Arrasto seco diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 57134bfcf4..ceb5c16f75 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -505,6 +505,10 @@ font-technology Variable Вариативные Cusp Точка возврата Straight segment Прямой сегмент Circle too large Круг слишком большой + Show Radii Показать радиусы + Show Diameter Показать диаметр + Anchors at Standard Positions Опорные точки в стандартных позициях + Third Point by Dragging Третья точка перетаскиванием Classic Defaults Классические значения по умолчанию Clean Up… Очистить… Clear Очистить @@ -608,9 +612,14 @@ font-technology Variable Вариативные {name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2} Wheel View Вид «Круг» Box View Вид «Квадрат» + Show Out-of-Gamut Colors Показать цвета вне цветового охвата Box Channel Канал квадрата Color box Цветовой квадрат Color Wheel Options Параметры цветового круга + Show Document Colors Показать цвета документа + Document Colors Цвета документа + Selection Colors Цвета выделения +@plural Used {n} time|Used {n} times Используется {n} раз|Используется {n} раза|Используется {n} раз Show Harmony Показать гармонию Harmony Rule Правило гармонии Harmony color Цвет гармонии @@ -654,6 +663,8 @@ font-technology Variable Вариативные Contextual Task Bar Контекстная панель задач Pin Bar Position Закрепить положение панели Reset Bar Position Сбросить положение панели + Bar Actions Действия панели + Reset Bar Actions Сбросить действия панели Resize Изменить размер Contrast Контраст Control Control @@ -1930,6 +1941,10 @@ file-filter Templates Шаблоны Rename Preset Переименовать набор Save Image Trace Preset Сохранить набор трассировки изображения Delete Image Trace Preset Удалить набор трассировки изображения + Tracing Presets… Наборы трассировки… + Import Image Trace Presets Импортировать наборы трассировки изображения + Export Image Trace Presets Экспортировать наборы трассировки изображения + Replace the saved presets that have these names? Заменить сохранённые наборы с этими именами? Image Trace Presets Наборы трассировки изображения Image: Изображение: Images: Изображения: @@ -2064,6 +2079,11 @@ file-filter Templates Шаблоны Knife Нож Knockout Group Группа с вырезанием Lab Lab + OKLCH Sliders Ползунки OKLCH + HSL Sliders Ползунки HSL + Chroma Хрома + The largest chroma sRGB holds at this lightness and hue Наибольшая хрома, которую вмещает sRGB при этой светлоте и оттенке + OKLCH needs sRGB as the working RGB space Для OKLCH рабочим пространством RGB должно быть sRGB Lab Spot Colors: Плашечные цвета Lab: Lab Values Значения Lab Landscape Альбомная @@ -2823,6 +2843,13 @@ file-filter Templates Шаблоны Pen Tool Инструмент «Перо» Quick Pen Tool Инструмент «Быстрое перо» Quick Pen Быстрое перо + Quick Pen Toolbar Панель быстрого пера + Continuous Arc Непрерывная дуга + Sharp Corner Arc Дуга с острым углом + Flip Arc Отразить дугу + Hide Toolbar Скрыть панель инструментов + Pin Toolbar Position Закрепить положение панели инструментов + Reset Toolbar Position Сбросить положение панели инструментов Pencil Карандаш Pencil Tool Инструмент «Карандаш» per slice на фрагмент @@ -3270,6 +3297,11 @@ digits Malayalam Малаялам Edit Arrowheads Редактировать стрелки Edit Arrowheads… Редактировать стрелки… Reload Arrowheads Перезагрузить стрелки + Bevels Фаски + Edit Bevels Редактировать фаски + Edit Bevels… Редактировать фаски… + {name} (document) {name} (документ) + Reload Bevels Перезагрузить фаски Rotate View Повернуть вид Reset Rotate View Сбросить поворот вида Rotate View to Selection Повернуть вид по выделению @@ -3408,9 +3440,13 @@ digits Malayalam Малаялам Edit type set in fonts that aren't available? Редактировать текст, набранный недоступными шрифтами? Shows each slice's number in a box at its top left on the canvas; off, the slice outlines still show. Показывает на холсте номер каждого фрагмента в рамке в его левом верхнем углу; если параметр выключен, контуры фрагментов по-прежнему видны. The color of user and object slice outlines and their number boxes; auto slices use a dimmer shade of it. Цвет контуров пользовательских и объектных фрагментов и рамок с их номерами; автоматические фрагменты используют более бледный оттенок этого цвета. + In paragraphs with Hyphenate on, a listed word is hyphenated only at the hyphens typed in it, or never when it has none, whatever its language or case. В абзацах с включённым параметром «Расставлять переносы» слово из списка получает знак переноса только по введённым в нём дефисам или никогда, если их нет, независимо от языка и регистра. + On the desktop, this folder's .wasm plug-ins load at startup and when OK sets a new folder, except in Safe Mode; one that asks for permissions loads only after you grant them. The web version loads none. В настольной версии модули .wasm из этой папки загружаются при запуске и когда ОК задаёт новую папку, кроме безопасного режима; модуль, запрашивающий разрешения, загружается только после того, как вы их дадите. Веб-версия не загружает ни одного. + Large gives each filter or command plug-in run at least 250 million instructions, with the same time limit; Normal keeps the plug-in's own budget. Live effects, exporters and importers keep theirs. «Большой» даёт каждому запуску модуля фильтра или команды не менее 250 миллионов инструкций при том же лимите времени; «Обычный» сохраняет собственный бюджет модуля. Живые эффекты, экспортёры и импортёры сохраняют свой. New type takes this language while Document Setup's language is English: USA; type already in a document keeps its own language. Новый текст получает этот язык, пока в «Параметрах документа» выбран язык Английский: США; текст, который уже есть в документе, сохраняет свой язык. In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its language or case. В абзацах с включённым параметром «Расставлять переносы» слово из списка переносится только по введённым в нём дефисам или нигде, если их нет, независимо от языка и регистра. On the desktop, the .wasm plug-ins in this folder load at startup and when you click OK with a new folder here, except in Safe Mode; the web version does not load them. В настольной версии модули .wasm из этой папки загружаются при запуске и при нажатии ОК с новой папкой здесь, кроме безопасного режима; веб-версия их не загружает. + Normal keeps each plug-in's own limits; with Large, a plug-in filter or command may run at least 250 million instructions besides those for its input. The time limit stays the same. «Обычный» сохраняет собственные ограничения каждого модуля; с «Большой» фильтр или команда модуля может выполнить не менее 250 миллионов инструкций сверх тех, что нужны для её входных данных. Ограничение по времени не меняется. How many instructions each run of a plug-in object filter may use; Large allows more than Normal with the same 60-second limit. Heavy filters keep their own budget. Сколько инструкций может использовать каждый запуск фильтра объектов из модуля; «Большой» разрешает больше, чем «Обычный», при том же ограничении в 60 секунд. Тяжёлые фильтры сохраняют свой бюджет. The first scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. Первый выбор рабочего диска: Startup, None или путь к папке; VectorCraft сохраняет его, но пока не использует рабочие диски. The second scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. Второй выбор рабочего диска: Startup, None или путь к папке; VectorCraft сохраняет его, но пока не использует рабочие диски. @@ -3422,13 +3458,15 @@ digits Malayalam Малаялам Shows each tool group's name above its tools in the toolbar; off, the groups follow one another with nothing between them. Показывает название каждой группы инструментов над её инструментами на панели инструментов; если выключено, группы идут друг за другом без промежутков. From now on, documents you open or create open as tabs; off, each opens in a floating window. Documents already open stay where they are. Теперь документы, которые вы открываете или создаёте, открываются во вкладках; если выключено, каждый открывается в плавающем окне. Уже открытые документы остаются на месте. Makes the document tabs taller and their names larger. Делает вкладки документов выше, а их названия крупнее. - From the next start, the system draws the window's title bar where VectorCraft would otherwise draw its own. Со следующего запуска система рисует строку заголовка окна там, где иначе VectorCraft рисовал бы свою. - From the next start, VectorCraft draws the window's title bar even where the desktop would draw it, unless System Title Bar is on. Со следующего запуска VectorCraft рисует строку заголовка окна даже там, где её нарисовала бы среда рабочего стола, если не включена «Системная строка заголовка». + From the next start, the system draws the window's title bar where VectorCraft would otherwise draw its own; on Linux and the BSDs, the VECTORCRAFT_TITLEBAR variable takes precedence. Со следующего запуска система рисует строку заголовка окна там, где иначе VectorCraft рисовал бы свою; в Linux и BSD приоритет у переменной VECTORCRAFT_TITLEBAR. + From the next start, VectorCraft draws the window's title bar even where the desktop would draw it, unless System Title Bar is on or the VECTORCRAFT_TITLEBAR variable chooses it. Со следующего запуска VectorCraft рисует строку заголовка окна даже там, где её нарисовала бы среда рабочего стола, если не включена «Системная строка заголовка» и её не выбирает переменная VECTORCRAFT_TITLEBAR. Makes the interface larger or smaller; art on the canvas keeps its size at the same zoom. Увеличивает или уменьшает интерфейс; графика на холсте сохраняет размер при том же масштабе. The tool pointers VectorCraft draws grow and shrink with UI Scaling; off, they keep their size. Указатели инструментов, которые рисует VectorCraft, растут и уменьшаются вместе с «Масштабом интерфейса»; если выключено, сохраняют свой размер. The language of the interface; Auto uses the system's language. The dialog switches language as soon as you choose one. Язык интерфейса; «Авто» использует язык системы. Диалог переключает язык, как только вы выбираете один из них. Animated Zoom works only while this is on; off, Animated Zoom is dimmed and zooming does not animate. Анимированное масштабирование работает, только пока это включено; если выключено, Анимированное масштабирование затенено и масштабирование не анимируется. The wheel's zoom glides in, and the Zoom tool zooms as you drag sideways or hold it down; off, the Zoom tool zooms to the area you drag across. Масштабирование колесом идёт плавно, а Инструмент «Масштаб» масштабирует, пока вы тянете вбок или удерживаете его; если выключено, он масштабирует до области, по которой вы протянули. + From the next start, the desktop version shows the canvas through this kind of graphics processor; the artwork is drawn on the CPU either way. Automatic prefers the integrated one on Windows and macOS. The web version does not use it. Со следующего запуска настольная версия выводит холст через этот тип графического процессора; сама графика всегда рисуется на ЦП. «Автоматически» в Windows и macOS предпочитает встроенный. Веб-версия его не использует. + From the next start, the window shows each frame without waiting for the display's refresh where the graphics driver allows, at most 240 frames a second. Со следующего запуска окно показывает каждый кадр, не дожидаясь обновления дисплея, если графический драйвер это позволяет, не более 240 кадров в секунду. From the next start, the desktop version draws with this kind of graphics processor; Automatic prefers the one that drives the display. The web version does not use it. Со следующего запуска настольная версия рисует этим типом графического процессора; «Автоматически» предпочитает тот, что управляет дисплеем. Веб-версия его не использует. From the next start, the window shows frames without waiting for the display to refresh, at most 240 a second; off, the display paces them. A present mode set at launch overrides it. Со следующего запуска окно показывает кадры, не дожидаясь обновления дисплея, не более 240 в секунду; если выключено, темп задаёт дисплей. Режим вывода, заданный при запуске, имеет приоритет. The most undo steps each document keeps; lowering it drops the oldest steps when you click OK. Steps can also go sooner when they use too much memory. Наибольшее число шагов отмены, которое хранит каждый документ; меньшее число удаляет самые старые шаги при нажатии ОК. Шаги могут уйти и раньше, если занимают слишком много памяти. @@ -3447,6 +3485,9 @@ digits Malayalam Малаялам Open Recent Files and the Home screen list at most this many recent files; 0 lists none, and VectorCraft still remembers up to 30. «Открыть последние файлы» и экран «Домой» показывают не больше стольких последних файлов; 0 не показывает ни одного, а VectorCraft всё равно помнит до 30. When a document opens, a linked EPS image that shows its saved preview keeps it instead of reading the EPS file again; changed files still follow Update Links. При открытии документа связанное изображение EPS, показывающее свой сохранённый просмотр, оставляет его вместо повторного чтения файла EPS; изменённые файлы по-прежнему следуют «Обновить связи». In Pixel Preview, images are drawn smoothed; off, their pixels show with hard edges. Outside Pixel Preview, images are always smoothed. В «Просмотре пикселей» изображения рисуются сглаженными; если выключено, их пиксели видны с резкими краями. Вне «Просмотра пикселей» изображения всегда сглаживаются. + PDF Text Текст PDF + The text of a PDF you open or embed comes in as editable type, or as outlines that look the same on a computer without its fonts. Текст открываемого или встраиваемого PDF поступает как редактируемый текст или как контуры, которые выглядят так же на компьютере без его шрифтов. + Linked pages show the file's own text. Связанные страницы показывают собственный текст файла. When a linked file changes, Automatically reads it again, Ask When Modified asks you first, and Manually leaves it and shows a note in the status bar. Когда связанный файл меняется, «Автоматически» перечитывает его, «Спрашивать при изменении» сначала спрашивает вас, а «Вручную» оставляет его как есть и показывает заметку в строке состояния. On the desktop, the folder New from Template… and Save as Template… start in; leave it blank for VectorCraft Templates in your documents folder. В настольной версии папка, с которой начинают «Создать из шаблона…» и «Сохранить как шаблон…»; оставьте пустой для VectorCraft Templates в вашей папке документов. Edit Original opens a linked file in the system's default app for its type; off, a linked raster image opens in PhotoCraft where it is installed. «Редактировать оригинал» открывает связанный файл в стандартном приложении системы для его типа; если выключено, связанное растровое изображение открывается в PhotoCraft, если он установлен. @@ -3706,6 +3747,7 @@ digits Malayalam Малаялам Recent Commands Недавние команды No recent commands Нет недавних команд Type to search commands, tools, panels and effects Начните вводить для поиска команд, инструментов, панелей и эффектов + Clear Recent Commands Очистить список недавних команд Search commands Поиск команд Search Commands… Поиск команд… Secondary Вторичный @@ -5206,6 +5248,8 @@ liquify-list-end {0}, {1} {0} и {1} @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` должно быть grayscale, rgb, hsb, cmyk или websafe @msg `view` must be wheel or box `view` должно быть wheel или box @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` должно быть hue, saturation, brightness, red, green или blue +@msg `sliders` must be none, oklch or hsl `sliders` должен быть none, oklch или hsl +@msg OKLCH needs sRGB as the working RGB space Для OKLCH рабочим пространством RGB должно быть sRGB @msg `{k}` must be [x, y] `{k}` должно быть [x, y] @msg `{name}` has no options `{name}` не имеет параметров @msg `{name}` is a built-in workspace; choose another name `{name}` — встроенная рабочая среда; выберите другое имя @@ -5618,6 +5662,10 @@ liquify-list-end {0}, {1} {0} и {1} @msg this trace would make more than {max} anchor points, more than the document can show smoothly: raise Noise, lower Paths or Colors, or pick a lower-fidelity preset эта трассировка создала бы более {max} опорных точек, что больше, чем документ может плавно отобразить: увеличьте «Шум», уменьшите «Контуры» или «Цвета» либо выберите набор с меньшей точностью @msg select an envelope выделите оболочку @msg select an image выделите изображение +@msg object {_1} is an image changed by Perspective Distort or Free Distort, which this command does not work on объект {_1} — изображение, изменённое с помощью «Искажение перспективы» или «Свободная деформация», и эта команда с ним не работает +@msg image {_1} cannot be distorted this way: its corners would not make a convex shape изображение {_1} нельзя так деформировать: его углы не образуют выпуклую фигуру +@msg image {_1} cannot be distorted this way: its corners would cross the warp's horizon изображение {_1} нельзя так деформировать: его углы пересекут горизонт деформации +@msg image {_1} cannot be distorted this way: its corners would be too close together for a perspective map изображение {_1} нельзя так деформировать: его углы окажутся слишком близко друг к другу для перспективного отображения @msg `background` must be edges, corners or colors `background` должен быть edges, corners или colors @msg `match` must be distance or channels `match` должен быть distance или channels @msg `{key}` must be from 0 to 100 `{key}` должен быть от 0 до 100 @@ -6441,7 +6489,10 @@ lighting Light Свет @msg the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate) у объекта нет 3D-эффекта (Выдавливание и фаска, Вращение, Надувание или Повернуть) @msg `render` must be an object holding only `mode`, set to shaded or wireframe `render` должен быть объектом только с полем `mode` со значением shaded или wireframe @msg its 3D effect builds no solid его 3D-эффект не строит тела -@msg bevel must be none or one of {_1} bevel должен быть none или одним из: {_1} +@msg bevel must be none or one of {_1}, or custom with {BEVEL_PROFILE} bevel должен быть none, одним из: {_1}, или custom с {BEVEL_PROFILE} +@msg bevel custom needs {BEVEL_PROFILE}, the bevel's points для bevel custom нужен {BEVEL_PROFILE}, точки фаски +@msg {BEVEL_NAME} must be a string {BEVEL_NAME} должно быть строкой +@msg {BEVEL_PROFILE} must be 2 to {most} [x, y] points, each share between 0 and 1, from [0, 0] (the cap's edge) to [1, 1] (the side wall) {BEVEL_PROFILE} должен содержать от 2 до {most} точек [x, y], каждая доля от 0 до 1, от [0, 0] (край торца) до [1, 1] (боковая стенка) @msg {_1} can't build solids from this art: its symbol instances, blends and clipping groups hold too many objects {_1}: нельзя построить тела из этой иллюстрации: её экземпляры символов, переходы и обтравочные группы содержат слишком много объектов @msg {label} can't build a solid from the instance of symbol "{symbol}": the symbol's art isn't available {label}: нельзя построить тело из экземпляра символа «{symbol}»: иллюстрация символа недоступна @msg {_1}: the clipping path is too complex to cut the art with {_1}: обтравочный контур слишком сложен, чтобы обрезать им иллюстрацию @@ -10804,6 +10855,20 @@ shape Open Открытый @msg Two panels pass through each other. Две панели проходят друг сквозь друга. @msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h} пикселей — слишком большой размер для PSD (не более {MAX_SIDE} пикселей по стороне): уменьшите разрешение @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer должен быть "singleLine", "everyLine", "standardSingleLine" или "standardEveryLine" + Vector Packs Векторные наборы + Compass Rose Роза ветров + Botanical Sprig Ботаническая ветвь + Facet Diamond Гранёный бриллиант + Tide Crest Гребень волны + Leaf Vine Лиственная лоза + Blossom Chain Цветочная цепочка + Pennant Garland Гирлянда флажков + Lantern String Цепочка фонариков + Orbit Lines Орбитальные линии + Petal Garland Гирлянда лепестков + Lattice Braid Решётчатое плетение + Facet Sweep Гранёный мазок + Artistic Brushes Художественные кисти Paint Краска Flat Sweep Плоский мазок Dry Drag Сухой протяг diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 5243e387f7..40402919e7 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -496,6 +496,10 @@ font-technology Variable Variabla Cusp Spets Straight segment Rakt segment Circle too large Cirkeln är för stor + Show Radii Visa radier + Show Diameter Visa diameter + Anchors at Standard Positions Ankarpunkter på standardpositioner + Third Point by Dragging Tredje punkt genom att dra Classic Defaults Klassiska standardvärden Clean Up… Rensa upp… Clear Rensa @@ -593,9 +597,14 @@ font-technology Variable Variabla {name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2} Wheel View Hjulvy Box View Rutvy + Show Out-of-Gamut Colors Visa färger utanför färgomfånget Box Channel Rutans kanal Color box Färgruta Color Wheel Options Alternativ för färghjulet + Show Document Colors Visa dokumentfärger + Document Colors Dokumentfärger + Selection Colors Markeringens färger +@plural Used {n} time|Used {n} times Används {n} gång|Används {n} gånger Show Harmony Visa harmoni Harmony Rule Harmoniregel Harmony color Harmonifärg @@ -639,6 +648,8 @@ font-technology Variable Variabla Contextual Task Bar Kontextuellt aktivitetsfält Pin Bar Position Fäst fältets position Reset Bar Position Återställ fältets position + Bar Actions Fältets åtgärder + Reset Bar Actions Återställ fältets åtgärder Resize Ändra storlek Contrast Kontrast Control Kontroll @@ -1852,6 +1863,10 @@ font-technology Variable Variabla Rename Preset Byt namn på förinställning Save Image Trace Preset Spara förinställning för bildkalkering Delete Image Trace Preset Radera förinställning för bildkalkering + Tracing Presets… Förinställningar för vektorisering… + Import Image Trace Presets Importera förinställningar för bildkalkering + Export Image Trace Presets Exportera förinställningar för bildkalkering + Replace the saved presets that have these names? Ersätta sparade förinställningar med dessa namn? Image Trace Presets Förinställningar för bildkalkering Image: Bild: Images: Bilder: @@ -1980,6 +1995,11 @@ font-technology Variable Variabla Knife Kniv Knockout Group Utsparningsgrupp Lab Lab + OKLCH Sliders OKLCH-reglage + HSL Sliders HSL-reglage + Chroma Kroma + The largest chroma sRGB holds at this lightness and hue Den största kroma som sRGB rymmer vid denna ljushet och nyans + OKLCH needs sRGB as the working RGB space OKLCH kräver sRGB som RGB-arbetsfärgrymd Lab Spot Colors: Lab-dekorfärger: Lab Values Lab-värden Landscape Liggande @@ -2718,6 +2738,13 @@ font-technology Variable Variabla Pen Tool Pennverktyg Quick Pen Tool Snabbpennverktyg Quick Pen Snabbpenna + Quick Pen Toolbar Snabbpennans verktygsfält + Continuous Arc Kontinuerlig båge + Sharp Corner Arc Båge med skarpt hörn + Flip Arc Vänd båge + Hide Toolbar Dölj verktygsfältet + Pin Toolbar Position Fäst verktygsfältets position + Reset Toolbar Position Återställ verktygsfältets position Pencil Blyertspenna Pencil Tool Blyertsverktyg per slice per skiva @@ -3160,6 +3187,11 @@ digits Malayalam Malayalam Edit Arrowheads Redigera pilspetsar Edit Arrowheads… Redigera pilspetsar… Reload Arrowheads Läs in pilspetsar igen + Bevels Fasningar + Edit Bevels Redigera fasningar + Edit Bevels… Redigera fasningar… + {name} (document) {name} (dokument) + Reload Bevels Läs in fasningar igen Reset Rotate View Återställ Rotera vy Rotate View to Selection Rotera vyn efter markeringen Reset the rows to the artwork's colors Återställ raderna till teckningens färger @@ -3297,9 +3329,14 @@ digits Malayalam Malayalam Edit type set in fonts that aren't available? Redigera text i typsnitt som inte är tillgängliga? Shows each slice's number in a box at its top left on the canvas; off, the slice outlines still show. Visar varje skivas nummer i en ruta i dess övre vänstra hörn på arbetsytan; när det är avstängt visas skivornas konturer fortfarande. The color of user and object slice outlines and their number boxes; auto slices use a dimmer shade of it. Färgen på konturerna för användar- och objektskivor och på deras nummerrutor; automatiska skivor använder en blekare nyans av den. + In paragraphs with Hyphenate on, a listed word is hyphenated only at the hyphens typed in it, or never when it has none, whatever its language or case. I stycken med Avstava på får ett listat ord avstavningsstreck bara vid bindestrecken som skrivits in i det, eller aldrig om det saknar sådana, oavsett språk och skiftläge. + On the desktop, this folder's .wasm plug-ins load at startup and when OK sets a new folder, except in Safe Mode; one that asks for permissions loads only after you grant them. The web version loads none. I skrivbordsversionen läses .wasm-plugins i den här mappen in vid start och när OK anger en ny mapp, utom i felsäkert läge; en plugin som begär behörigheter läses in först när du har gett dem. Webbversionen läser inte in någon. + Large gives each filter or command plug-in run at least 250 million instructions, with the same time limit; Normal keeps the plug-in's own budget. Live effects, exporters and importers keep theirs. Stor ger varje körning av en filter- eller kommandoplugin minst 250 miljoner instruktioner med samma tidsgräns; Normal behåller pluginens egen budget. Liveeffekter, exportörer och importörer behåller sin. New type takes this language while Document Setup's language is English: USA; type already in a document keeps its own language. Ny text får det här språket så länge språket i Dokumentinställningar är Engelska: USA; text som redan finns i ett dokument behåller sitt eget språk. + New type takes this language while Document Setup's language is English: USA and [Normal Character Style] sets none; type already in a document keeps its own language. Ny text får det här språket så länge språket i Dokumentinställningar är Engelska: USA och [Normal teckenstil] inte anger något språk; text som redan finns i ett dokument behåller sitt eget språk. In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its language or case. I stycken med Avstava på avstavas ett listat ord bara vid bindestrecken som skrivits in i det, eller inte alls om det saknar sådana, oavsett språk och skiftläge. On the desktop, the .wasm plug-ins in this folder load at startup and when you click OK with a new folder here, except in Safe Mode; the web version does not load them. I skrivbordsversionen läses .wasm-plugins i den här mappen in vid start och när du klickar på OK med en ny mapp här, utom i felsäkert läge; webbversionen läser inte in dem. + Normal keeps each plug-in's own limits; with Large, a plug-in filter or command may run at least 250 million instructions besides those for its input. The time limit stays the same. Normal behåller varje plugins egna gränser; med Stor får ett pluginfilter eller ett pluginkommando köra minst 250 miljoner instruktioner utöver dem för sin indata. Tidsgränsen förblir densamma. How many instructions each run of a plug-in object filter may use; Large allows more than Normal with the same 60-second limit. Heavy filters keep their own budget. Hur många instruktioner varje körning av ett objektfilter från ett plugin får använda; Stor tillåter fler än Normal med samma gräns på 60 sekunder. Tunga filter behåller sin egen budget. The first scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. Det första valet av arbetsdisk: Startup, None eller en mappsökväg; VectorCraft sparar det men använder ännu inte arbetsdiskar. The second scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. Det andra valet av arbetsdisk: Startup, None eller en mappsökväg; VectorCraft sparar det men använder ännu inte arbetsdiskar. @@ -3311,13 +3348,15 @@ digits Malayalam Malayalam Shows each tool group's name above its tools in the toolbar; off, the groups follow one another with nothing between them. Visar varje verktygsgrupps namn ovanför dess verktyg i verktygsfältet; avstängt följer grupperna på varandra utan något emellan. From now on, documents you open or create open as tabs; off, each opens in a floating window. Documents already open stay where they are. Från och med nu öppnas dokument som du öppnar eller skapar som flikar; avstängt öppnas vart och ett i ett flytande fönster. Dokument som redan är öppna stannar där de är. Makes the document tabs taller and their names larger. Gör dokumentflikarna högre och deras namn större. - From the next start, the system draws the window's title bar where VectorCraft would otherwise draw its own. Från nästa start ritar systemet fönstrets namnlist där VectorCraft annars skulle rita sin egen. - From the next start, VectorCraft draws the window's title bar even where the desktop would draw it, unless System Title Bar is on. Från nästa start ritar VectorCraft fönstrets namnlist även där skrivbordsmiljön skulle rita den, om inte Systemets namnlist är på. + From the next start, the system draws the window's title bar where VectorCraft would otherwise draw its own; on Linux and the BSDs, the VECTORCRAFT_TITLEBAR variable takes precedence. Från nästa start ritar systemet fönstrets namnlist där VectorCraft annars skulle rita sin egen; på Linux och BSD-systemen har variabeln VECTORCRAFT_TITLEBAR företräde. + From the next start, VectorCraft draws the window's title bar even where the desktop would draw it, unless System Title Bar is on or the VECTORCRAFT_TITLEBAR variable chooses it. Från nästa start ritar VectorCraft fönstrets namnlist även där skrivbordsmiljön skulle rita den, om inte Systemets namnlist är på eller variabeln VECTORCRAFT_TITLEBAR väljer den. Makes the interface larger or smaller; art on the canvas keeps its size at the same zoom. Gör gränssnittet större eller mindre; bilder på arbetsytan behåller sin storlek vid samma zoom. The tool pointers VectorCraft draws grow and shrink with UI Scaling; off, they keep their size. Verktygspekarna som VectorCraft ritar växer och krymper med Gränssnittsskalning; avstängt behåller de sin storlek. The language of the interface; Auto uses the system's language. The dialog switches language as soon as you choose one. Gränssnittets språk; Auto använder systemets språk. Dialogrutan byter språk så fort du väljer ett. Animated Zoom works only while this is on; off, Animated Zoom is dimmed and zooming does not animate. Animerad zoom fungerar bara medan detta är på; avstängt är Animerad zoom nedtonad och zoomningen animeras inte. The wheel's zoom glides in, and the Zoom tool zooms as you drag sideways or hold it down; off, the Zoom tool zooms to the area you drag across. Zoom med hjulet glider in mjukt, och Zoomverktyget zoomar medan du drar åt sidan eller håller det nedtryckt; avstängt zoomar Zoomverktyget till området du drar över. + From the next start, the desktop version shows the canvas through this kind of graphics processor; the artwork is drawn on the CPU either way. Automatic prefers the integrated one on Windows and macOS. The web version does not use it. Från nästa start visar skrivbordsversionen arbetsytan genom den här typen av grafikprocessor; teckningen ritas alltid på processorn (CPU). Automatisk föredrar den integrerade på Windows och macOS. Webbversionen använder den inte. + From the next start, the window shows each frame without waiting for the display's refresh where the graphics driver allows, at most 240 frames a second. Från nästa start visar fönstret varje bildruta utan att vänta på skärmens uppdatering där grafikdrivrutinen tillåter det, högst 240 bildrutor per sekund. From the next start, the desktop version draws with this kind of graphics processor; Automatic prefers the one that drives the display. The web version does not use it. Från nästa start ritar skrivbordsversionen med den här typen av grafikprocessor; Automatisk föredrar den som driver skärmen. Webbversionen använder den inte. From the next start, the window shows frames without waiting for the display to refresh, at most 240 a second; off, the display paces them. A present mode set at launch overrides it. Från nästa start visar fönstret bildrutor utan att vänta på att skärmen uppdateras, högst 240 per sekund; avstängt styr skärmen takten. Ett presentationsläge som anges vid start går före. The most undo steps each document keeps; lowering it drops the oldest steps when you click OK. Steps can also go sooner when they use too much memory. Det högsta antalet ångra-steg som varje dokument behåller; ett lägre tal tar bort de äldsta stegen när du klickar på OK. Steg kan också försvinna tidigare när de använder för mycket minne. @@ -3336,6 +3375,9 @@ digits Malayalam Malayalam Open Recent Files and the Home screen list at most this many recent files; 0 lists none, and VectorCraft still remembers up to 30. Öppna senaste filer och startskärmen listar högst så här många senaste filer; 0 listar inga, och VectorCraft minns ändå upp till 30. When a document opens, a linked EPS image that shows its saved preview keeps it instead of reading the EPS file again; changed files still follow Update Links. När ett dokument öppnas behåller en länkad EPS-bild som visar sin sparade förhandsvisning den i stället för att läsa EPS-filen igen; ändrade filer följer fortfarande Uppdatera länkar. In Pixel Preview, images are drawn smoothed; off, their pixels show with hard edges. Outside Pixel Preview, images are always smoothed. I Pixelförhandsgranskning ritas bilder utjämnade; avstängt visar deras pixlar skarpa kanter. Utanför Pixelförhandsgranskning utjämnas bilder alltid. + PDF Text PDF-text + The text of a PDF you open or embed comes in as editable type, or as outlines that look the same on a computer without its fonts. Texten i en PDF som du öppnar eller bäddar in kommer in som redigerbar text eller som konturlinjer som ser likadana ut på en dator utan dess teckensnitt. + Linked pages show the file's own text. Länkade sidor visar filens egen text. When a linked file changes, Automatically reads it again, Ask When Modified asks you first, and Manually leaves it and shows a note in the status bar. När en länkad fil ändras läser Automatiskt in den igen, Fråga vid ändring frågar dig först, och Manuellt låter den vara och visar en notis i statusfältet. On the desktop, the folder New from Template… and Save as Template… start in; leave it blank for VectorCraft Templates in your documents folder. I skrivbordsversionen mappen som Ny från mall… och Spara som mall… börjar i; lämna tom för VectorCraft Templates i din dokumentmapp. Edit Original opens a linked file in the system's default app for its type; off, a linked raster image opens in PhotoCraft where it is installed. Redigera original öppnar en länkad fil i systemets standardapp för dess typ; avstängt öppnas en länkad rasterbild i PhotoCraft om det är installerat. @@ -3350,7 +3392,6 @@ digits Malayalam Malayalam Output All Blacks as Rich Black draws pure CMYK black as RGB black in RGB and grayscale raster exports and Print as Bitmap; it does not change vector exports, CMYK JPEG, TIFF and PSD, or other printing. Återge all svart som djupsvart ritar ren CMYK-svart som RGB-svart i RGB- och gråskale-rasterexporter och med Skriv ut som bitmapp; den ändrar inte vektorexporter, CMYK-JPEG, -TIFF och -PSD eller annan utskrift. On a touch screen, switches to the Touch workspace; turning this off, or losing the touch screen, goes back to the workspace it switched from. På en pekskärm växlar detta till arbetslayouten för pekskärm; när inställningen stängs av eller pekskärmen försvinner återgår den till arbetslayouten från före bytet. A two-finger tap on the canvas undoes, or switches between selection and drawing tools in the Touch workspace, and a three-finger tap redoes; neither works in Presentation Mode. Ett tryck med två fingrar på arbetsytan ångrar eller växlar i arbetslayouten för pekskärm mellan markerings- och ritverktyg, och ett tryck med tre fingrar gör om; inget av dem fungerar i presentationsläge. - New type takes this language while Document Setup's language is English: USA and [Normal Character Style] sets none; type already in a document keeps its own language. Ny text får det här språket så länge språket i Dokumentinställningar är Engelska: USA och [Normal teckenstil] inte anger något språk; text som redan finns i ett dokument behåller sitt eget språk. In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its case; Korean words take no hyphen, and Indian-language words do not break inside a character cluster. I stycken med Avstava på avstavas ett listat ord bara vid bindestrecken som skrivits in i det, eller inte alls om det saknar sådana, oavsett skiftläge; koreanska ord får inget avstavningstecken, och ord på indiska språk avstavas inte inuti en teckengrupp. Reset all preferences to their defaults? Återställa alla inställningar till standard? The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. Standardvärdena verkställs när du klickar på OK i Inställningar. Avbryt där behåller dina nuvarande inställningar. @@ -3581,6 +3622,7 @@ digits Malayalam Malayalam Recent Commands Senaste kommandon No recent commands Inga senaste kommandon Type to search commands, tools, panels and effects Skriv för att söka efter kommandon, verktyg, paneler och effekter + Clear Recent Commands Rensa senaste kommandon Search commands Sök kommandon Search Commands… Sök kommandon… Secondary Sekundär @@ -5474,6 +5516,10 @@ liquify-list-end {0}, {1} {0} och {1} @msg this trace would make more than {max} anchor points, more than the document can show smoothly: raise Noise, lower Paths or Colors, or pick a lower-fidelity preset spårningen skulle ge fler än {max} ankarpunkter, fler än dokumentet kan visa smidigt: höj Brus, sänk Banor eller Färger, eller välj en förinställning med lägre återgivning @msg select an envelope markera ett kuvert @msg select an image markera en bild +@msg object {_1} is an image changed by Perspective Distort or Free Distort, which this command does not work on objekt {_1} är en bild som ändrats med Perspektivförvrängning eller Fri förvrängning, och det här kommandot fungerar inte på den +@msg image {_1} cannot be distorted this way: its corners would not make a convex shape bild {_1} kan inte förvrängas så: dess hörn skulle inte bilda en konvex form +@msg image {_1} cannot be distorted this way: its corners would cross the warp's horizon bild {_1} kan inte förvrängas så: dess hörn skulle korsa förvrängningens horisont +@msg image {_1} cannot be distorted this way: its corners would be too close together for a perspective map bild {_1} kan inte förvrängas så: dess hörn skulle ligga för nära varandra för en perspektivavbildning @msg `background` must be edges, corners or colors `background` måste vara edges, corners eller colors @msg `match` must be distance or channels `match` måste vara distance eller channels @msg `{key}` must be from 0 to 100 `{key}` måste vara från 0 till 100 @@ -6310,7 +6356,10 @@ lighting Light Ljus @msg the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate) objektet har ingen 3D-effekt (Extrudera och fasa, Rotera runt axel, Blås upp eller Rotera) @msg `render` must be an object holding only `mode`, set to shaded or wireframe `render` måste vara ett objekt som bara innehåller `mode`, med värdet shaded eller wireframe @msg its 3D effect builds no solid dess 3D-effekt bygger ingen solid -@msg bevel must be none or one of {_1} bevel måste vara none eller något av {_1} +@msg bevel must be none or one of {_1}, or custom with {BEVEL_PROFILE} bevel måste vara none, något av {_1} eller custom med {BEVEL_PROFILE} +@msg bevel custom needs {BEVEL_PROFILE}, the bevel's points bevel custom kräver {BEVEL_PROFILE}, fasningens punkter +@msg {BEVEL_NAME} must be a string {BEVEL_NAME} måste vara en sträng +@msg {BEVEL_PROFILE} must be 2 to {most} [x, y] points, each share between 0 and 1, from [0, 0] (the cap's edge) to [1, 1] (the side wall) {BEVEL_PROFILE} måste vara 2 till {most} punkter [x, y], varje andel mellan 0 och 1, från [0, 0] (ändytans kant) till [1, 1] (sidoväggen) @msg {_1} can't build solids from this art: its symbol instances, blends and clipping groups hold too many objects {_1} kan inte bygga solider av den här teckningen: dess symbolinstanser, blandningar och urklippsgrupper innehåller för många objekt @msg {label} can't build a solid from the instance of symbol "{symbol}": the symbol's art isn't available {label} kan inte bygga en solid av instansen av symbolen ”{symbol}”: symbolens teckning är inte tillgänglig @msg {_1}: the clipping path is too complex to cut the art with {_1}: urklippsbanan är för komplex för att klippa teckningen med @@ -6971,6 +7020,8 @@ theme Appearance Utseende @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` måste vara grayscale, rgb, hsb, cmyk eller websafe @msg `view` must be wheel or box `view` måste vara wheel eller box @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` måste vara hue, saturation, brightness, red, green eller blue +@msg `sliders` must be none, oklch or hsl `sliders` måste vara none, oklch eller hsl +@msg OKLCH needs sRGB as the working RGB space OKLCH kräver sRGB som RGB-arbetsfärgrymd @msg `{key}` must be an array of these names: {_1} `{key}` måste vara en lista med dessa namn: {_1} @msg choose a destination folder välj en målmapp @msg choose a source folder välj en källmapp @@ -10841,6 +10892,20 @@ digits Hindi Hindi @msg A joint does not close by {gap} pt. En fog sluter inte med {gap} pt. @msg Two panels pass through each other. Två paneler går igenom varandra. @msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h} pixlar är för stort för PSD (högst {MAX_SIDE} pixlar per sida): sänk upplösningen + Vector Packs Vektorpaket + Compass Rose Kompassros + Botanical Sprig Botanisk kvist + Facet Diamond Fasetterad diamant + Tide Crest Vågkam + Leaf Vine Bladranka + Blossom Chain Blomkedja + Pennant Garland Vimpelgirlang + Lantern String Lyktgirlang + Orbit Lines Banlinjer + Petal Garland Kronbladsgirlang + Lattice Braid Gallerfläta + Facet Sweep Fasetterat drag + Artistic Brushes Konstnärliga penslar Paint Färg Flat Sweep Platt penseldrag Dry Drag Torrt drag diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index ce65661e7f..319de5bb5d 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -573,6 +573,26 @@ fn objects_on_path_detach_strings_are_in_complete_catalogs() { } } +/// The errors of Perspective Distort and Free Distort on an image, and of the image commands that +/// refuse a distorted image, are in every complete-message catalog. +#[test] +fn distorted_image_messages_are_in_complete_catalogs() { + let literals = message_literals(); + for msg in [ + "object {_1} is an image changed by Perspective Distort or Free Distort, which this command does not work on", + "image {_1} cannot be distorted this way: its corners would not make a convex shape", + "image {_1} cannot be distorted this way: its corners would cross the warp's horizon", + "image {_1} cannot be distorted this way: its corners would be too close together for a perspective map", + ] { + assert!(literals.contains(msg), "{msg}"); + let shown = msg.replace("{_1}", "7"); + for code in COMPLETE_MESSAGES { + let lang = Lang::from_code(code).expect("registered"); + assert_ne!(message(lang, &shown), shown, "{code}: {msg}"); + } + } +} + /// View › Proof Setup › Customize's labels. #[test] fn proof_setup_dialog_labels_are_in_complete_catalogs() { @@ -4086,6 +4106,22 @@ fn three_d_refusals_translate_with_their_values() { (refuse(vectorcraft_effects::validate_three_d(&rect, CLASSIC_EXTRUDE, &json!({"depth": "deep"}))), "must be a number", vec!["`depth`"]), (refuse(vectorcraft_effects::validate_three_d(&instance, EXTRUDE, &json!({}))), "the symbol's art isn't available", vec!["Mine 7"]), (refuse(vectorcraft_effects::three_d_wireframe_in(None, &rect).map(drop)), "has no 3D effect", vec![]), + ( + refuse(vectorcraft_effects::validate_three_d(&rect, EXTRUDE, &json!({"bevel": "wavy"}))), + "or custom with", + vec!["none", "classic", "custom", "bevelProfile"], + ), + ( + refuse(vectorcraft_effects::validate_three_d(&rect, EXTRUDE, &json!({"bevel": "custom"}))), + "the bevel's points", + vec!["custom", "bevelProfile"], + ), + (refuse(vectorcraft_effects::validate_three_d(&rect, CLASSIC_EXTRUDE, &json!({"bevelName": 3}))), "must be a string", vec!["bevelName"]), + ( + refuse(vectorcraft_effects::validate_three_d(&rect, EXTRUDE, &json!({"bevel": "custom", "bevelProfile": [[0, 0]]}))), + "each share between", + vec!["bevelProfile", "[x, y]", "[0, 0]", "[1, 1]"], + ), ]; for (e, english, _) in &errors { assert!(e.starts_with("invalid parameters for `effect.apply`: ") && e.contains(english), "{e}"); @@ -6563,7 +6599,8 @@ const NAMED_KEYS: &[(&str, &[&str])] = &[ ("axis must be \"vertical\", \"horizontal\" or an angle in degrees, not `{v}`", &["axis"]), ("balance must be between 0 and 100", &["balance"]), ("before must name a panel", &["before"]), - ("bevel must be none or one of {_1}", &["bevel", "none"]), + ("bevel custom needs {BEVEL_PROFILE}, the bevel's points", &["bevel", "custom"]), + ("bevel must be none or one of {_1}, or custom with {BEVEL_PROFILE}", &["bevel", "none", "custom"]), ("brightness must be dark|mediumDark|mediumLight|light", &["brightness", "dark", "mediumDark", "mediumLight", "light"]), ("clip must be true or false", &["clip"]), ("collapsed must be true or false", &["collapsed"]), diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index f0fd71db89..f23a781cd0 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -489,6 +489,10 @@ font-technology Variable Değişken Cusp Sivri nokta Straight segment Düz segment Circle too large Daire çok büyük + Show Radii Yarıçapları Göster + Show Diameter Çapı Göster + Anchors at Standard Positions Standart Konumlarda Bağlantı Noktaları + Third Point by Dragging Sürükleyerek Üçüncü Nokta Classic Defaults Klasik Varsayılanlar Clean Up… Temizleme… Clear Temizle @@ -591,9 +595,14 @@ font-technology Variable Değişken {name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2} Wheel View Tekerlek Görünümü Box View Kutu Görünümü + Show Out-of-Gamut Colors Gamut Dışı Renkleri Göster Box Channel Kutu Kanalı Color box Renk kutusu Color Wheel Options Renk Tekerleği Seçenekleri + Show Document Colors Belge Renklerini Göster + Document Colors Belge Renkleri + Selection Colors Seçim Renkleri +@plural Used {n} time|Used {n} times {n} kez kullanıldı Show Harmony Uyumu Göster Harmony Rule Uyum Kuralı Harmony color Uyum rengi @@ -636,6 +645,8 @@ font-technology Variable Değişken Contextual Task Bar Bağlamsal Görev Çubuğu Pin Bar Position Pim Çubuğu Konumu Reset Bar Position Çubuk Konumunu Sıfırla + Bar Actions Çubuk Eylemleri + Reset Bar Actions Çubuk Eylemlerini Sıfırla Contrast Kontrast Control Kontrol Convert Dönüştür @@ -1730,6 +1741,10 @@ font-technology Variable Değişken Rename Preset Ön Ayarı Yeniden Adlandır Save Image Trace Preset Görüntü İzleme Ön Ayarını Kaydet Delete Image Trace Preset Görüntü İzleme Ön Ayarını Sil + Tracing Presets… İzleme Ön Ayarları… + Import Image Trace Presets Görüntü İzleme Ön Ayarlarını İçe Aktar + Export Image Trace Presets Görüntü İzleme Ön Ayarlarını Dışa Aktar + Replace the saved presets that have these names? Bu adlara sahip kayıtlı ön ayarlar değiştirilsin mi? Image Trace Presets Görüntü İzleme Ön Ayarları Image: Resim: Images: Görseller: @@ -1859,6 +1874,11 @@ font-technology Variable Değişken Knife Bıçak Knockout Group Nakavt Grubu Lab Laboratuvar + OKLCH Sliders OKLCH Kaydırıcıları + HSL Sliders HSL Kaydırıcıları + Chroma Kroma + The largest chroma sRGB holds at this lightness and hue sRGB'nin bu açıklık ve renk tonunda alabileceği en yüksek kroma + OKLCH needs sRGB as the working RGB space OKLCH, çalışma RGB alanı olarak sRGB gerektirir Lab Spot Colors: Laboratuvar Spot Renkleri: Lab Values Laboratuvar Değerleri Landscape Manzara @@ -2567,6 +2587,13 @@ shape Open Açık Pen Tool Kalem Aracı Quick Pen Tool Hızlı Kalem Aracı Quick Pen Hızlı Kalem + Quick Pen Toolbar Hızlı Kalem Araç Çubuğu + Continuous Arc Sürekli Yay + Sharp Corner Arc Keskin Köşeli Yay + Flip Arc Yayı Çevir + Hide Toolbar Araç Çubuğunu Gizle + Pin Toolbar Position Araç Çubuğu Konumunu Sabitle + Reset Toolbar Position Araç Çubuğu Konumunu Sıfırla Pencil Kalem Pencil Tool Kurşun Kalem Aracı per slice dilim başına @@ -3005,6 +3032,11 @@ digits Malayalam Malayalam Edit Arrowheads Ok Uçlarını Düzenle Edit Arrowheads… Ok Uçlarını Düzenle… Reload Arrowheads Ok Uçlarını Yeniden Yükle + Bevels Eğimler + Edit Bevels Eğimleri Düzenle + Edit Bevels… Eğimleri Düzenle… + {name} (document) {name} (belge) + Reload Bevels Eğimleri Yeniden Yükle Reset Rotate View Döndürme Görünümünü Sıfırla Rotate View to Selection Görünümü Seçime Döndür Reset the rows to the artwork's colors Satırları resmin renklerine göre sıfırlayın @@ -3142,9 +3174,14 @@ digits Malayalam Malayalam Edit type set in fonts that aren't available? Mevcut olmayan yazı tiplerindeki metin düzenlensin mi? Shows each slice's number in a box at its top left on the canvas; off, the slice outlines still show. Tuvalde her dilimin numarasını sol üst köşesindeki bir kutuda gösterir; kapalıyken dilimlerin dış çizgileri görünmeye devam eder. The color of user and object slice outlines and their number boxes; auto slices use a dimmer shade of it. Kullanıcı ve nesne dilimlerinin dış çizgilerinin ve numara kutularının rengi; otomatik dilimler bu rengin daha soluk bir tonunu kullanır. + In paragraphs with Hyphenate on, a listed word is hyphenated only at the hyphens typed in it, or never when it has none, whatever its language or case. Tireleme açık paragraflarda listedeki bir sözcük yalnızca içine yazılan tirelerden tirelenir, tire yoksa hiç tirelenmez; dili ve büyük/küçük harf durumu fark etmez. + On the desktop, this folder's .wasm plug-ins load at startup and when OK sets a new folder, except in Safe Mode; one that asks for permissions loads only after you grant them. The web version loads none. Masaüstü sürümünde bu klasördeki .wasm eklentileri başlangıçta ve Tamam yeni bir klasör ayarladığında yüklenir, Güvenli Mod hariç; izin isteyen bir eklenti ancak siz izinleri verdikten sonra yüklenir. Web sürümü hiçbirini yüklemez. + Large gives each filter or command plug-in run at least 250 million instructions, with the same time limit; Normal keeps the plug-in's own budget. Live effects, exporters and importers keep theirs. Büyük, bir filtre veya komut eklentisinin her çalışmasına aynı süre sınırıyla en az 250 milyon talimat verir; Normal eklentinin kendi bütçesini korur. Canlı efektler, dışa aktarıcılar ve içe aktarıcılar kendi bütçelerini korur. New type takes this language while Document Setup's language is English: USA; type already in a document keeps its own language. Belge Kurulumu'nun dili İngilizce: ABD olduğu sürece yeni metin bu dili alır; bir belgede zaten bulunan metin kendi dilini korur. + New type takes this language while Document Setup's language is English: USA and [Normal Character Style] sets none; type already in a document keeps its own language. Belge Kurulumu'nun dili İngilizce: ABD olduğu ve [Normal Karakter Stili] bir dil belirlemediği sürece yeni metin bu dili alır; bir belgede zaten bulunan metin kendi dilini korur. In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its language or case. Tireleme açık paragraflarda listedeki bir sözcük yalnızca içine yazılan tirelerden bölünür, tire yoksa hiç bölünmez; dili ve büyük/küçük harf durumu fark etmez. On the desktop, the .wasm plug-ins in this folder load at startup and when you click OK with a new folder here, except in Safe Mode; the web version does not load them. Masaüstü sürümünde bu klasördeki .wasm eklentileri başlangıçta ve burada yeni bir klasörle Tamam'a tıkladığınızda yüklenir, Güvenli Mod hariç; web sürümü bunları yüklemez. + Normal keeps each plug-in's own limits; with Large, a plug-in filter or command may run at least 250 million instructions besides those for its input. The time limit stays the same. Normal, her eklentinin kendi sınırlarını korur; Büyük ile bir eklenti filtresi veya komutu, girdisi için olanlara ek olarak en az 250 milyon talimat çalıştırabilir. Süre sınırı aynı kalır. How many instructions each run of a plug-in object filter may use; Large allows more than Normal with the same 60-second limit. Heavy filters keep their own budget. Bir eklentinin nesne filtresinin her çalıştırmasının kullanabileceği talimat sayısı; Büyük, aynı 60 saniyelik sınırla Normal'den fazlasına izin verir. Ağır filtreler kendi bütçelerini korur. The first scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. İlk geçici disk seçimi: Startup, None veya bir klasör yolu; VectorCraft bunu saklar ancak henüz geçici disk kullanmaz. The second scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. İkinci geçici disk seçimi: Startup, None veya bir klasör yolu; VectorCraft bunu saklar ancak henüz geçici disk kullanmaz. @@ -3156,13 +3193,15 @@ digits Malayalam Malayalam Shows each tool group's name above its tools in the toolbar; off, the groups follow one another with nothing between them. Araç çubuğunda her araç grubunun adını araçlarının üstünde gösterir; kapalıyken gruplar arada hiçbir şey olmadan birbirini izler. From now on, documents you open or create open as tabs; off, each opens in a floating window. Documents already open stay where they are. Bundan sonra açtığınız veya oluşturduğunuz belgeler sekme olarak açılır; kapalıyken her biri kayan bir pencerede açılır. Zaten açık olan belgeler yerinde kalır. Makes the document tabs taller and their names larger. Belge sekmelerini daha yüksek, adlarını daha büyük yapar. - From the next start, the system draws the window's title bar where VectorCraft would otherwise draw its own. Bir sonraki başlatmadan itibaren sistem, VectorCraft'ın aksi halde kendi başlık çubuğunu çizeceği yerde pencerenin başlık çubuğunu çizer. - From the next start, VectorCraft draws the window's title bar even where the desktop would draw it, unless System Title Bar is on. Bir sonraki başlatmadan itibaren VectorCraft, masaüstünün çizeceği yerlerde bile pencerenin başlık çubuğunu çizer; Sistem Başlık Çubuğu açıksa çizmez. + From the next start, the system draws the window's title bar where VectorCraft would otherwise draw its own; on Linux and the BSDs, the VECTORCRAFT_TITLEBAR variable takes precedence. Bir sonraki başlatmadan itibaren sistem, VectorCraft'ın aksi halde kendi başlık çubuğunu çizeceği yerde pencerenin başlık çubuğunu çizer; Linux ve BSD'lerde VECTORCRAFT_TITLEBAR değişkeni önceliklidir. + From the next start, VectorCraft draws the window's title bar even where the desktop would draw it, unless System Title Bar is on or the VECTORCRAFT_TITLEBAR variable chooses it. Bir sonraki başlatmadan itibaren VectorCraft, masaüstünün çizeceği yerlerde bile pencerenin başlık çubuğunu çizer; Sistem Başlık Çubuğu açıksa veya VECTORCRAFT_TITLEBAR değişkeni onu seçiyorsa çizmez. Makes the interface larger or smaller; art on the canvas keeps its size at the same zoom. Arayüzü büyütür veya küçültür; kanvastaki çizim aynı yakınlaştırmada boyutunu korur. The tool pointers VectorCraft draws grow and shrink with UI Scaling; off, they keep their size. VectorCraft'ın çizdiği araç işaretçileri Kullanıcı Arayüzü Ölçeklendirme ile büyüyüp küçülür; kapalıyken boyutlarını korur. The language of the interface; Auto uses the system's language. The dialog switches language as soon as you choose one. Arayüzün dili; Otomatik, sistemin dilini kullanır. İletişim kutusu, bir dil seçer seçmez o dile geçer. Animated Zoom works only while this is on; off, Animated Zoom is dimmed and zooming does not animate. Animasyonlu Yakınlaştırma yalnızca bu açıkken çalışır; kapalıyken Animasyonlu Yakınlaştırma soluk görünür ve yakınlaştırma animasyonlu olmaz. The wheel's zoom glides in, and the Zoom tool zooms as you drag sideways or hold it down; off, the Zoom tool zooms to the area you drag across. Tekerlekle yakınlaştırma yumuşakça kayar, Yakınlaştırma Aracı ise yana sürüklerken veya basılı tutarken yakınlaştırır; kapalıyken Yakınlaştırma Aracı sürüklediğiniz alana yakınlaştırır. + From the next start, the desktop version shows the canvas through this kind of graphics processor; the artwork is drawn on the CPU either way. Automatic prefers the integrated one on Windows and macOS. The web version does not use it. Bir sonraki başlatmadan itibaren masaüstü sürümü tuvali bu tür grafik işlemci üzerinden gösterir; çizim her durumda CPU'da yapılır. Otomatik, Windows ve macOS'ta tümleşik işlemciyi tercih eder. Web sürümü bunu kullanmaz. + From the next start, the window shows each frame without waiting for the display's refresh where the graphics driver allows, at most 240 frames a second. Bir sonraki başlatmadan itibaren pencere, grafik sürücüsünün izin verdiği yerde ekranın yenilenmesini beklemeden her kareyi gösterir; saniyede en fazla 240 kare. From the next start, the desktop version draws with this kind of graphics processor; Automatic prefers the one that drives the display. The web version does not use it. Bir sonraki başlatmadan itibaren masaüstü sürümü bu tür grafik işlemciyle çizer; Otomatik, ekranı süren işlemciyi tercih eder. Web sürümü bunu kullanmaz. From the next start, the window shows frames without waiting for the display to refresh, at most 240 a second; off, the display paces them. A present mode set at launch overrides it. Bir sonraki başlatmadan itibaren pencere, ekranın yenilenmesini beklemeden kareleri gösterir, saniyede en fazla 240; kapalıyken hızı ekran belirler. Başlatırken ayarlanan bir sunum modu önceliklidir. The most undo steps each document keeps; lowering it drops the oldest steps when you click OK. Steps can also go sooner when they use too much memory. Her belgenin sakladığı en fazla geri alma adımı sayısı; daha düşük bir sayı, Tamam'a tıkladığınızda en eski adımları kaldırır. Adımlar çok fazla bellek kullanırsa daha erken de gidebilir. @@ -3181,6 +3220,9 @@ digits Malayalam Malayalam Open Recent Files and the Home screen list at most this many recent files; 0 lists none, and VectorCraft still remembers up to 30. Son Dosyaları Aç ve Ana Sayfa ekranı en fazla bu kadar son dosyayı listeler; 0 hiçbirini listelemez ve VectorCraft yine de 30'a kadarını hatırlar. When a document opens, a linked EPS image that shows its saved preview keeps it instead of reading the EPS file again; changed files still follow Update Links. Bir belge açılırken, kayıtlı önizlemesini gösteren bağlı bir EPS görüntüsü EPS dosyasını yeniden okumak yerine bu önizlemeyi korur; değişen dosyalar yine Bağlantıları Güncelle ayarını izler. In Pixel Preview, images are drawn smoothed; off, their pixels show with hard edges. Outside Pixel Preview, images are always smoothed. Piksel Önizlemesi'nde görüntüler yumuşatılarak çizilir; kapalıyken pikselleri keskin kenarlı görünür. Piksel Önizlemesi dışında görüntüler her zaman yumuşatılır. + PDF Text PDF metni + The text of a PDF you open or embed comes in as editable type, or as outlines that look the same on a computer without its fonts. Açtığınız veya gömdüğünüz bir PDF'nin metni düzenlenebilir metin olarak ya da yazı tipleri olmayan bir bilgisayarda aynı görünen ana hatlar olarak gelir. + Linked pages show the file's own text. Bağlı sayfalar dosyanın kendi metnini gösterir. When a linked file changes, Automatically reads it again, Ask When Modified asks you first, and Manually leaves it and shows a note in the status bar. Bağlı bir dosya değiştiğinde Otomatik olarak onu yeniden okur, Değiştirildiğinde Sor önce size sorar, Manuel olarak ise onu olduğu gibi bırakıp durum çubuğunda bir not gösterir. On the desktop, the folder New from Template… and Save as Template… start in; leave it blank for VectorCraft Templates in your documents folder. Masaüstü sürümünde Şablondan yeni… ve Şablon Olarak Kaydet… komutlarının başladığı klasör; belgeler klasörünüzdeki VectorCraft Templates için boş bırakın. Edit Original opens a linked file in the system's default app for its type; off, a linked raster image opens in PhotoCraft where it is installed. Orijinali Düzenle, bağlı bir dosyayı sistemin o tür için varsayılan uygulamasında açar; kapalıyken bağlı bir raster görüntü, kuruluysa PhotoCraft'ta açılır. @@ -3195,7 +3237,6 @@ digits Malayalam Malayalam Output All Blacks as Rich Black draws pure CMYK black as RGB black in RGB and grayscale raster exports and Print as Bitmap; it does not change vector exports, CMYK JPEG, TIFF and PSD, or other printing. Tüm Siyahların Çıkışını Zengin Siyah Olarak Çıkarın seçeneği, RGB ve gri tonlamalı raster dışa aktarımlarda ve Bitmap olarak yazdır ile saf CMYK siyahını RGB siyahı olarak çizer; vektör dışa aktarımları, CMYK JPEG, TIFF ve PSD dosyalarını veya diğer yazdırmaları değiştirmez. On a touch screen, switches to the Touch workspace; turning this off, or losing the touch screen, goes back to the workspace it switched from. Dokunmatik ekranda dokunmatik çalışma alanına geçer; seçenek kapatıldığında veya dokunmatik ekran algılanmadığında önceki çalışma alanına döner. A two-finger tap on the canvas undoes, or switches between selection and drawing tools in the Touch workspace, and a three-finger tap redoes; neither works in Presentation Mode. Tuvale iki parmakla dokunmak geri alır veya dokunmatik çalışma alanında seçim ve çizim araçları arasında geçiş yapar, üç parmakla dokunmak yineler; Sunum Modu'nda ikisi de çalışmaz. - New type takes this language while Document Setup's language is English: USA and [Normal Character Style] sets none; type already in a document keeps its own language. Belge Kurulumu'nun dili İngilizce: ABD olduğu ve [Normal Karakter Stili] bir dil belirlemediği sürece yeni metin bu dili alır; bir belgede zaten bulunan metin kendi dilini korur. In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its case; Korean words take no hyphen, and Indian-language words do not break inside a character cluster. Tireleme açık paragraflarda listedeki bir sözcük yalnızca içine yazılan tirelerden bölünür, tire yoksa hiç bölünmez; büyük/küçük harf durumu fark etmez, Korece sözcükler tire almaz ve Hint dillerindeki sözcükler bir karakter grubunun içinden bölünmez. Reset all preferences to their defaults? Tüm tercihler varsayılanlarına sıfırlansın mı? The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. Varsayılanlar, Tercihler'de Tamam'a tıkladığınızda uygulanır. Oradaki İptal, mevcut tercihlerinizi korur. @@ -3461,6 +3502,7 @@ digits Malayalam Malayalam Recent Commands Son komutlar No recent commands Son komut yok Type to search commands, tools, panels and effects Komutları, araçları, panelleri ve efektleri aramak için yazın + Clear Recent Commands Son Komutları Temizle Search commands Komutları arayın Search Commands… Arama Komutları… Secondary İkincil @@ -4911,6 +4953,8 @@ liquify-list-end {0}, {1} {0} ve {1} @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` grayscale, rgb, hsb, cmyk veya websafe olmalıdır @msg `view` must be wheel or box `view` wheel veya box olmalıdır @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` hue, saturation, brightness, red, green veya blue olmalıdır +@msg `sliders` must be none, oklch or hsl `sliders` none, oklch veya hsl olmalıdır +@msg OKLCH needs sRGB as the working RGB space OKLCH, çalışma RGB alanı olarak sRGB gerektirir @msg `{k}` must be [x, y] `{k}` [x, y] olmalıdır @msg `{name}` has no options `{name}`nin seçeneği yok @msg `{name}` is a built-in workspace; choose another name `{name}` yerleşik bir çalışma alanıdır; başka bir isim seç @@ -5318,6 +5362,10 @@ liquify-list-end {0}, {1} {0} ve {1} @msg this trace would make more than {max} anchor points, more than the document can show smoothly: raise Noise, lower Paths or Colors, or pick a lower-fidelity preset bu iz, {max} bağlantı noktalarından daha fazlasını, yani belgenin düzgün bir şekilde gösterebileceğinden daha fazlasını oluşturur: Gürültüyü artırın, Yolları veya Renkleri düşürün veya aslına uygunluğu daha düşük bir ön ayar seçin @msg select an envelope bir zarf seç @msg select an image bir resim seç +@msg object {_1} is an image changed by Perspective Distort or Free Distort, which this command does not work on {_1} nesnesi Perspektif Deformasyonu veya Serbest Deformasyon ile değiştirilmiş bir görüntüdür ve bu komut onunla çalışmaz +@msg image {_1} cannot be distorted this way: its corners would not make a convex shape {_1} görüntüsü bu şekilde deforme edilemez: köşeleri dışbükey bir şekil oluşturmaz +@msg image {_1} cannot be distorted this way: its corners would cross the warp's horizon {_1} görüntüsü bu şekilde deforme edilemez: köşeleri deformasyonun ufkunu geçer +@msg image {_1} cannot be distorted this way: its corners would be too close together for a perspective map {_1} görüntüsü bu şekilde deforme edilemez: köşeleri perspektif eşleme için birbirine çok yakın olur @msg `background` must be edges, corners or colors `background` edges, corners veya colors olmalıdır @msg `match` must be distance or channels `match` distance veya channels olmalıdır @msg `{key}` must be from 0 to 100 `{key}` 0 ile 100 arasında olmalıdır @@ -6134,7 +6182,10 @@ lighting Light Işık @msg the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate) nesnenin 3 boyutlu efekti yok (Ekstrüzyon ve Eğim, Eksen Etrafında Döndür, Şişir veya Döndür) @msg `render` must be an object holding only `mode`, set to shaded or wireframe `render`, yalnızca değeri shaded veya wireframe olan `mode` içeren bir nesne olmalıdır @msg its 3D effect builds no solid 3 boyutlu efekti hiçbir katı oluşturmuyor -@msg bevel must be none or one of {_1} bevel, none veya {_1} değerlerinden biri olmalıdır +@msg bevel must be none or one of {_1}, or custom with {BEVEL_PROFILE} bevel; none, {_1} değerlerinden biri veya {BEVEL_PROFILE} ile custom olmalıdır +@msg bevel custom needs {BEVEL_PROFILE}, the bevel's points bevel custom için {BEVEL_PROFILE}, yani eğimin noktaları gerekir +@msg {BEVEL_NAME} must be a string {BEVEL_NAME} bir dize olmalıdır +@msg {BEVEL_PROFILE} must be 2 to {most} [x, y] points, each share between 0 and 1, from [0, 0] (the cap's edge) to [1, 1] (the side wall) {BEVEL_PROFILE}, 2 ile {most} arasında [x, y] noktası olmalıdır; her oran 0 ile 1 arasında, [0, 0] (uç yüzeyin kenarı) ile [1, 1] (yan duvar) arasında @msg {_1} can't build solids from this art: its symbol instances, blends and clipping groups hold too many objects {_1} bu resimden katı oluşturamaz: sembol örnekleri, karışımları ve kırpma grupları çok fazla nesne içeriyor @msg {label} can't build a solid from the instance of symbol "{symbol}": the symbol's art isn't available {label}, “{symbol}” sembolünün örneğinden katı oluşturamaz: sembolün resmi kullanılamıyor @msg {_1}: the clipping path is too complex to cut the art with {_1}: kırpma yolu resmi kesmek için çok karmaşık @@ -10706,6 +10757,20 @@ breakText Glyphs Glifler @msg A panel is not joined to the rest by a crease. Bir panel geri kalanlara hiçbir pilyaj çizgisiyle bağlı değil. @msg A fold line is on a non-printing layer. Bir katlama çizgisi yazdırılmayan bir katmanda. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Paneller: {panels}, menteşeler: {hinges}, hatalar: {errors}, uyarılar: {warnings} + Vector Packs Vektör Paketleri + Compass Rose Pusula Gülü + Botanical Sprig Botanik Dal + Facet Diamond Fasetli Elmas + Tide Crest Dalga Tepesi + Leaf Vine Yapraklı sarmaşık + Blossom Chain Çiçek zinciri + Pennant Garland Bayrak süsü + Lantern String Fener dizisi + Orbit Lines Yörünge Çizgileri + Petal Garland Taç Yaprağı Çelengi + Lattice Braid Kafes Örgü + Facet Sweep Fasetli Darbe + Artistic Brushes Sanatsal Fırçalar Paint Boya Flat Sweep Düz fırça izi Dry Drag Kuru sürükleme diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 710eafa214..efc5b68554 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -503,6 +503,11 @@ font-technology Variable Варіативні Cusp Точка звороту Straight segment Прямий сегмент Circle too large Коло завелике + Show Radii Показати радіуси + Show Diameter Показати діаметр + Anchors at Standard Positions Опорні точки в стандартних позиціях + Third Point by Dragging Третя точка перетягуванням + Gray Сірий Classic Defaults Класичні значення за промовчанням Clean Up… Очистити… Clear Очистити @@ -606,9 +611,14 @@ font-technology Variable Варіативні {name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2} Wheel View Вигляд «Коло» Box View Вигляд «Квадрат» + Show Out-of-Gamut Colors Показати кольори поза колірним охопленням Box Channel Канал квадрата Color box Колірний квадрат Color Wheel Options Параметри колірного кола + Show Document Colors Показати кольори документа + Document Colors Кольори документа + Selection Colors Кольори виділення +@plural Used {n} time|Used {n} times Використано {n} раз|Використано {n} рази|Використано {n} разів Show Harmony Показати гармонію Harmony Rule Правило гармонії Harmony color Колір гармонії @@ -652,6 +662,8 @@ font-technology Variable Варіативні Contextual Task Bar Контекстна панель завдань Pin Bar Position Закріпити положення панелі Reset Bar Position Скинути положення панелі + Bar Actions Дії панелі + Reset Bar Actions Скинути дії панелі Resize Змінити розмір Contrast Контраст Control Панель керування @@ -1938,6 +1950,10 @@ file-filter Templates Шаблони Rename Preset Перейменувати набір Save Image Trace Preset Зберегти набір трасування зображення Delete Image Trace Preset Видалити набір трасування зображення + Tracing Presets… Набори трасування… + Import Image Trace Presets Імпортувати набори трасування зображення + Export Image Trace Presets Експортувати набори трасування зображення + Replace the saved presets that have these names? Замінити збережені набори з цими назвами? Image Trace Presets Набір трасування зображення Image: Зображення: Images: Зображення: @@ -2072,6 +2088,11 @@ file-filter Templates Шаблони Knife Ніж Knockout Group Група з вирізуванням Lab Lab + OKLCH Sliders Повзунки OKLCH + HSL Sliders Повзунки HSL + Chroma Хрома + The largest chroma sRGB holds at this lightness and hue Найбільша хрома, яку вміщує sRGB за цієї світлоти й відтінку + OKLCH needs sRGB as the working RGB space Для OKLCH робочим простором RGB має бути sRGB Lab Spot Colors: Плашкові кольори Lab: Lab Values Значення Lab Landscape Альбомна @@ -2832,6 +2853,13 @@ file-filter Templates Шаблони Pen Tool Інструмент «Перо» Quick Pen Tool Інструмент «Швидке перо» Quick Pen Швидке перо + Quick Pen Toolbar Панель швидкого пера + Continuous Arc Неперервна дуга + Sharp Corner Arc Дуга з гострим кутом + Flip Arc Відобразити дугу + Hide Toolbar Сховати панель інструментів + Pin Toolbar Position Закріпити положення панелі інструментів + Reset Toolbar Position Скинути положення панелі інструментів Pencil Олівець Pencil Tool Інструмент «Олівець» per slice на фрагмент @@ -3279,6 +3307,11 @@ digits Malayalam Малаялам Edit Arrowheads Редагувати стрілки Edit Arrowheads… Редагувати стрілки… Reload Arrowheads Перезавантажити стрілки + Bevels Фаски + Edit Bevels Редагувати фаски + Edit Bevels… Редагувати фаски… + {name} (document) {name} (документ) + Reload Bevels Перезавантажити фаски Rotate View Повернути вид Reset Rotate View Скинути поворот виду Rotate View to Selection Повернути вид за виділенням @@ -3417,9 +3450,14 @@ digits Malayalam Малаялам Edit type set in fonts that aren't available? Редагувати текст, набраний недоступними шрифтами? Shows each slice's number in a box at its top left on the canvas; off, the slice outlines still show. Показує на полотні номер кожного фрагмента в рамці в його лівому верхньому куті; коли параметр вимкнено, контури фрагментів і далі видно. The color of user and object slice outlines and their number boxes; auto slices use a dimmer shade of it. Колір контурів користувацьких і об’єктних фрагментів та рамок з їхніми номерами; автоматичні фрагменти використовують блідіший відтінок цього кольору. + New type takes this language while Document Setup's language is English: USA and [Normal Character Style] sets none; type already in a document keeps its own language. Новий текст отримує цю мову, доки в «Параметрах документа» вибрано мову Англійська: США, а [Звичайний стиль символу] не задає мову; текст, який уже є в документі, зберігає свою мову. + In paragraphs with Hyphenate on, a listed word is hyphenated only at the hyphens typed in it, or never when it has none, whatever its language or case. В абзацах з увімкненим параметром «Розставляти переноси» слово зі списку отримує знак переносу лише за введеними в ньому дефісами або ніколи, якщо їх немає, незалежно від мови й регістру. + On the desktop, this folder's .wasm plug-ins load at startup and when OK sets a new folder, except in Safe Mode; one that asks for permissions loads only after you grant them. The web version loads none. У настільній версії модулі .wasm з цієї папки завантажуються під час запуску і коли ОК задає нову папку, крім безпечного режиму; модуль, що запитує дозволи, завантажується лише після того, як ви їх надасте. Веб-версія не завантажує жодного. + Large gives each filter or command plug-in run at least 250 million instructions, with the same time limit; Normal keeps the plug-in's own budget. Live effects, exporters and importers keep theirs. «Великий» дає кожному запуску модуля фільтра або команди щонайменше 250 мільйонів інструкцій з тим самим обмеженням часу; «Звичайний» зберігає власний бюджет модуля. Живі ефекти, експортери та імпортери зберігають свій. New type takes this language while Document Setup's language is English: USA; type already in a document keeps its own language. Новий текст отримує цю мову, доки в «Параметрах документа» вибрано мову Англійська: США; текст, який уже є в документі, зберігає свою мову. In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its language or case. В абзацах з увімкненим параметром «Розставляти переноси» слово зі списку переноситься лише за введеними в ньому дефісами або ніде, якщо їх немає, незалежно від мови й регістру. On the desktop, the .wasm plug-ins in this folder load at startup and when you click OK with a new folder here, except in Safe Mode; the web version does not load them. У настільній версії модулі .wasm з цієї папки завантажуються під час запуску і коли ви натискаєте ОК з новою папкою тут, крім безпечного режиму; веб-версія їх не завантажує. + Normal keeps each plug-in's own limits; with Large, a plug-in filter or command may run at least 250 million instructions besides those for its input. The time limit stays the same. «Звичайний» зберігає власні обмеження кожного модуля; з «Великий» фільтр або команда модуля може виконати щонайменше 250 мільйонів інструкцій понад ті, що потрібні для її вхідних даних. Обмеження часу не змінюється. How many instructions each run of a plug-in object filter may use; Large allows more than Normal with the same 60-second limit. Heavy filters keep their own budget. Скільки інструкцій може використати кожен запуск фільтра об’єктів із модуля; «Великий» дозволяє більше, ніж «Звичайний», з тим самим обмеженням у 60 секунд. Важкі фільтри зберігають власний бюджет. The first scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. Перший вибір робочого диска: Startup, None або шлях до папки; VectorCraft зберігає його, але поки не використовує робочі диски. The second scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. Другий вибір робочого диска: Startup, None або шлях до папки; VectorCraft зберігає його, але поки не використовує робочі диски. @@ -3431,13 +3469,15 @@ digits Malayalam Малаялам Shows each tool group's name above its tools in the toolbar; off, the groups follow one another with nothing between them. Показує назву кожної групи інструментів над її інструментами на панелі інструментів; якщо вимкнено, групи йдуть одна за одною без проміжків. From now on, documents you open or create open as tabs; off, each opens in a floating window. Documents already open stay where they are. Відтепер документи, які ви відкриваєте або створюєте, відкриваються у вкладках; якщо вимкнено, кожен відкривається в плаваючому вікні. Уже відкриті документи лишаються на місці. Makes the document tabs taller and their names larger. Робить вкладки документів вищими, а їхні назви більшими. - From the next start, the system draws the window's title bar where VectorCraft would otherwise draw its own. З наступного запуску система малює рядок заголовка вікна там, де інакше VectorCraft малював би свій. - From the next start, VectorCraft draws the window's title bar even where the desktop would draw it, unless System Title Bar is on. З наступного запуску VectorCraft малює рядок заголовка вікна навіть там, де його намалювало б робоче середовище, якщо не ввімкнено «Системний рядок заголовка». + From the next start, the system draws the window's title bar where VectorCraft would otherwise draw its own; on Linux and the BSDs, the VECTORCRAFT_TITLEBAR variable takes precedence. З наступного запуску система малює рядок заголовка вікна там, де інакше VectorCraft малював би свій; у Linux і BSD пріоритет має змінна VECTORCRAFT_TITLEBAR. + From the next start, VectorCraft draws the window's title bar even where the desktop would draw it, unless System Title Bar is on or the VECTORCRAFT_TITLEBAR variable chooses it. З наступного запуску VectorCraft малює рядок заголовка вікна навіть там, де його намалювало б робоче середовище, якщо не ввімкнено «Системний рядок заголовка» і його не вибирає змінна VECTORCRAFT_TITLEBAR. Makes the interface larger or smaller; art on the canvas keeps its size at the same zoom. Збільшує або зменшує інтерфейс; графіка на полотні зберігає розмір за того самого масштабу. The tool pointers VectorCraft draws grow and shrink with UI Scaling; off, they keep their size. Вказівники інструментів, які малює VectorCraft, ростуть і зменшуються разом із «Масштабом інтерфейсу»; якщо вимкнено, зберігають свій розмір. The language of the interface; Auto uses the system's language. The dialog switches language as soon as you choose one. Мова інтерфейсу; «Авто» використовує мову системи. Діалог перемикає мову, щойно ви її виберете. Animated Zoom works only while this is on; off, Animated Zoom is dimmed and zooming does not animate. Анімоване масштабування працює, лише поки це увімкнено; якщо вимкнено, Анімоване масштабування затінене і масштабування не анімується. The wheel's zoom glides in, and the Zoom tool zooms as you drag sideways or hold it down; off, the Zoom tool zooms to the area you drag across. Масштабування коліщатком іде плавно, а Інструмент «Масштаб» масштабує, поки ви тягнете вбік або утримуєте його; якщо вимкнено, він масштабує до області, яку ви протягнули. + From the next start, the desktop version shows the canvas through this kind of graphics processor; the artwork is drawn on the CPU either way. Automatic prefers the integrated one on Windows and macOS. The web version does not use it. З наступного запуску настільна версія показує полотно через цей тип графічного процесора; саму графіку завжди малює центральний процесор. «Автоматично» у Windows і macOS надає перевагу вбудованому. Веб-версія його не використовує. + From the next start, the window shows each frame without waiting for the display's refresh where the graphics driver allows, at most 240 frames a second. З наступного запуску вікно показує кожен кадр, не чекаючи оновлення дисплея, якщо графічний драйвер це дозволяє, не більше 240 кадрів на секунду. From the next start, the desktop version draws with this kind of graphics processor; Automatic prefers the one that drives the display. The web version does not use it. З наступного запуску настільна версія малює цим типом графічного процесора; «Автоматично» надає перевагу тому, що керує дисплеєм. Веб-версія його не використовує. From the next start, the window shows frames without waiting for the display to refresh, at most 240 a second; off, the display paces them. A present mode set at launch overrides it. З наступного запуску вікно показує кадри, не чекаючи оновлення дисплея, не більше 240 на секунду; якщо вимкнено, темп задає дисплей. Режим виведення, заданий під час запуску, має пріоритет. The most undo steps each document keeps; lowering it drops the oldest steps when you click OK. Steps can also go sooner when they use too much memory. Найбільша кількість кроків скасування, яку зберігає кожен документ; менше число видаляє найстаріші кроки, коли ви натискаєте ОК. Кроки можуть зникнути й раніше, якщо займають надто багато пам’яті. @@ -3456,6 +3496,9 @@ digits Malayalam Малаялам Open Recent Files and the Home screen list at most this many recent files; 0 lists none, and VectorCraft still remembers up to 30. «Відкрити останні файли» та екран «Додому» показують не більше стількох останніх файлів; 0 не показує жодного, а VectorCraft однаково пам’ятає до 30. When a document opens, a linked EPS image that shows its saved preview keeps it instead of reading the EPS file again; changed files still follow Update Links. Під час відкриття документа пов’язане зображення EPS, що показує свій збережений перегляд, залишає його замість повторного читання файлу EPS; змінені файли й далі підлягають «Оновити зв’язки». In Pixel Preview, images are drawn smoothed; off, their pixels show with hard edges. Outside Pixel Preview, images are always smoothed. У «Перегляді пікселів» зображення малюються згладженими; якщо вимкнено, їхні пікселі мають різкі краї. Поза «Переглядом пікселів» зображення завжди згладжуються. + PDF Text Текст PDF + The text of a PDF you open or embed comes in as editable type, or as outlines that look the same on a computer without its fonts. Текст PDF, який ви відкриваєте або вбудовуєте, надходить як редагований текст або як контури, що виглядають так само на комп’ютері без його шрифтів. + Linked pages show the file's own text. Пов’язані сторінки показують власний текст файлу. When a linked file changes, Automatically reads it again, Ask When Modified asks you first, and Manually leaves it and shows a note in the status bar. Коли пов’язаний файл змінюється, «Автоматично» перечитує його, «Запитувати при зміні» спершу питає вас, а «Вручну» залишає його як є і показує примітку в рядку стану. On the desktop, the folder New from Template… and Save as Template… start in; leave it blank for VectorCraft Templates in your documents folder. У настільній версії папка, з якої починають «Створити із шаблону…» і «Зберегти як шаблон…»; залиште порожньою для VectorCraft Templates у вашій папці документів. Edit Original opens a linked file in the system's default app for its type; off, a linked raster image opens in PhotoCraft where it is installed. «Редагувати оригінал» відкриває пов’язаний файл у стандартній програмі системи для його типу; якщо вимкнено, пов’язане растрове зображення відкривається в PhotoCraft, якщо його встановлено. @@ -3470,7 +3513,6 @@ digits Malayalam Малаялам Output All Blacks as Rich Black draws pure CMYK black as RGB black in RGB and grayscale raster exports and Print as Bitmap; it does not change vector exports, CMYK JPEG, TIFF and PSD, or other printing. Виводити всі чорні як складовий чорний малює чистий чорний CMYK як чорний RGB у растрових експортах RGB і у відтінках сірого та з «Друк як растрове зображення»; він не змінює векторні експорти, JPEG, TIFF і PSD у CMYK та інший друк. On a touch screen, switches to the Touch workspace; turning this off, or losing the touch screen, goes back to the workspace it switched from. На сенсорному екрані переходить у сенсорне робоче середовище; вимкнення параметра або зникнення сенсорного екрана повертає робоче середовище, яке було до переходу. A two-finger tap on the canvas undoes, or switches between selection and drawing tools in the Touch workspace, and a three-finger tap redoes; neither works in Presentation Mode. Дотик двома пальцями до полотна скасовує дію, а в сенсорному робочому середовищі перемикає між інструментами виділення й малювання; дотик трьома пальцями повторює. У режимі презентації жоден не працює. - New type takes this language while Document Setup's language is English: USA and [Normal Character Style] sets none; type already in a document keeps its own language. Новий текст отримує цю мову, доки в «Параметрах документа» вибрано мову Англійська: США, а [Звичайний стиль символу] не задає мову; текст, який уже є в документі, зберігає свою мову. In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its case; Korean words take no hyphen, and Indian-language words do not break inside a character cluster. В абзацах з увімкненим параметром «Розставляти переноси» слово зі списку переноситься лише за введеними в ньому дефісами або ніде, якщо їх немає, незалежно від регістру; корейські слова не отримують дефіса, а слова індійськими мовами не переносяться всередині групи символів. Reset all preferences to their defaults? Скинути всі налаштування до значень за промовчанням? The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. Значення за промовчанням застосовуються, коли ви натискаєте ОК у вікні «Налаштування». Скасувати там зберігає поточні налаштування. @@ -3717,6 +3759,7 @@ digits Malayalam Малаялам Recent Commands Нещодавні команди No recent commands Немає нещодавніх команд Type to search commands, tools, panels and effects Почніть вводити для пошуку команд, інструментів, панелей та ефектів + Clear Recent Commands Очистити список нещодавніх команд Search commands Пошук команд Search Commands… Пошук команд… Secondary Вторинний @@ -5194,6 +5237,8 @@ liquify-list-end {0}, {1} {0} і {1} @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` має бути grayscale, rgb, hsb, cmyk або websafe @msg `view` must be wheel or box `view` має бути wheel або box @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` має бути hue, saturation, brightness, red, green або blue +@msg `sliders` must be none, oklch or hsl `sliders` має бути none, oklch або hsl +@msg OKLCH needs sRGB as the working RGB space Для OKLCH робочим простором RGB має бути sRGB @msg `{k}` must be [x, y] `{k}` має бути [x, y] @msg `{name}` has no options `{name}` не має параметрів @msg `{name}` is a built-in workspace; choose another name `{name}` - вбудоване робоче середовище; виберіть інше ім’я @@ -5604,6 +5649,10 @@ liquify-list-end {0}, {1} {0} і {1} @msg this trace would make more than {max} anchor points, more than the document can show smoothly: raise Noise, lower Paths or Colors, or pick a lower-fidelity preset це трасування створило б більше {max} опорних точок, що більше, ніж документ може плавно відобразити: збільште «Шум», зменште «Контури» або «Кольори» або виберіть набір з меншою точністю @msg select an envelope виділіть оболонку @msg select an image виділіть зображення +@msg object {_1} is an image changed by Perspective Distort or Free Distort, which this command does not work on об’єкт {_1} — зображення, змінене за допомогою «Спотворення перспективи» або «Вільна деформація», і ця команда з ним не працює +@msg image {_1} cannot be distorted this way: its corners would not make a convex shape зображення {_1} не можна так деформувати: його кути не утворять опуклої фігури +@msg image {_1} cannot be distorted this way: its corners would cross the warp's horizon зображення {_1} не можна так деформувати: його кути перетнуть горизонт деформації +@msg image {_1} cannot be distorted this way: its corners would be too close together for a perspective map зображення {_1} не можна так деформувати: його кути будуть надто близько один до одного для перспективного відображення @msg `background` must be edges, corners or colors `background` має бути edges, corners або colors @msg `match` must be distance or channels `match` має бути distance або channels @msg `{key}` must be from 0 to 100 `{key}` має бути від 0 до 100 @@ -6423,7 +6472,10 @@ lighting Light Світло @msg the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate) об’єкт не має 3D-ефекту (Видавлювання та фаска, Обертання, Надування або Повернути) @msg `render` must be an object holding only `mode`, set to shaded or wireframe `render` має бути об’єктом лише з полем `mode` зі значенням shaded або wireframe @msg its 3D effect builds no solid його 3D-ефект не будує тіла -@msg bevel must be none or one of {_1} bevel має бути none або одним з: {_1} +@msg bevel must be none or one of {_1}, or custom with {BEVEL_PROFILE} bevel має бути none, одним з: {_1}, або custom з {BEVEL_PROFILE} +@msg bevel custom needs {BEVEL_PROFILE}, the bevel's points для bevel custom потрібен {BEVEL_PROFILE}, точки фаски +@msg {BEVEL_NAME} must be a string {BEVEL_NAME} має бути рядком +@msg {BEVEL_PROFILE} must be 2 to {most} [x, y] points, each share between 0 and 1, from [0, 0] (the cap's edge) to [1, 1] (the side wall) {BEVEL_PROFILE} має містити від 2 до {most} точок [x, y], кожна частка від 0 до 1, від [0, 0] (край торця) до [1, 1] (бічна стінка) @msg {_1} can't build solids from this art: its symbol instances, blends and clipping groups hold too many objects {_1}: не вдається побудувати тіла з цієї ілюстрації: її екземпляри символів, переходи та відсічні групи містять забагато об’єктів @msg {label} can't build a solid from the instance of symbol "{symbol}": the symbol's art isn't available {label}: не вдається побудувати тіло з екземпляра символу «{symbol}»: ілюстрація символу недоступна @msg {_1}: the clipping path is too complex to cut the art with {_1}: відсічний контур надто складний, щоб обрізати ним ілюстрацію @@ -10399,6 +10451,20 @@ breakText Glyphs Гліфи @msg A panel is not joined to the rest by a crease. Панель не з’єднана з рештою жодною лінією біговки. @msg A fold line is on a non-printing layer. Лінія згину лежить на шарі, що не друкується. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Панелі: {panels}, шарніри: {hinges}, помилки: {errors}, попередження: {warnings} + Vector Packs Векторні набори + Compass Rose Роза вітрів + Botanical Sprig Ботанічна гілочка + Facet Diamond Гранований діамант + Tide Crest Гребінь хвилі + Leaf Vine Листяна лоза + Blossom Chain Квітковий ланцюжок + Pennant Garland Гірлянда прапорців + Lantern String Ланцюжок ліхтариків + Orbit Lines Орбітальні лінії + Petal Garland Гірлянда пелюсток + Lattice Braid Ґратчасте плетіння + Facet Sweep Гранований мазок + Artistic Brushes Художні пензлі Paint Фарба Flat Sweep Плоский мазок Dry Drag Сухий протяг diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 9e8ad66998..5d7ee18fdf 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -587,6 +587,11 @@ font-technology Variable Biến thiên Cusp Điểm lùi Straight segment Đoạn thẳng Circle too large Hình tròn quá lớn + Show Radii Hiện bán kính + Show Diameter Hiện đường kính + Anchors at Standard Positions Điểm neo ở vị trí chuẩn + Third Point by Dragging Điểm thứ ba bằng cách kéo + Gray Xám Classic Cổ điển Classic Defaults Mặc định cổ điển Clean Up… Dọn dẹp… @@ -725,9 +730,14 @@ font-technology Variable Biến thiên {name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2} Wheel View Hiển thị bánh xe Box View Hiển thị hộp + Show Out-of-Gamut Colors Hiện màu ngoài dải màu Box Channel Kênh của hộp Color box Hộp màu Color Wheel Options Tùy chọn bánh xe màu + Show Document Colors Hiện màu của tài liệu + Document Colors Màu của tài liệu + Selection Colors Màu của vùng chọn +@plural Used {n} time|Used {n} times Dùng {n} lần Show Harmony Hiện hài hòa màu Harmony Rule Quy tắc hài hòa màu Harmony color Màu hài hòa @@ -2372,6 +2382,11 @@ digits Hindi Hindi Knife Dao Knockout Group Nhóm Knockout Lab Lab + OKLCH Sliders Thanh trượt OKLCH + HSL Sliders Thanh trượt HSL + Chroma Độ tươi màu + The largest chroma sRGB holds at this lightness and hue Độ tươi màu lớn nhất mà sRGB chứa được ở độ sáng và sắc độ này + OKLCH needs sRGB as the working RGB space OKLCH cần sRGB làm không gian RGB làm việc Lab Spot Colors: Màu đặc Lab: Lab Values Giá trị Lab Landscape Ngang @@ -3151,6 +3166,13 @@ digits Hindi Hindi Pen Tool Công cụ Bút Quick Pen Tool Công cụ Bút nhanh Quick Pen Bút nhanh + Quick Pen Toolbar Thanh công cụ Bút nhanh + Continuous Arc Cung liên tục + Sharp Corner Arc Cung góc nhọn + Flip Arc Lật cung + Hide Toolbar Ẩn thanh công cụ + Pin Toolbar Position Ghim vị trí thanh công cụ + Reset Toolbar Position Đặt lại vị trí thanh công cụ Pencil Bút chì Pencil Tool Công cụ Bút chì per slice mỗi lát cắt @@ -3566,6 +3588,8 @@ mark-style Japanese Kiểu Nhật Reset all 3D settings to their defaults. Đặt lại tất cả cài đặt 3D về mặc định. Reset all Revolve settings to their defaults. Đặt lại tất cả cài đặt Revolve về mặc định. Reset Bar Position Đặt lại vị trí thanh + Bar Actions Thao tác của thanh + Reset Bar Actions Đặt lại thao tác của thanh Reset Bounding Box Đặt lại hộp bao Rotate Bounding Box Xoay hộp bao Rotate Bounding Box… Xoay hộp bao… @@ -3590,6 +3614,11 @@ mark-style Japanese Kiểu Nhật Edit Arrowheads Chỉnh sửa đầu mũi tên Edit Arrowheads… Chỉnh sửa đầu mũi tên… Reload Arrowheads Tải lại đầu mũi tên + Bevels Các kiểu vát + Edit Bevels Chỉnh sửa kiểu vát + Edit Bevels… Chỉnh sửa kiểu vát… + {name} (document) {name} (tài liệu) + Reload Bevels Tải lại kiểu vát Rotate View Xoay chế độ xem Reset Rotate View Đặt lại xoay chế độ xem Rotate View to Selection Xoay chế độ xem theo vùng chọn @@ -3741,9 +3770,14 @@ mark-style Japanese Kiểu Nhật Edit type set in fonts that aren't available? Chỉnh sửa văn bản dùng phông chữ không có sẵn? Shows each slice's number in a box at its top left on the canvas; off, the slice outlines still show. Hiển thị trên khung vẽ số của mỗi lát cắt trong một ô ở góc trên bên trái của nó; khi tắt, đường viền của các lát cắt vẫn hiện. The color of user and object slice outlines and their number boxes; auto slices use a dimmer shade of it. Màu của đường viền lát cắt người dùng và lát cắt đối tượng cùng các ô số của chúng; lát cắt tự động dùng một sắc độ nhạt hơn của màu này. + New type takes this language while Document Setup's language is English: USA and [Normal Character Style] sets none; type already in a document keeps its own language. Văn bản mới nhận ngôn ngữ này khi ngôn ngữ trong Thiết lập tài liệu là Tiếng Anh: Mỹ và [Kiểu ký tự thường] không đặt ngôn ngữ; văn bản đã có trong tài liệu giữ ngôn ngữ của nó. + In paragraphs with Hyphenate on, a listed word is hyphenated only at the hyphens typed in it, or never when it has none, whatever its language or case. Trong các đoạn bật Gạch nối, một từ trong danh sách chỉ được thêm gạch nối tại các dấu gạch nối đã gõ trong từ, hoặc không bao giờ nếu không có, bất kể ngôn ngữ hay chữ hoa thường. + On the desktop, this folder's .wasm plug-ins load at startup and when OK sets a new folder, except in Safe Mode; one that asks for permissions loads only after you grant them. The web version loads none. Trong phiên bản máy tính, các plug-in .wasm trong thư mục này được tải khi khởi động và khi OK đặt một thư mục mới, trừ trong Chế độ an toàn; plug-in yêu cầu quyền chỉ được tải sau khi bạn cấp quyền. Phiên bản web không tải plug-in nào. + Large gives each filter or command plug-in run at least 250 million instructions, with the same time limit; Normal keeps the plug-in's own budget. Live effects, exporters and importers keep theirs. Lớn cho mỗi lần chạy plug-in bộ lọc hoặc lệnh ít nhất 250 triệu lệnh máy, với cùng giới hạn thời gian; Thường giữ ngân sách riêng của plug-in. Hiệu ứng trực tiếp, trình xuất và trình nhập giữ ngân sách của chúng. New type takes this language while Document Setup's language is English: USA; type already in a document keeps its own language. Văn bản mới nhận ngôn ngữ này khi ngôn ngữ trong Thiết lập tài liệu là Tiếng Anh: Mỹ; văn bản đã có trong tài liệu giữ ngôn ngữ của nó. In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its language or case. Trong các đoạn bật Gạch nối, một từ trong danh sách chỉ được ngắt tại các dấu gạch nối đã gõ trong từ, hoặc không ngắt ở đâu nếu không có, bất kể ngôn ngữ hay chữ hoa thường. On the desktop, the .wasm plug-ins in this folder load at startup and when you click OK with a new folder here, except in Safe Mode; the web version does not load them. Trong phiên bản máy tính, các plug-in .wasm trong thư mục này được tải khi khởi động và khi bạn bấm OK với một thư mục mới ở đây, trừ trong Chế độ an toàn; phiên bản web không tải chúng. + Normal keeps each plug-in's own limits; with Large, a plug-in filter or command may run at least 250 million instructions besides those for its input. The time limit stays the same. Thường giữ giới hạn riêng của từng plug-in; với Lớn, một bộ lọc hoặc lệnh của plug-in có thể chạy ít nhất 250 triệu lệnh ngoài các lệnh cho dữ liệu đầu vào của nó. Giới hạn thời gian vẫn giữ nguyên. How many instructions each run of a plug-in object filter may use; Large allows more than Normal with the same 60-second limit. Heavy filters keep their own budget. Số lệnh mà mỗi lần chạy bộ lọc đối tượng của plug-in được dùng; Lớn cho phép nhiều hơn Thường với cùng giới hạn 60 giây. Bộ lọc nặng giữ ngân sách riêng. The first scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. Lựa chọn đĩa tạm thứ nhất: Startup, None hoặc đường dẫn thư mục; VectorCraft lưu lựa chọn này nhưng chưa dùng đĩa tạm. The second scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. Lựa chọn đĩa tạm thứ hai: Startup, None hoặc đường dẫn thư mục; VectorCraft lưu lựa chọn này nhưng chưa dùng đĩa tạm. @@ -3755,13 +3789,15 @@ mark-style Japanese Kiểu Nhật Shows each tool group's name above its tools in the toolbar; off, the groups follow one another with nothing between them. Hiện tên của từng nhóm công cụ phía trên các công cụ của nhóm trong thanh công cụ; khi tắt, các nhóm nối tiếp nhau mà không có gì ở giữa. From now on, documents you open or create open as tabs; off, each opens in a floating window. Documents already open stay where they are. Từ giờ, tài liệu bạn mở hoặc tạo sẽ mở dưới dạng tab; khi tắt, mỗi tài liệu mở trong một cửa sổ nổi. Tài liệu đã mở vẫn ở nguyên chỗ. Makes the document tabs taller and their names larger. Làm cho tab tài liệu cao hơn và tên của chúng lớn hơn. - From the next start, the system draws the window's title bar where VectorCraft would otherwise draw its own. Từ lần khởi động tới, hệ thống vẽ thanh tiêu đề của cửa sổ ở nơi mà nếu không thì VectorCraft sẽ tự vẽ. - From the next start, VectorCraft draws the window's title bar even where the desktop would draw it, unless System Title Bar is on. Từ lần khởi động tới, VectorCraft vẽ thanh tiêu đề của cửa sổ ngay cả ở nơi môi trường màn hình nền sẽ vẽ nó, trừ khi Thanh tiêu đề hệ thống đang bật. + From the next start, the system draws the window's title bar where VectorCraft would otherwise draw its own; on Linux and the BSDs, the VECTORCRAFT_TITLEBAR variable takes precedence. Từ lần khởi động tới, hệ thống vẽ thanh tiêu đề của cửa sổ ở nơi mà nếu không thì VectorCraft sẽ tự vẽ; trên Linux và BSD, biến VECTORCRAFT_TITLEBAR được ưu tiên. + From the next start, VectorCraft draws the window's title bar even where the desktop would draw it, unless System Title Bar is on or the VECTORCRAFT_TITLEBAR variable chooses it. Từ lần khởi động tới, VectorCraft vẽ thanh tiêu đề của cửa sổ ngay cả ở nơi môi trường màn hình nền sẽ vẽ nó, trừ khi Thanh tiêu đề hệ thống đang bật hoặc biến VECTORCRAFT_TITLEBAR chọn nó. Makes the interface larger or smaller; art on the canvas keeps its size at the same zoom. Phóng to hoặc thu nhỏ giao diện; hình vẽ trên vùng vẽ giữ nguyên kích thước ở cùng mức thu phóng. The tool pointers VectorCraft draws grow and shrink with UI Scaling; off, they keep their size. Con trỏ công cụ do VectorCraft vẽ to lên và nhỏ lại theo Tỷ lệ giao diện; khi tắt, chúng giữ nguyên kích thước. The language of the interface; Auto uses the system's language. The dialog switches language as soon as you choose one. Ngôn ngữ của giao diện; Tự động dùng ngôn ngữ của hệ thống. Hộp thoại đổi ngôn ngữ ngay khi bạn chọn một ngôn ngữ. Animated Zoom works only while this is on; off, Animated Zoom is dimmed and zooming does not animate. Thu phóng có hiệu ứng chỉ hoạt động khi mục này bật; khi tắt, Thu phóng có hiệu ứng bị làm mờ và việc thu phóng không có hiệu ứng. The wheel's zoom glides in, and the Zoom tool zooms as you drag sideways or hold it down; off, the Zoom tool zooms to the area you drag across. Thu phóng bằng con lăn trượt mượt mà, và Công cụ thu phóng phóng to khi bạn kéo sang ngang hoặc giữ nó; khi tắt, Công cụ thu phóng phóng to vùng bạn kéo qua. + From the next start, the desktop version shows the canvas through this kind of graphics processor; the artwork is drawn on the CPU either way. Automatic prefers the integrated one on Windows and macOS. The web version does not use it. Từ lần khởi động tới, phiên bản máy tính hiển thị khung vẽ qua loại bộ xử lý đồ họa này; tác phẩm luôn được vẽ trên CPU. Tự động ưu tiên bộ xử lý tích hợp trên Windows và macOS. Phiên bản web không dùng nó. + From the next start, the window shows each frame without waiting for the display's refresh where the graphics driver allows, at most 240 frames a second. Từ lần khởi động tới, cửa sổ hiển thị từng khung hình mà không chờ màn hình làm mới khi trình điều khiển đồ họa cho phép, tối đa 240 khung hình mỗi giây. From the next start, the desktop version draws with this kind of graphics processor; Automatic prefers the one that drives the display. The web version does not use it. Từ lần khởi động tới, phiên bản máy tính vẽ bằng loại bộ xử lý đồ họa này; Tự động ưu tiên bộ xử lý điều khiển màn hình. Phiên bản web không dùng nó. From the next start, the window shows frames without waiting for the display to refresh, at most 240 a second; off, the display paces them. A present mode set at launch overrides it. Từ lần khởi động tới, cửa sổ hiển thị khung hình mà không chờ màn hình làm mới, tối đa 240 mỗi giây; khi tắt, màn hình quyết định nhịp. Chế độ trình chiếu đặt khi khởi động sẽ được ưu tiên. The most undo steps each document keeps; lowering it drops the oldest steps when you click OK. Steps can also go sooner when they use too much memory. Số bước hoàn tác tối đa mà mỗi tài liệu giữ; số nhỏ hơn sẽ xóa các bước cũ nhất khi bạn bấm OK. Các bước cũng có thể bị xóa sớm hơn khi chúng dùng quá nhiều bộ nhớ. @@ -3780,6 +3816,9 @@ mark-style Japanese Kiểu Nhật Open Recent Files and the Home screen list at most this many recent files; 0 lists none, and VectorCraft still remembers up to 30. Mở tệp gần đây và màn hình Trang chủ liệt kê tối đa chừng này tệp gần đây; 0 không liệt kê tệp nào, và VectorCraft vẫn nhớ đến 30 tệp. When a document opens, a linked EPS image that shows its saved preview keeps it instead of reading the EPS file again; changed files still follow Update Links. Khi mở tài liệu, ảnh EPS được liên kết đang hiển thị bản xem trước đã lưu sẽ giữ nó thay vì đọc lại tệp EPS; tệp đã thay đổi vẫn theo Cập nhật các liên kết. In Pixel Preview, images are drawn smoothed; off, their pixels show with hard edges. Outside Pixel Preview, images are always smoothed. Trong Xem trước pixel, ảnh được vẽ làm mịn; khi tắt, pixel của chúng hiện với cạnh sắc. Ngoài Xem trước pixel, ảnh luôn được làm mịn. + PDF Text Văn bản PDF + The text of a PDF you open or embed comes in as editable type, or as outlines that look the same on a computer without its fonts. Văn bản của PDF bạn mở hoặc nhúng được đưa vào dưới dạng văn bản có thể chỉnh sửa, hoặc dưới dạng đường bao trông giống hệt trên máy tính không có phông chữ của nó. + Linked pages show the file's own text. Các trang liên kết hiển thị văn bản riêng của tệp. When a linked file changes, Automatically reads it again, Ask When Modified asks you first, and Manually leaves it and shows a note in the status bar. Khi một tệp liên kết thay đổi, Tự động đọc lại nó, Hỏi khi đã sửa đổi hỏi bạn trước, còn Thủ công giữ nguyên và hiện ghi chú trên thanh trạng thái. On the desktop, the folder New from Template… and Save as Template… start in; leave it blank for VectorCraft Templates in your documents folder. Trên phiên bản máy tính, thư mục mà Mới từ mẫu… và Lưu thành mẫu… bắt đầu; để trống để dùng VectorCraft Templates trong thư mục tài liệu của bạn. Edit Original opens a linked file in the system's default app for its type; off, a linked raster image opens in PhotoCraft where it is installed. Chỉnh sửa bản gốc mở tệp liên kết trong ứng dụng mặc định của hệ thống cho loại của nó; khi tắt, ảnh raster liên kết mở trong PhotoCraft nếu đã cài. @@ -3794,7 +3833,6 @@ mark-style Japanese Kiểu Nhật Output All Blacks as Rich Black draws pure CMYK black as RGB black in RGB and grayscale raster exports and Print as Bitmap; it does not change vector exports, CMYK JPEG, TIFF and PSD, or other printing. Xuất tất cả màu đen là đen phong phú vẽ màu đen CMYK thuần thành đen RGB trong các bản xuất raster RGB và thang xám và với In dưới dạng bitmap; tùy chọn này không thay đổi các bản xuất vector, JPEG, TIFF và PSD CMYK hay việc in khác. On a touch screen, switches to the Touch workspace; turning this off, or losing the touch screen, goes back to the workspace it switched from. Trên màn hình cảm ứng, chuyển sang không gian làm việc cảm ứng; tắt tùy chọn này hoặc mất màn hình cảm ứng sẽ trở về không gian làm việc trước khi chuyển. A two-finger tap on the canvas undoes, or switches between selection and drawing tools in the Touch workspace, and a three-finger tap redoes; neither works in Presentation Mode. Chạm hai ngón trên khung vẽ sẽ hoàn tác, hoặc trong không gian làm việc cảm ứng sẽ chuyển giữa công cụ chọn và công cụ vẽ, còn chạm ba ngón sẽ làm lại; cả hai không hoạt động trong chế độ trình bày. - New type takes this language while Document Setup's language is English: USA and [Normal Character Style] sets none; type already in a document keeps its own language. Văn bản mới nhận ngôn ngữ này khi ngôn ngữ trong Thiết lập tài liệu là Tiếng Anh: Mỹ và [Kiểu ký tự thường] không đặt ngôn ngữ; văn bản đã có trong tài liệu giữ ngôn ngữ của nó. In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its case; Korean words take no hyphen, and Indian-language words do not break inside a character cluster. Trong các đoạn bật Gạch nối, một từ trong danh sách chỉ được ngắt tại các dấu gạch nối đã gõ trong từ, hoặc không ngắt ở đâu nếu không có, bất kể chữ hoa thường; từ tiếng Hàn không được thêm gạch nối, và từ trong các ngôn ngữ Ấn Độ không bị ngắt bên trong một cụm ký tự. Reset all preferences to their defaults? Đặt lại tất cả tùy chọn về mặc định? The defaults are applied when you click OK in Preferences. Cancel there keeps your current preferences. Giá trị mặc định được áp dụng khi bạn nhấn OK trong Tùy chọn. Hủy ở đó giữ nguyên các tùy chọn hiện tại của bạn. @@ -4071,6 +4109,7 @@ mark-style Japanese Kiểu Nhật Recent Commands Lệnh gần đây No recent commands Không có lệnh gần đây Type to search commands, tools, panels and effects Nhập để tìm kiếm lệnh, công cụ, bảng và hiệu ứng + Clear Recent Commands Xóa lệnh gần đây Search commands Tìm kiếm lệnh Search Commands… Tìm kiếm lệnh… Search Fonts Folder Tìm kiếm thư mục phông chữ @@ -4792,6 +4831,10 @@ mark-style Japanese Kiểu Nhật Rename Preset Đổi tên thiết lập sẵn Save Image Trace Preset Lưu thiết lập sẵn vector hóa ảnh Delete Image Trace Preset Xóa thiết lập sẵn vector hóa ảnh + Tracing Presets… Thiết lập sẵn vector hóa… + Import Image Trace Presets Nhập thiết lập sẵn vector hóa ảnh + Export Image Trace Presets Xuất thiết lập sẵn vector hóa ảnh + Replace the saved presets that have these names? Thay thế các thiết lập sẵn đã lưu có những tên này? Tracing Result Kết quả vector hóa Tracing Result with Outlines Kết quả vector hóa với đường bao Tracking Giãn chữ @@ -5192,6 +5235,8 @@ theme Appearance Giao diện @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` phải là grayscale, rgb, hsb, cmyk hoặc websafe @msg `view` must be wheel or box `view` phải là wheel hoặc box @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` phải là hue, saturation, brightness, red, green hoặc blue +@msg `sliders` must be none, oklch or hsl `sliders` phải là none, oklch hoặc hsl +@msg OKLCH needs sRGB as the working RGB space OKLCH cần sRGB làm không gian RGB làm việc @msg `{k}` must be [x, y] `{k}` phải là [x, y] @msg `{name}` has no options `{name}` không có tùy chọn @msg `{name}` is a built-in workspace; choose another name `{name}` là không gian làm việc tích hợp sẵn; hãy chọn tên khác @@ -6070,6 +6115,10 @@ liquify-list-end {0}, {1} {0} và {1} @msg a symbol can't hold an instance of itself ký hiệu không thể chứa đối tượng của chính nó @msg select an envelope hãy chọn một Envelope @msg select an image hãy chọn ảnh +@msg object {_1} is an image changed by Perspective Distort or Free Distort, which this command does not work on đối tượng {_1} là ảnh đã được thay đổi bằng Làm méo phối cảnh hoặc Làm méo tự do, lệnh này không dùng được với ảnh đó +@msg image {_1} cannot be distorted this way: its corners would not make a convex shape không thể làm méo ảnh {_1} theo cách này: các góc của ảnh sẽ không tạo thành hình lồi +@msg image {_1} cannot be distorted this way: its corners would cross the warp's horizon không thể làm méo ảnh {_1} theo cách này: các góc của ảnh sẽ vượt qua đường chân trời của phép làm méo +@msg image {_1} cannot be distorted this way: its corners would be too close together for a perspective map không thể làm méo ảnh {_1} theo cách này: các góc của ảnh sẽ quá gần nhau để ánh xạ phối cảnh @msg `background` must be edges, corners or colors `background` phải là edges, corners hoặc colors @msg `match` must be distance or channels `match` phải là distance hoặc channels @msg `{key}` must be from 0 to 100 `{key}` phải nằm trong khoảng 0 đến 100 @@ -6175,7 +6224,10 @@ liquify-list-end {0}, {1} {0} và {1} @msg the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate) đối tượng không có hiệu ứng 3D (Kéo dài & vát, Xoay tròn, Phình hoặc Xoay) @msg `render` must be an object holding only `mode`, set to shaded or wireframe `render` phải là một đối tượng chỉ chứa `mode`, với giá trị shaded hoặc wireframe @msg its 3D effect builds no solid hiệu ứng 3D của nó không tạo ra khối nào -@msg bevel must be none or one of {_1} bevel phải là none hoặc một trong {_1} +@msg bevel must be none or one of {_1}, or custom with {BEVEL_PROFILE} bevel phải là none, một trong {_1}, hoặc custom kèm {BEVEL_PROFILE} +@msg bevel custom needs {BEVEL_PROFILE}, the bevel's points bevel custom cần {BEVEL_PROFILE}, các điểm của kiểu vát +@msg {BEVEL_NAME} must be a string {BEVEL_NAME} phải là một chuỗi +@msg {BEVEL_PROFILE} must be 2 to {most} [x, y] points, each share between 0 and 1, from [0, 0] (the cap's edge) to [1, 1] (the side wall) {BEVEL_PROFILE} phải có từ 2 đến {most} điểm [x, y], mỗi tỷ lệ từ 0 đến 1, từ [0, 0] (cạnh của mặt đầu) đến [1, 1] (thành bên) @msg {_1} can't build solids from this art: its symbol instances, blends and clipping groups hold too many objects {_1} không thể tạo khối từ hình vẽ này: các phiên bản ký hiệu, hòa trộn và nhóm cắt của nó chứa quá nhiều đối tượng @msg {label} can't build a solid from the instance of symbol "{symbol}": the symbol's art isn't available {label} không thể tạo khối từ phiên bản của ký hiệu “{symbol}”: không có hình vẽ của ký hiệu @msg {_1}: the clipping path is too complex to cut the art with {_1}: đường dẫn cắt quá phức tạp để cắt hình vẽ @@ -8596,6 +8648,20 @@ breakText Glyphs Glyph @msg {width} × {height} pixels is too large for Targa (at most 65535 pixels a side): lower the resolution {width} × {height} điểm ảnh quá lớn cho Targa (tối đa 65535 điểm ảnh mỗi cạnh): hãy giảm độ phân giải @msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h} điểm ảnh quá lớn cho PSD (tối đa {MAX_SIDE} điểm ảnh mỗi cạnh): hãy giảm độ phân giải @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer phải là "singleLine", "everyLine", "standardSingleLine" hoặc "standardEveryLine" + Vector Packs Bộ cọ véc-tơ + Compass Rose Hoa la bàn + Botanical Sprig Cành cây + Facet Diamond Kim cương nhiều mặt + Tide Crest Đỉnh sóng + Leaf Vine Dây leo lá + Blossom Chain Chuỗi hoa + Pennant Garland Dây cờ tam giác + Lantern String Dây đèn lồng + Orbit Lines Đường quỹ đạo + Petal Garland Vòng hoa cánh + Lattice Braid Bện lưới + Facet Sweep Nét đa diện + Artistic Brushes Cọ nghệ thuật Paint Sơn Flat Sweep Nét quét phẳng Dry Drag Nét kéo khô diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index e3fb64487a..1259dd74e6 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -456,6 +456,10 @@ antiAlias Sharp 锐利 Cusp 尖点 Straight segment 直线段 Circle too large 圆形过大 + Show Radii 显示半径 + Show Diameter 显示直径 + Anchors at Standard Positions 锚点位于标准位置 + Third Point by Dragging 拖动放置第三点 Classic Defaults 经典默认 Clean Up… 清理… Clear 清除 @@ -557,9 +561,14 @@ antiAlias Sharp 锐利 {name1} {value1}, {name2} {value2} {name1} {value1},{name2} {value2} Wheel View 色轮视图 Box View 方块视图 + Show Out-of-Gamut Colors 显示超出色域的颜色 Box Channel 方块色版 Color box 颜色方块 Color Wheel Options 色轮选项 + Show Document Colors 显示文档颜色 + Document Colors 文档颜色 + Selection Colors 所选对象的颜色 +@plural Used {n} time|Used {n} times 使用 {n} 次 Show Harmony 显示协调 Harmony Rule 协调规则 Harmony color 协调颜色 @@ -603,6 +612,8 @@ antiAlias Sharp 锐利 Contextual Task Bar 上下文任务栏 Pin Bar Position 固定任务栏位置 Reset Bar Position 重置任务栏位置 + Bar Actions 任务栏操作 + Reset Bar Actions 重置任务栏操作 Resize 调整大小 Contrast 对比 Control 控制栏 @@ -1861,6 +1872,10 @@ file-filter Templates 模板 Rename Preset 重命名预设 Save Image Trace Preset 保存图像描摹预设 Delete Image Trace Preset 删除图像描摹预设 + Tracing Presets… 描摹预设… + Import Image Trace Presets 导入图像描摹预设 + Export Image Trace Presets 导出图像描摹预设 + Replace the saved presets that have these names? 替换具有这些名称的已存储预设? Image Trace Presets 图像描摹预设 Image: 图像: Images: 图像: @@ -1954,6 +1969,11 @@ file-filter Templates 模板 Knife 刻刀 Knockout Group 挖空组 Lab Lab + OKLCH Sliders OKLCH 滑块 + HSL Sliders HSL 滑块 + Chroma 色度 + The largest chroma sRGB holds at this lightness and hue sRGB 在此亮度和色相下可容纳的最大色度 + OKLCH needs sRGB as the working RGB space OKLCH 需要将 sRGB 用作 RGB 工作空间 Lab Spot Colors: Lab 专色: Lab Values Lab 值 Landscape 横向 @@ -2684,6 +2704,13 @@ file-filter Templates 模板 Pen Tool 钢笔工具 Quick Pen Tool 快速钢笔工具 Quick Pen 快速钢笔 + Quick Pen Toolbar 快速钢笔工具栏 + Continuous Arc 连续弧线 + Sharp Corner Arc 尖角弧线 + Flip Arc 翻转弧线 + Hide Toolbar 隐藏工具栏 + Pin Toolbar Position 固定工具栏位置 + Reset Toolbar Position 重置工具栏位置 Pencil 铅笔 Pencil Tool 铅笔工具 per slice 每个切片 @@ -3130,6 +3157,11 @@ digits Malayalam 马拉雅拉姆数字 Edit Arrowheads 编辑箭头 Edit Arrowheads… 编辑箭头… Reload Arrowheads 重新载入箭头 + Bevels 斜角列表 + Edit Bevels 编辑斜角 + Edit Bevels… 编辑斜角… + {name} (document) {name} (文档) + Reload Bevels 重新载入斜角 Reset Rotate View 重置旋转视图 Rotate View to Selection 按所选对象旋转视图 Reset the rows to the artwork's colors 将各行重置为图稿的颜色 @@ -3267,9 +3299,13 @@ digits Malayalam 马拉雅拉姆数字 Edit type set in fonts that aren't available? 要编辑使用了不可用字体的文字吗? Shows each slice's number in a box at its top left on the canvas; off, the slice outlines still show. 在画布上于每个切片左上角的方框中显示其编号;关闭时,切片轮廓仍会显示。 The color of user and object slice outlines and their number boxes; auto slices use a dimmer shade of it. 用户切片和对象切片的轮廓及其编号方框的颜色;自动切片使用此颜色较淡的色调。 + In paragraphs with Hyphenate on, a listed word is hyphenated only at the hyphens typed in it, or never when it has none, whatever its language or case. 在启用自动断字的段落中,列表中的单词只在其中键入的连字符处加断字连字符,没有连字符则从不断字,与语言和大小写无关。 + On the desktop, this folder's .wasm plug-ins load at startup and when OK sets a new folder, except in Safe Mode; one that asks for permissions loads only after you grant them. The web version loads none. 在桌面版中,此文件夹中的 .wasm 增效工具会在启动时以及通过“确定”设置新文件夹时载入,安全模式除外;请求权限的增效工具只在您授予权限后载入。Web 版不载入任何增效工具。 + Large gives each filter or command plug-in run at least 250 million instructions, with the same time limit; Normal keeps the plug-in's own budget. Live effects, exporters and importers keep theirs. “大”为滤镜或命令增效工具的每次运行提供至少 2.5 亿条指令,时间限制不变;“正常”保留增效工具自己的预算。实时效果、导出器和导入器保留各自的预算。 New type takes this language while Document Setup's language is English: USA; type already in a document keeps its own language. 当文档设置的语言为英语:美国时,新文字使用此语言;文档中已有的文字保留自己的语言。 In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its language or case. 在启用自动断字的段落中,列表中的单词只在其中键入的连字符处断开,没有连字符则不断开,与语言和大小写无关。 On the desktop, the .wasm plug-ins in this folder load at startup and when you click OK with a new folder here, except in Safe Mode; the web version does not load them. 在桌面版中,此文件夹中的 .wasm 增效工具会在启动时以及在此处指定新文件夹并单击“确定”时载入,安全模式除外;Web 版不会载入它们。 + Normal keeps each plug-in's own limits; with Large, a plug-in filter or command may run at least 250 million instructions besides those for its input. The time limit stays the same. “正常”保留每个增效工具自身的限制;选择“大”时,增效工具的滤镜或命令除处理其输入所需的指令外,至少可运行 2.5 亿条指令。时间限制不变。 How many instructions each run of a plug-in object filter may use; Large allows more than Normal with the same 60-second limit. Heavy filters keep their own budget. 增效工具的对象滤镜每次运行可使用的指令数;“大”比“正常”允许更多,60 秒的时间限制不变。重型滤镜保留自己的预算。 The first scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. 第一个暂存盘选择:Startup、None 或文件夹路径;VectorCraft 会存储它,但尚未使用暂存盘。 The second scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. 第二个暂存盘选择:Startup、None 或文件夹路径;VectorCraft 会存储它,但尚未使用暂存盘。 @@ -3281,13 +3317,15 @@ digits Malayalam 马拉雅拉姆数字 Shows each tool group's name above its tools in the toolbar; off, the groups follow one another with nothing between them. 在工具栏中把每个工具组的名称显示在其工具上方;关闭此项后,各组依次排列,中间没有任何内容。 From now on, documents you open or create open as tabs; off, each opens in a floating window. Documents already open stay where they are. 从现在起,打开或新建的文档以标签页打开;关闭此项后,每个文档在浮动窗口中打开。已打开的文档保持原位。 Makes the document tabs taller and their names larger. 让文档标签页更高,标签上的名称更大。 - From the next start, the system draws the window's title bar where VectorCraft would otherwise draw its own. 从下次启动起,在 VectorCraft 原本会自行绘制标题栏的地方,改由系统绘制窗口的标题栏。 - From the next start, VectorCraft draws the window's title bar even where the desktop would draw it, unless System Title Bar is on. 从下次启动起,即使桌面会绘制窗口的标题栏,VectorCraft 也会自行绘制,除非开启了系统标题栏。 + From the next start, the system draws the window's title bar where VectorCraft would otherwise draw its own; on Linux and the BSDs, the VECTORCRAFT_TITLEBAR variable takes precedence. 从下次启动起,在 VectorCraft 原本会自行绘制标题栏的地方,改由系统绘制窗口的标题栏;在 Linux 和 BSD 上,VECTORCRAFT_TITLEBAR 变量优先。 + From the next start, VectorCraft draws the window's title bar even where the desktop would draw it, unless System Title Bar is on or the VECTORCRAFT_TITLEBAR variable chooses it. 从下次启动起,即使桌面会绘制窗口的标题栏,VectorCraft 也会自行绘制,除非开启了系统标题栏或 VECTORCRAFT_TITLEBAR 变量选择了标题栏。 Makes the interface larger or smaller; art on the canvas keeps its size at the same zoom. 放大或缩小界面;在相同缩放比例下,画布上的图稿保持原有大小。 The tool pointers VectorCraft draws grow and shrink with UI Scaling; off, they keep their size. VectorCraft 绘制的工具指针随界面缩放一起变大变小;关闭此项后,指针保持原有大小。 The language of the interface; Auto uses the system's language. The dialog switches language as soon as you choose one. 界面的语言;“自动”使用系统的语言。选择一种语言后,对话框会立即切换到该语言。 Animated Zoom works only while this is on; off, Animated Zoom is dimmed and zooming does not animate. 只有开启此项时,动画缩放才会起作用;关闭此项后,动画缩放显示为灰色,缩放不带动画。 The wheel's zoom glides in, and the Zoom tool zooms as you drag sideways or hold it down; off, the Zoom tool zooms to the area you drag across. 用滚轮缩放时会平滑过渡,缩放工具在你向侧面拖动或按住不放时进行缩放;关闭此项后,缩放工具缩放到你拖过的区域。 + From the next start, the desktop version shows the canvas through this kind of graphics processor; the artwork is drawn on the CPU either way. Automatic prefers the integrated one on Windows and macOS. The web version does not use it. 从下次启动起,桌面版通过这类图形处理器显示画布;图稿始终在 CPU 上绘制。“自动”在 Windows 和 macOS 上优先使用集成图形处理器。Web 版不使用此项。 + From the next start, the window shows each frame without waiting for the display's refresh where the graphics driver allows, at most 240 frames a second. 从下次启动起,在图形驱动程序允许时,窗口显示每一帧而不等待显示器刷新,最多每秒 240 帧。 From the next start, the desktop version draws with this kind of graphics processor; Automatic prefers the one that drives the display. The web version does not use it. 从下次启动起,桌面版使用这类图形处理器绘制;“自动”优先使用驱动显示器的图形处理器。Web 版不使用此项。 From the next start, the window shows frames without waiting for the display to refresh, at most 240 a second; off, the display paces them. A present mode set at launch overrides it. 从下次启动起,窗口不等待显示器刷新就显示帧,每秒最多 240 帧;关闭时由显示器决定帧的节奏。启动时设置的呈现模式优先。 The most undo steps each document keeps; lowering it drops the oldest steps when you click OK. Steps can also go sooner when they use too much memory. 每个文档保留的最大撤销步骤数;调低后,单击“确定”时会删除最早的步骤。步骤占用过多内存时也可能更早被删除。 @@ -3306,6 +3344,9 @@ digits Malayalam 马拉雅拉姆数字 Open Recent Files and the Home screen list at most this many recent files; 0 lists none, and VectorCraft still remembers up to 30. “打开最近文件”和主页屏幕最多列出这么多最近文件;为 0 时不列出,但 VectorCraft 仍会记住最多 30 个。 When a document opens, a linked EPS image that shows its saved preview keeps it instead of reading the EPS file again; changed files still follow Update Links. 打开文档时,显示已保存预览的链接 EPS 图像会保留该预览,而不重新读取 EPS 文件;已更改的文件仍按“更新链接”处理。 In Pixel Preview, images are drawn smoothed; off, their pixels show with hard edges. Outside Pixel Preview, images are always smoothed. 在像素预览中,图像以平滑方式绘制;关闭此项后,像素边缘清晰锐利。像素预览之外,图像始终平滑显示。 + PDF Text PDF 文本 + The text of a PDF you open or embed comes in as editable type, or as outlines that look the same on a computer without its fonts. 打开或嵌入的 PDF 中的文本以可编辑文本导入,或以轮廓导入,在没有其字体的电脑上看起来也一样。 + Linked pages show the file's own text. 链接的页面显示文件本身的文本。 When a linked file changes, Automatically reads it again, Ask When Modified asks you first, and Manually leaves it and shows a note in the status bar. 链接文件更改时,“自动”会重新读取,“修改时询问”会先询问你,“手动”则保持不变并在状态栏显示提示。 On the desktop, the folder New from Template… and Save as Template… start in; leave it blank for VectorCraft Templates in your documents folder. 在桌面版中,“从模板新建…”和“存为模板…”打开时所在的文件夹;留空则使用文档文件夹中的 VectorCraft Templates。 Edit Original opens a linked file in the system's default app for its type; off, a linked raster image opens in PhotoCraft where it is installed. “编辑原稿”用系统中该类型的默认应用打开链接文件;关闭此项后,若已安装 PhotoCraft,链接的栅格图像会在 PhotoCraft 中打开。 @@ -3533,6 +3574,7 @@ digits Malayalam 马拉雅拉姆数字 Recent Commands 最近使用的命令 No recent commands 没有最近使用的命令 Type to search commands, tools, panels and effects 输入以搜索命令、工具、面板和效果 + Clear Recent Commands 清除最近使用的命令 Search commands 搜索命令 Search Commands… 搜索命令… Secondary 次要 @@ -5309,6 +5351,8 @@ imageTrace Outline 轮廓 @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` 必须是 grayscale、rgb、hsb、cmyk 或 websafe @msg `view` must be wheel or box `view` 必须是 wheel 或 box @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` 必须是 hue、saturation、brightness、red、green 或 blue +@msg `sliders` must be none, oklch or hsl `sliders` 必须是 none、oklch 或 hsl +@msg OKLCH needs sRGB as the working RGB space OKLCH 需要将 sRGB 用作 RGB 工作空间 @msg `{key}` must be true or false `{key}` 必须是 true 或 false @msg `top` and `below` can't both be true `top` 和 `below` 不能同时为 true @msg `select` must be true or false `select` 必须是 true 或 false @@ -5340,6 +5384,10 @@ imageTrace Outline 轮廓 @msg no such view 没有此视图 @msg printing isn't available here 此处无法打印 @msg select an image 请选择一个图像 +@msg object {_1} is an image changed by Perspective Distort or Free Distort, which this command does not work on 对象 {_1} 是经过透视扭曲或自由变形的图像,此命令不适用于它 +@msg image {_1} cannot be distorted this way: its corners would not make a convex shape 无法这样扭曲图像 {_1}:其角点不会构成凸形 +@msg image {_1} cannot be distorted this way: its corners would cross the warp's horizon 无法这样扭曲图像 {_1}:其角点会越过扭曲的地平线 +@msg image {_1} cannot be distorted this way: its corners would be too close together for a perspective map 无法这样扭曲图像 {_1}:其角点会太靠近,无法进行透视映射 @msg `background` must be edges, corners or colors `background` 必须为 edges、corners 或 colors @msg `match` must be distance or channels `match` 必须为 distance 或 channels @msg `{key}` must be from 0 to 100 `{key}` 必须介于 0 到 100 之间 @@ -6693,7 +6741,10 @@ lighting Light 光源 @msg the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate) 该对象没有 3D 效果(突出与斜角、回转、膨胀或旋转) @msg `render` must be an object holding only `mode`, set to shaded or wireframe `render` 必须是只含 `mode` 的对象,值为 shaded 或 wireframe @msg its 3D effect builds no solid 其 3D 效果未生成任何实体 -@msg bevel must be none or one of {_1} bevel 必须是 none 或 {_1} 之一 +@msg bevel must be none or one of {_1}, or custom with {BEVEL_PROFILE} bevel 必须是 none、{_1} 之一,或带 {BEVEL_PROFILE} 的 custom +@msg bevel custom needs {BEVEL_PROFILE}, the bevel's points bevel custom 需要 {BEVEL_PROFILE},即斜角的点 +@msg {BEVEL_NAME} must be a string {BEVEL_NAME} 必须是字符串 +@msg {BEVEL_PROFILE} must be 2 to {most} [x, y] points, each share between 0 and 1, from [0, 0] (the cap's edge) to [1, 1] (the side wall) {BEVEL_PROFILE} 必须是 2 到 {most} 个 [x, y] 点,每个比例在 0 到 1 之间,从 [0, 0](端面的边缘)到 [1, 1](侧壁) @msg {_1} can't build solids from this art: its symbol instances, blends and clipping groups hold too many objects {_1}无法从此图稿生成实体:其符号实例、混合和剪切组包含的对象过多 @msg {label} can't build a solid from the instance of symbol "{symbol}": the symbol's art isn't available {label}无法从符号“{symbol}”的实例生成实体:该符号的图稿不可用 @msg {_1}: the clipping path is too complex to cut the art with {_1}:剪切路径过于复杂,无法用来剪切图稿 @@ -10591,6 +10642,20 @@ breakText Glyphs 字形 @msg A joint does not close by {gap} pt. 有一处接缝相差 {gap} pt 未闭合。 @msg Two panels pass through each other. 两个面板相互穿插。 @msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h} 像素对 PSD 而言过大 (每边最多 {MAX_SIDE} 像素):请降低分辨率 + Vector Packs 矢量画笔包 + Compass Rose 罗盘玫瑰 + Botanical Sprig 植物枝条 + Facet Diamond 切面钻石 + Tide Crest 浪尖 + Leaf Vine 叶藤 + Blossom Chain 花链 + Pennant Garland 旗帜花环 + Lantern String 灯笼串 + Orbit Lines 轨道线 + Petal Garland 花瓣花环 + Lattice Braid 格纹编织 + Facet Sweep 切面笔触 + Artistic Brushes 艺术画笔 Paint 绘画 Flat Sweep 平刷 Dry Drag 干拖 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 2e5cb7fcdd..633296c767 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -471,6 +471,11 @@ font-technology Variable 可變 Cusp 尖點 Straight segment 直線段 Circle too large 圓形過大 + Show Radii 顯示半徑 + Show Diameter 顯示直徑 + Anchors at Standard Positions 錨點位於標準位置 + Third Point by Dragging 拖曳放置第三點 + Gray 灰 Classic Defaults 經典預設值 Clean Up… 清除… Clear 清除 @@ -574,9 +579,14 @@ font-technology Variable 可變 {name1} {value1}, {name2} {value2} {name1} {value1},{name2} {value2} Wheel View 色輪檢視 Box View 方塊檢視 + Show Out-of-Gamut Colors 顯示超出色域的顏色 Box Channel 方塊色版 Color box 顏色方塊 Color Wheel Options 色輪選項 + Show Document Colors 顯示文件顏色 + Document Colors 文件顏色 + Selection Colors 所選物件的顏色 +@plural Used {n} time|Used {n} times 使用 {n} 次 Show Harmony 顯示色彩調和 Harmony Rule 色彩調和規則 Harmony color 調和色彩 @@ -620,6 +630,8 @@ font-technology Variable 可變 Contextual Task Bar 快捷工作列 Pin Bar Position 釘選工作列位置 Reset Bar Position 重設工作列位置 + Bar Actions 工作列動作 + Reset Bar Actions 重設工作列動作 Resize 調整大小 Contrast 對比 Control 控制 @@ -1909,6 +1921,10 @@ file-filter Templates 範本 Rename Preset 重新命名預設集 Save Image Trace Preset 儲存影像描圖預設集 Delete Image Trace Preset 刪除影像描圖預設集 + Tracing Presets… 描圖預設集… + Import Image Trace Presets 匯入影像描圖預設集 + Export Image Trace Presets 匯出影像描圖預設集 + Replace the saved presets that have these names? 要取代具有這些名稱的已儲存預設集嗎? Image Trace Presets 影像描圖預設集 Image: 影像: Images: 影像: @@ -2683,6 +2699,8 @@ file-filter Templates 範本 @msg `mode` must be grayscale, rgb, hsb, cmyk or websafe `mode` 必須是 grayscale、rgb、hsb、cmyk 或 websafe @msg `view` must be wheel or box `view` 必須是 wheel 或 box @msg `channel` must be hue, saturation, brightness, red, green or blue `channel` 必須是 hue、saturation、brightness、red、green 或 blue +@msg `sliders` must be none, oklch or hsl `sliders` 必須是 none、oklch 或 hsl +@msg OKLCH needs sRGB as the working RGB space OKLCH 需要將 sRGB 用作 RGB 工作空間 @msg `{key}` must be true or false `{key}` 必須是 true 或 false @msg `top` and `below` can't both be true `top` 和 `below` 不能同時為 true @msg `select` must be true or false `select` 必須是 true 或 false @@ -2714,6 +2732,10 @@ file-filter Templates 範本 @msg no such view 沒有這個檢視 @msg printing isn't available here 此處無法列印 @msg select an image 請選取影像 +@msg object {_1} is an image changed by Perspective Distort or Free Distort, which this command does not work on 物件 {_1} 是經過透視扭曲或隨意扭曲的影像,此指令無法用於它 +@msg image {_1} cannot be distorted this way: its corners would not make a convex shape 無法這樣扭曲影像 {_1}:其角點不會構成凸形 +@msg image {_1} cannot be distorted this way: its corners would cross the warp's horizon 無法這樣扭曲影像 {_1}:其角點會越過扭曲的地平線 +@msg image {_1} cannot be distorted this way: its corners would be too close together for a perspective map 無法這樣扭曲影像 {_1}:其角點會太靠近,無法進行透視對應 @msg `background` must be edges, corners or colors `background` 必須為 edges、corners 或 colors @msg `match` must be distance or channels `match` 必須為 distance 或 channels @msg `{key}` must be from 0 to 100 `{key}` 必須介於 0 到 100 之間 @@ -3339,6 +3361,11 @@ liquify-list-end {0}, {1} {0}和{1} Knife 美工刀 Knockout Group 去底群組 Lab Lab + OKLCH Sliders OKLCH 滑桿 + HSL Sliders HSL 滑桿 + Chroma 色度 + The largest chroma sRGB holds at this lightness and hue sRGB 在此亮度和色相下可容納的最大色度 + OKLCH needs sRGB as the working RGB space OKLCH 需要將 sRGB 用作 RGB 工作空間 Lab Spot Colors: Lab 特別色: Lab Values Lab 值 Landscape 橫向 @@ -4120,6 +4147,13 @@ liquify-list-end {0}, {1} {0}和{1} Pen Tool 筆型工具 Quick Pen Tool 快速筆型工具 Quick Pen 快速筆型 + Quick Pen Toolbar 快速筆型工具列 + Continuous Arc 連續弧線 + Sharp Corner Arc 尖角弧線 + Flip Arc 翻轉弧線 + Hide Toolbar 隱藏工具列 + Pin Toolbar Position 釘選工具列位置 + Reset Toolbar Position 重設工具列位置 Pencil 鉛筆 Pencil Tool 鉛筆工具 per slice 每個切片 @@ -4570,6 +4604,11 @@ digits Malayalam 馬來亞拉姆數字 Edit Arrowheads 編輯箭頭 Edit Arrowheads… 編輯箭頭… Reload Arrowheads 重新載入箭頭 + Bevels 斜角清單 + Edit Bevels 編輯斜角 + Edit Bevels… 編輯斜角… + {name} (document) {name} (文件) + Reload Bevels 重新載入斜角 Rotate View 旋轉檢視 Reset Rotate View 重設旋轉檢視 Rotate View to Selection 依選取範圍旋轉檢視 @@ -4708,9 +4747,13 @@ digits Malayalam 馬來亞拉姆數字 Edit type set in fonts that aren't available? 要編輯使用了無法使用之字體的文字嗎? Shows each slice's number in a box at its top left on the canvas; off, the slice outlines still show. 在畫布上於每個切片左上角的方框中顯示其編號;關閉時,切片輪廓仍會顯示。 The color of user and object slice outlines and their number boxes; auto slices use a dimmer shade of it. 使用者切片和物件切片的輪廓及其編號方框的顏色;自動切片使用此顏色較淡的色調。 + In paragraphs with Hyphenate on, a listed word is hyphenated only at the hyphens typed in it, or never when it has none, whatever its language or case. 在開啟使用連字號的段落中,清單中的單字只在其中輸入的連字號處加上斷字連字號,沒有連字號則從不斷字,與語言和大小寫無關。 + On the desktop, this folder's .wasm plug-ins load at startup and when OK sets a new folder, except in Safe Mode; one that asks for permissions loads only after you grant them. The web version loads none. 在桌面版中,此資料夾中的 .wasm 增效模組會在啟動時以及透過「確定」設定新資料夾時載入,安全模式除外;要求權限的增效模組只在您授予權限後載入。網頁版不載入任何增效模組。 + Large gives each filter or command plug-in run at least 250 million instructions, with the same time limit; Normal keeps the plug-in's own budget. Live effects, exporters and importers keep theirs. 「大」為濾鏡或指令增效模組的每次執行提供至少 2.5 億個指令,時間限制不變;「正常」保留增效模組自己的預算。即時效果、轉存器和匯入器保留各自的預算。 New type takes this language while Document Setup's language is English: USA; type already in a document keeps its own language. 當文件設定的語言為英文:美國時,新文字使用此語言;文件中已有的文字保留自己的語言。 In paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere when it has none, whatever its language or case. 在開啟使用連字號的段落中,清單中的單字只在其中輸入的連字號處斷開,沒有連字號則不斷開,與語言和大小寫無關。 On the desktop, the .wasm plug-ins in this folder load at startup and when you click OK with a new folder here, except in Safe Mode; the web version does not load them. 在桌面版中,此資料夾中的 .wasm 增效模組會在啟動時以及在此指定新資料夾並按一下「確定」時載入,安全模式除外;網頁版不會載入它們。 + Normal keeps each plug-in's own limits; with Large, a plug-in filter or command may run at least 250 million instructions besides those for its input. The time limit stays the same. 「正常」保留每個增效模組自身的限制;選擇「大」時,增效模組的濾鏡或命令除處理其輸入所需的指令外,至少可執行 2.5 億條指令。時間限制不變。 How many instructions each run of a plug-in object filter may use; Large allows more than Normal with the same 60-second limit. Heavy filters keep their own budget. 增效模組的物件濾鏡每次執行可使用的指令數;「大」比「正常」允許更多,60 秒的時間限制不變。重型濾鏡保留自己的預算。 The first scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. 第一個暫存磁碟選擇:Startup、None 或資料夾路徑;VectorCraft 會儲存它,但尚未使用暫存磁碟。 The second scratch disk choice: Startup, None or a folder path; VectorCraft stores it but does not use scratch disks yet. 第二個暫存磁碟選擇:Startup、None 或資料夾路徑;VectorCraft 會儲存它,但尚未使用暫存磁碟。 @@ -4722,13 +4765,15 @@ digits Malayalam 馬來亞拉姆數字 Shows each tool group's name above its tools in the toolbar; off, the groups follow one another with nothing between them. 在工具列中將每個工具組的名稱顯示在其工具上方;關閉此選項時,各組依序排列,中間沒有任何內容。 From now on, documents you open or create open as tabs; off, each opens in a floating window. Documents already open stay where they are. 從現在起,開啟或新增的文件會以分頁開啟;關閉此選項時,每份文件會在浮動視窗中開啟。已開啟的文件保持原位。 Makes the document tabs taller and their names larger. 讓文件頁籤更高,頁籤上的名稱更大。 - From the next start, the system draws the window's title bar where VectorCraft would otherwise draw its own. 從下次啟動起,在 VectorCraft 原本會自行繪製標題列的地方,改由系統繪製視窗的標題列。 - From the next start, VectorCraft draws the window's title bar even where the desktop would draw it, unless System Title Bar is on. 從下次啟動起,即使桌面會繪製視窗的標題列,VectorCraft 也會自行繪製,除非開啟了系統標題列。 + From the next start, the system draws the window's title bar where VectorCraft would otherwise draw its own; on Linux and the BSDs, the VECTORCRAFT_TITLEBAR variable takes precedence. 從下次啟動起,在 VectorCraft 原本會自行繪製標題列的地方,改由系統繪製視窗的標題列;在 Linux 和 BSD 上,VECTORCRAFT_TITLEBAR 變數優先。 + From the next start, VectorCraft draws the window's title bar even where the desktop would draw it, unless System Title Bar is on or the VECTORCRAFT_TITLEBAR variable chooses it. 從下次啟動起,即使桌面會繪製視窗的標題列,VectorCraft 也會自行繪製,除非開啟了系統標題列或 VECTORCRAFT_TITLEBAR 變數選擇了標題列。 Makes the interface larger or smaller; art on the canvas keeps its size at the same zoom. 放大或縮小介面;在相同縮放比例下,畫布上的圖稿保持原有大小。 The tool pointers VectorCraft draws grow and shrink with UI Scaling; off, they keep their size. VectorCraft 繪製的工具指標會隨介面縮放一起變大變小;關閉此選項時,指標保持原有大小。 The language of the interface; Auto uses the system's language. The dialog switches language as soon as you choose one. 介面的語言;「自動」使用系統的語言。選擇一種語言後,對話方塊會立即切換為該語言。 Animated Zoom works only while this is on; off, Animated Zoom is dimmed and zooming does not animate. 只有開啟此選項時,動畫縮放才會起作用;關閉此選項時,動畫縮放會顯示為灰色,縮放不帶動畫。 The wheel's zoom glides in, and the Zoom tool zooms as you drag sideways or hold it down; off, the Zoom tool zooms to the area you drag across. 用滾輪縮放時會平滑過渡,縮放工具在你向側邊拖曳或按住不放時進行縮放;關閉此選項時,縮放工具會縮放到你拖曳過的區域。 + From the next start, the desktop version shows the canvas through this kind of graphics processor; the artwork is drawn on the CPU either way. Automatic prefers the integrated one on Windows and macOS. The web version does not use it. 從下次啟動起,桌面版透過這類圖形處理器顯示畫布;圖稿一律在 CPU 上繪製。「自動」在 Windows 和 macOS 上優先使用內建圖形處理器。網頁版不使用此選項。 + From the next start, the window shows each frame without waiting for the display's refresh where the graphics driver allows, at most 240 frames a second. 從下次啟動起,在圖形驅動程式允許時,視窗顯示每一影格而不等待顯示器重新整理,最多每秒 240 影格。 From the next start, the desktop version draws with this kind of graphics processor; Automatic prefers the one that drives the display. The web version does not use it. 從下次啟動起,桌面版使用這類圖形處理器繪製;「自動」優先使用驅動顯示器的圖形處理器。網頁版不使用此選項。 From the next start, the window shows frames without waiting for the display to refresh, at most 240 a second; off, the display paces them. A present mode set at launch overrides it. 從下次啟動起,視窗不等待顯示器重新整理就顯示畫面,每秒最多 240 格;關閉時由顯示器決定畫面的節奏。啟動時設定的呈現模式優先。 The most undo steps each document keeps; lowering it drops the oldest steps when you click OK. Steps can also go sooner when they use too much memory. 每份文件保留的最大復原步驟數;調低後,按一下「確定」時會刪除最早的步驟。步驟佔用過多記憶體時也可能更早被刪除。 @@ -4747,6 +4792,9 @@ digits Malayalam 馬來亞拉姆數字 Open Recent Files and the Home screen list at most this many recent files; 0 lists none, and VectorCraft still remembers up to 30. 「開啟最近使用的檔案」和首頁畫面最多列出這麼多最近的檔案;設為 0 時不列出,但 VectorCraft 仍會記住最多 30 個。 When a document opens, a linked EPS image that shows its saved preview keeps it instead of reading the EPS file again; changed files still follow Update Links. 開啟文件時,顯示已儲存預視的連結 EPS 影像會保留該預視,而不重新讀取 EPS 檔案;已變更的檔案仍依「更新連結」處理。 In Pixel Preview, images are drawn smoothed; off, their pixels show with hard edges. Outside Pixel Preview, images are always smoothed. 在像素預視中,影像以平滑方式繪製;關閉此選項時,像素邊緣清晰銳利。像素預視以外,影像一律平滑顯示。 + PDF Text PDF 文字 + The text of a PDF you open or embed comes in as editable type, or as outlines that look the same on a computer without its fonts. 開啟或嵌入的 PDF 中的文字會以可編輯文字匯入,或以外框匯入,在沒有其字體的電腦上看起來也相同。 + Linked pages show the file's own text. 連結的頁面顯示檔案本身的文字。 When a linked file changes, Automatically reads it again, Ask When Modified asks you first, and Manually leaves it and shows a note in the status bar. 連結的檔案變更時,「自動」會重新讀取,「修改時詢問」會先詢問您,「手動」則保持不變並在狀態列顯示提示。 On the desktop, the folder New from Template… and Save as Template… start in; leave it blank for VectorCraft Templates in your documents folder. 在桌面版中,「從範本新增…」和「另存範本…」開啟時所在的資料夾;留空則使用文件資料夾中的 VectorCraft Templates。 Edit Original opens a linked file in the system's default app for its type; off, a linked raster image opens in PhotoCraft where it is installed. 「編輯原稿」以系統中該類型的預設應用程式開啟連結的檔案;關閉此選項時,若已安裝 PhotoCraft,連結的點陣影像會在 PhotoCraft 中開啟。 @@ -5006,6 +5054,7 @@ digits Malayalam 馬來亞拉姆數字 Recent Commands 最近使用的指令 No recent commands 沒有最近使用的指令 Type to search commands, tools, panels and effects 輸入以搜尋指令、工具、面板與效果 + Clear Recent Commands 清除最近使用的指令 Search commands 搜尋指令 Search Commands… 搜尋指令… Secondary 次要 @@ -6541,7 +6590,10 @@ lighting Light 光源 @msg the object has no 3D effect (Extrude & Bevel, Revolve, Inflate or Rotate) 此物件沒有 3D 效果 (突出與斜角、迴轉、膨脹或旋轉) @msg `render` must be an object holding only `mode`, set to shaded or wireframe `render` 必須是只含 `mode` 的物件,值為 shaded 或 wireframe @msg its 3D effect builds no solid 其 3D 效果沒有產生任何實體 -@msg bevel must be none or one of {_1} bevel 必須是 none 或 {_1} 其中之一 +@msg bevel must be none or one of {_1}, or custom with {BEVEL_PROFILE} bevel 必須是 none、{_1} 其中之一,或帶有 {BEVEL_PROFILE} 的 custom +@msg bevel custom needs {BEVEL_PROFILE}, the bevel's points bevel custom 需要 {BEVEL_PROFILE},也就是斜角的點 +@msg {BEVEL_NAME} must be a string {BEVEL_NAME} 必須是字串 +@msg {BEVEL_PROFILE} must be 2 to {most} [x, y] points, each share between 0 and 1, from [0, 0] (the cap's edge) to [1, 1] (the side wall) {BEVEL_PROFILE} 必須是 2 到 {most} 個 [x, y] 點,每個比例介於 0 和 1 之間,從 [0, 0](端面的邊緣)到 [1, 1](側壁) @msg {_1} can't build solids from this art: its symbol instances, blends and clipping groups hold too many objects {_1}無法從此圖稿產生實體:其符號實例、漸變和剪裁群組包含的物件過多 @msg {label} can't build a solid from the instance of symbol "{symbol}": the symbol's art isn't available {label}無法從符號「{symbol}」的實例產生實體:該符號的圖稿無法使用 @msg {_1}: the clipping path is too complex to cut the art with {_1}:剪裁路徑過於複雜,無法用來剪裁圖稿 @@ -10406,6 +10458,20 @@ breakText Glyphs 字符 @msg A joint does not close by {gap} pt. 有一處接縫相差 {gap} pt 未閉合。 @msg Two panels pass through each other. 兩個面板相互穿插。 @msg {what} would print on more than {MAX_TILES} tiles: scale it down {what} 會列印在超過 {MAX_TILES} 個拼貼上:請縮小 + Vector Packs 向量筆刷包 + Compass Rose 羅盤玫瑰 + Botanical Sprig 植物枝條 + Facet Diamond 切面鑽石 + Tide Crest 浪尖 + Leaf Vine 葉藤 + Blossom Chain 花鏈 + Pennant Garland 旗幟花環 + Lantern String 燈籠串 + Orbit Lines 軌道線 + Petal Garland 花瓣花環 + Lattice Braid 格紋編織 + Facet Sweep 切面筆觸 + Artistic Brushes 藝術筆刷 Paint 繪畫 Flat Sweep 平刷 Dry Drag 乾拖 diff --git a/crates/ui-egui/src/io/open.rs b/crates/ui-egui/src/io/open.rs index b0a037804f..180c459453 100644 --- a/crates/ui-egui/src/io/open.rs +++ b/crates/ui-egui/src/io/open.rs @@ -35,6 +35,9 @@ fn open_bytes_with(app: &mut VectorcraftApp, name: &str, bytes: &[u8], path: Opt }; return dialogs::script_check::command(app, &p).map(|_| Value::Null); } + if let Some(OpensAs::Presets { import: "imageTrace.presets.import", .. }) = opens { + return dialogs::tracing_presets::open_file(app, bytes).map(|_| Value::Null); + } if let Some(OpensAs::Presets { import, what }) = opens { import_presets(app, import, what, serde_json::json!({"dataBase64": vectorcraft_format::base64_encode(bytes)}))?; return Ok(Value::Null); @@ -108,6 +111,7 @@ pub fn opens_as(name: &str) -> Option { (vectorcraft_engine::cmd::pdfcmds::PRESET_EXTS, "pdf.preset.import", "PDF presets"), (vectorcraft_engine::cmd::printpresets::PRESET_EXTS, "print.presets.import", "print presets"), (vectorcraft_engine::cmd::perspgrid::PRESET_EXTS, "perspective.presets.import", "perspective grid presets"), + (vectorcraft_engine::cmd::TRACE_PRESET_EXTS, "imageTrace.presets.import", "tracing presets"), (fileio::SCREEN_EXPORT_PRESET_EXTS, "document.exportPresets.import", EXPORT_PRESETS), (vectorcraft_engine::cmd::compositefonts::EXTS, "type.compositeFonts.import", "composite fonts"), ]; @@ -133,8 +137,10 @@ pub fn opens_as(name: &str) -> Option { /// Open a document through the engine loader with the `document.open` options in `p` → /// `document.open`'s result, or `{dialog}` when Edit › Color Settings asks about its profile first /// ([`dialogs::profile_mismatch::open_or_ask`]): the document then opens, and goes on the recent -/// files, once the question is answered. +/// files, once the question is answered. A PDF opens with the `pdfTextAs` preference unless `p` +/// gives `textAs` ([`dialogs::import_pdf::with_preferred_text_as`]). pub fn open_document(app: &mut VectorcraftApp, name: &str, bytes: &[u8], path: Option, p: &Value) -> Result { + let p = &dialogs::import_pdf::with_preferred_text_as(app, name, bytes, p); let update_links = app.session.prefs.update_links == "automatically"; let low_res_proxy_eps = app.session.prefs.low_res_proxy_eps; let file = fileio::read_for_open_asking(name, bytes, path.clone(), p, update_links, low_res_proxy_eps, true).map_err(|e| e.to_string())?; @@ -557,6 +563,12 @@ fn open_file_with(app: &mut VectorcraftApp, path: &str, background: bool, p: &Va note_recent(app, path); return Ok(Value::Null); } + // A tracing presets file is read up to its size limit, as Import… reads it. + if let Some(OpensAs::Presets { import: "imageTrace.presets.import", .. }) = opens_as(path) { + dialogs::tracing_presets::open_path(app, path)?; + note_recent(app, path); + return Ok(Value::Null); + } // A file only an importer plug-in reads is not read past the importer's input limit. check_import_size(path, false)?; let mut bytes = read(app, path)?; @@ -570,7 +582,8 @@ fn open_file_with(app: &mut VectorcraftApp, path: &str, background: bool, p: &Va note_recent(app, path); return Ok(Value::Null); } - match crate::opening::start(app, path, bytes) { + let params = crate::dialogs::import_pdf::with_preferred_text_as(app, path, &bytes, &Value::Null); + match crate::opening::start_with(app, path, bytes, params) { Ok(r) => return Ok(r), // No thread: at once. Err(back) => bytes = back, diff --git a/crates/ui-egui/src/io/save.rs b/crates/ui-egui/src/io/save.rs index ff4eba30fb..aa4b565c07 100644 --- a/crates/ui-egui/src/io/save.rs +++ b/crates/ui-egui/src/io/save.rs @@ -154,6 +154,7 @@ const FILE_TYPES: &[(&str, &[&str])] = &[ ("PDF presets", vectorcraft_engine::cmd::pdfcmds::PRESET_EXTS), ("Perspective grid presets", vectorcraft_engine::cmd::perspgrid::PRESET_EXTS), ("Print presets", vectorcraft_engine::cmd::printpresets::PRESET_EXTS), + ("Tracing presets", vectorcraft_engine::cmd::TRACE_PRESET_EXTS), ("Action sets", &[crate::panels::actions::ACTIONS_EXT]), ("Export presets", fileio::SCREEN_EXPORT_PRESET_EXTS), ("Composite fonts", vectorcraft_engine::cmd::compositefonts::EXTS), diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 781b6a9f63..ac5ec6825b 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -49,6 +49,7 @@ mod invoke; mod keyboard; mod labels; mod run; +pub(crate) use run::TRIM_VIEW_HIDES; mod slots; mod state; mod submenus; @@ -82,6 +83,7 @@ pub use run::{check_params, run_ui_command}; pub(crate) use run::{normalize_panel, opt_bool, opt_index, opt_number}; #[cfg(test)] use slots::RECENT_FONT_IDS; +pub(crate) use state::why_off; pub use state::{checked, enabled, plugin_revision, shortcut_of, shown_state}; pub(crate) use submenus::PATH_EFFECTS; pub(crate) use tree::arrange_documents_items; diff --git a/crates/ui-egui/src/menus/context.rs b/crates/ui-egui/src/menus/context.rs index f99bbfef2e..d80b69038b 100644 --- a/crates/ui-egui/src/menus/context.rs +++ b/crates/ui-egui/src/menus/context.rs @@ -270,8 +270,9 @@ fn isolatable(app: &VectorcraftApp, doc: &vectorcraft_doc::Document, n: &vectorc && doc.symbol_edit.as_ref().is_none_or(|e| doc.ancestry(target).is_some_and(|a| a.contains(&e.layer))) } -/// `items` without the commands that can't run now (Undo and Redo stay, greyed out), submenus -/// left empty, and separators that no longer separate anything. +/// `items` without the commands that can't run now (Undo and Redo stay, greyed out, and so do Show +/// Grid and Hide Guides while Trim View holds them off: #8363), submenus left empty, and separators +/// that no longer separate anything. fn prune(app: &VectorcraftApp, items: Vec) -> Vec { let mut out: Vec = Vec::with_capacity(items.len()); for it in items { @@ -280,7 +281,7 @@ fn prune(app: &VectorcraftApp, items: Vec) -> Vec { it => it, }; let keep = match &it { - Item::Cmd(_, id, _) => matches!(*id, "edit.undo" | "edit.redo") || enabled(app, id), + Item::Cmd(_, id, _) => matches!(*id, "edit.undo" | "edit.redo" | "view.guides" | "view.grid") || enabled(app, id), Item::Sub(_, children) => !children.is_empty(), Item::Sep => out.last().is_some_and(|l| !matches!(l, Item::Sep)), _ => true, diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index b6b8977157..8c2767e20b 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -135,6 +135,26 @@ pub fn run_ui_command(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option Option> { let s = |k: &str| p.get(k).and_then(Value::as_str).map(str::to_string); @@ -292,7 +312,12 @@ fn run_ui_part3(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option flag(&mut app.ui.view.pixel_preview), - "view.trimView" => flag(&mut app.ui.view.trim_view), + // Trim View hides the guides while it is on (#8363), and hidden guides cannot stay selected. + "view.trimView" => { + let r = flag(&mut app.ui.view.trim_view); + deselect_hidden_guides(app); + r + } "view.cornerWidget" => flag(&mut app.ui.view.corner_widgets), // Hide/Show Shape Widgets: `on` sets the state, and without it the state flips. "view.shapeWidgets" => opt_bool(p, "on").map(|on| { @@ -403,22 +428,12 @@ fn run_ui_part4(app: &mut VectorcraftApp, id: &str, _p: &Value) -> Option flag(&mut app.ui.view.bounding_box), + // Trim View hides the guides and the grid while it is on, and their Show/Hide items wait + // until it is off (#8363). + "view.guides" | "view.grid" if app.ui.view.trim_view => Err(TRIM_VIEW_HIDES.into()), "view.guides" => { let r = flag(&mut app.ui.view.guides); - // Hidden ruler guides and guide paths cannot stay selected: their selection overlay - // would otherwise reveal geometry that Hide Guides just hid. - let hidden_selection = !app.ui.view.guides - && app.session.active().is_some_and(|d| { - !d.selection.guides.is_empty() - || d.selection - .objects - .iter() - .any(|id| matches!(d.doc.node(*id).map(|n| &n.kind), Some(vectorcraft_doc::NodeKind::Path { guide: true, .. }))) - }); - if hidden_selection { - // Deselecting a document that is open cannot fail. - let _ = app.run("select.none", json!({})); - } + deselect_hidden_guides(app); r } "view.smartGuides" => flag(&mut app.ui.view.smart_guides), @@ -652,6 +667,64 @@ fn run_ui_part6(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option match (s("action").filter(|a| crate::canvas::is_task_bar_action(a)), opt_bool(p, "visible")) { + (None, _) => { + let ids = crate::canvas::TASK_BAR_ACTIONS.iter().map(|a| a.0).chain(crate::canvas::TASK_BAR_CHIPS); + Err(format!("`action` must be one of {}", ids.collect::>().join(", "))) + } + (_, Err(e)) => Err(e), + (Some(action), Ok(visible)) => { + let hidden = &mut app.ui.task_bar_hidden_actions; + let visible = visible.unwrap_or_else(|| hidden.contains(&action)); + if visible { + hidden.remove(&action); + } else { + hidden.insert(action.clone()); + } + Ok(json!({ "action": action, "visible": visible })) + } + }, + // More Options › Reset Bar Actions: every action and chip shows again. + "window.taskBar.resetActions" => Ok(json!(std::mem::take(&mut app.ui.task_bar_hidden_actions))), + "window.quickPenToolbar" => flag(&mut app.ui.quick_pen_bar), + "window.quickPenToolbar.pin" => { + let place = &mut app.ui.quick_pen_bar_place; + opt_bool(p, "pinned").map(|pinned| { + let pinned = pinned.unwrap_or(!place.pinned); + if pinned && !place.pinned { + place.pin_at = place.shown_at; + } + place.pinned = pinned; + json!(pinned) + }) + } + "window.quickPenToolbar.reset" => { + app.ui.quick_pen_bar_place = Default::default(); + Ok(Value::Null) + } + "tool.quickPen.flipArc" => { + // C's flip, for the toolbar's Flip Arc button: false, with nothing changed beyond the + // edit finished first, while the last piece of the path being drawn is not a sharp-corner + // arc. Input held for an edit is finished first, so the key is made now rather than + // held; when that fails the error is returned and the flip is not made. + match app.session.finish_tool_edit() { + Ok(reqs) => crate::canvas::apply_requests(app, Ok(reqs)), + Err(e) => return Some(Err(e.to_string())), + } + let view = app.view_info(); + let key = vectorcraft_tools::ToolKey::Letter('c'); + if app.session.tool_id() != vectorcraft_tools::quickpen::ID || !app.session.tool_claims_key(key, view) { + return Some(Ok(json!(false))); + } + match app.session.tool_key(key, vectorcraft_tools::Mods::default(), view) { + Ok(reqs) => { + crate::canvas::apply_requests(app, Ok(reqs)); + Ok(json!(true)) + } + Err(e) => Err(e.to_string()), + } + } "window.dock" => { let ui = &mut app.ui; // The bars the last Tab hid show again, unless the toolbar or the Control bar was shown @@ -774,8 +847,13 @@ fn run_ui_part7(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option crate::dialogs::safe_mode::open(app), "help.copyTroubleshootingInfo" => crate::troubleshooting::copy(app), "help.commandPalette" => { - app.ui.palette_open = !app.ui.palette_open; - app.ui.palette_query.clear(); + crate::palette::toggle(app); + Ok(Value::Null) + } + // A pick of it in the search is recorded and counted first, and then cleared with the rest. + "help.clearRecentCommands" => { + app.ui.recent_commands.clear(); + app.ui.command_uses = Default::default(); Ok(Value::Null) } // Closing asks Save / Don't Save / Cancel for modified documents first (`unsaved`). @@ -918,6 +996,10 @@ fn run_ui_part9(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option crate::dialogs::trace_presets::open(app, p), + "ui.tracingPresetsDialog" => { + crate::dialogs::tracing_presets::open(app, s("selected").as_deref()); + Ok(Value::Null) + } "ui.flattenerPreview" => crate::panels::flattener_preview::command(app, p), "ui.foldPreview" => crate::addons::packaging::preview::command(app, p), "ui.copyScriptConsole" => crate::panels::script_console::copy(app, p), diff --git a/crates/ui-egui/src/menus/state.rs b/crates/ui-egui/src/menus/state.rs index 5e54c1d651..3fc578d754 100644 --- a/crates/ui-egui/src/menus/state.rs +++ b/crates/ui-egui/src/menus/state.rs @@ -95,6 +95,12 @@ pub fn checked(app: &VectorcraftApp, id: &str, p: &Value) -> Option { "window.taskBar" => app.ui.task_bar, "window.pathfinder.compoundShapes" => app.ui.shape_modes_compound, "window.taskBar.pin" => app.ui.task_bar_place.pinned, + "window.taskBar.actions" => p + .get("action") + .and_then(Value::as_str) + .is_some_and(|a| crate::canvas::is_task_bar_action(a) && !app.ui.task_bar_hidden_actions.contains(a)), + "window.quickPenToolbar" => app.ui.quick_pen_bar, + "window.quickPenToolbar.pin" => app.ui.quick_pen_bar_place.pinned, "window.learn" => crate::panels::learn::visible(&app.ui), "window.panel" => { let panel = p.get("panel").and_then(Value::as_str).unwrap_or(""); @@ -212,22 +218,39 @@ pub(super) fn has_subject(app: &VectorcraftApp) -> bool { /// Can command `id` run now? An engine command asks the engine, a UI command the app's state; /// none that would act on text an input method is still composing. pub fn enabled(app: &VectorcraftApp, id: &str) -> bool { + why_off(app, id).is_none() +} + +/// Why command `id` can't run now ([`enabled`]): `None` while it can, else `Some` with the +/// engine's reason when the engine's check of an engine command fails. The engine's check runs at +/// most once. +pub(crate) fn why_off(app: &VectorcraftApp, id: &str) -> Option> { if waits_for_ime(app, id) { - return false; + return Some(None); } if SUBJECT_COMMANDS.contains(&id) { - return has_subject(app); + return (!has_subject(app)).then_some(None); } // The Artboard tool's canvas menu measured this when it opened. if id == "artboard.deleteEmpty" && let Some(facts) = crate::panels::artboards::open_menu_facts(app) { - return facts.any_empty; + return (!facts.any_empty).then_some(None); } if let Some(c) = vectorcraft_engine::find_command(id) { - // The system clipboard's contents can be pasted with an empty internal clipboard. - return (c.enabled)(&app.session).is_ok() || app.system_paste && id.starts_with("edit.paste"); + return match (c.enabled)(&app.session) { + Ok(()) => None, + // The system clipboard's contents can be pasted into an open document with an empty + // internal clipboard. + Err(_) if app.system_paste && app.session.active().is_some() && id.starts_with("edit.paste") => None, + Err(why) => Some(Some(why)), + }; } + (!ui_enabled(app, id)).then_some(None) +} + +/// Can UI command `id` run now? +fn ui_enabled(app: &VectorcraftApp, id: &str) -> bool { match id { // Save is off for a clean document that already has its own file. "file.save" => app.session.active().is_some_and(|d| d.path.is_none() || d.converted || d.is_dirty()), @@ -269,6 +292,7 @@ pub fn enabled(app: &VectorcraftApp, id: &str) -> bool { "view.rotateToSelection" | crate::addons::arrange::ZOOM => app.session.active().is_some_and(|d| !d.selection.objects.is_empty()), id if id.starts_with("file.openRecent") => recent_slot(app, id).is_some(), "file.clearRecent" => !app.ui.recent_files.is_empty(), + "help.clearRecentCommands" => !app.ui.recent_commands.is_empty() || !app.ui.command_uses.is_empty(), id if id.starts_with("type.recentFont") => { id["type.recentFont".len()..].parse::().is_ok_and(|n| n >= 1 && n <= app.recent_fonts().len()) && app.session.active().is_some() } @@ -347,6 +371,9 @@ pub fn enabled(app: &VectorcraftApp, id: &str) -> bool { "file.exportSelection" => app.session.active().is_some_and(|d| !d.selection.is_empty()), "css.copy" | "css.exportFile" => app.session.active().is_some(), "print.printerSetup" => app.services.print.as_ref().is_some_and(|s| s.has_setup()), + // Trim View hides the guides and the grid while it is on, so their Show/Hide items wait + // until it is off (#8363). + "view.guides" | "view.grid" => !app.ui.view.trim_view, "view.refreshMonitorProfile" => app.session.prefs.monitor_profile_display && app.display_profile.has_reader(), "plugin.dialog" => app.session.active().is_some(), "ui.perspectiveGridDialog" | "ui.savePerspectivePreset" => app.session.active().is_some(), diff --git a/crates/ui-egui/src/menus/tests.rs b/crates/ui-egui/src/menus/tests.rs index 37ae4cba23..fa94c19cd5 100644 --- a/crates/ui-egui/src/menus/tests.rs +++ b/crates/ui-egui/src/menus/tests.rs @@ -1745,3 +1745,43 @@ fn selection_tools_toggle_propagates_a_failed_valid_choice() { } assert_eq!(failures, vec![Err(failure.to_string()), Err(failure.to_string())], "both failed valid choices must reach the command caller"); } + +/// #8363: while Trim View is on, View › Guides › Show/Hide Guides and View › Show/Hide Grid are +/// greyed out (in the menu bar, on their keys and in the canvas context menu, where they stay +/// listed), refuse to run and leave the choices they keep alone; turning it off brings them back. +#[test] +fn trim_view_greys_out_show_guides_and_show_grid() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.ui.view.grid = true; + let listed = |app: &VectorcraftApp, id: &str| { + fn find(items: &[Item], id: &str) -> bool { + items.iter().any(|it| match it { + Item::Cmd(_, c, _) => *c == id, + Item::Sub(_, children) => find(children, id), + _ => false, + }) + } + find(&context_items(app), id) + }; + for id in ["view.guides", "view.grid"] { + assert!(enabled(&app, id), "{id} runs with Trim View off"); + assert!(listed(&app, id), "{id} is in the canvas context menu"); + } + + app.run("view.trimView", json!({})).unwrap(); + for id in ["view.guides", "view.grid"] { + assert!(!enabled(&app, id), "{id} is greyed out while Trim View is on"); + assert!(listed(&app, id), "{id} stays in the canvas context menu, greyed out"); + assert!(app.run(id, json!({})).is_err(), "{id} does not run while Trim View is on"); + } + assert!(app.ui.view.guides && app.ui.view.grid, "the choices stay as they were"); + assert_eq!((checked(&app, "view.grid", &Value::Null), dynamic_label(&app, "view.guides", "Show Guides").as_str()), (Some(true), "Hide Guides")); + + app.run("view.trimView", json!({})).unwrap(); + for id in ["view.guides", "view.grid"] { + assert!(enabled(&app, id), "{id} runs again with Trim View off"); + } + app.run("view.guides", json!({})).unwrap(); + assert!(!app.ui.view.guides); +} diff --git a/crates/ui-egui/src/menus/tree.rs b/crates/ui-egui/src/menus/tree.rs index 5c98b30ad7..3e68b98c92 100644 --- a/crates/ui-egui/src/menus/tree.rs +++ b/crates/ui-egui/src/menus/tree.rs @@ -137,6 +137,7 @@ pub fn menu_tree_named(english_names: bool) -> Vec<(&'static str, Vec)> { c("Transparency Flattener Presets…", "ui.flattenerPresetsDialog"), c("Print Presets…", "ui.printPresetsDialog"), c("PDF Presets…", "ui.pdfPresetsDialog"), + c("Tracing Presets…", "ui.tracingPresetsDialog"), c("Perspective Grid Presets…", "ui.perspectivePresetsDialog"), Sep, c("Color Settings…", "edit.colorSettings"), @@ -684,6 +685,7 @@ pub fn menu_tree_named(english_names: bool) -> Vec<(&'static str, Vec)> { c("Control", "window.control"), c("Help Bar", "window.helpBar"), c("Contextual Task Bar", "window.taskBar"), + c("Quick Pen Toolbar", "window.quickPenToolbar"), c("Tools", "window.toolbar"), sub("Toolbars", crate::custom_toolbars::menu_items()), Sep, diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index f2dcbea689..ad562ecd6c 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -688,6 +688,37 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "{pinned?: bool} keep the Contextual Task Bar where it is instead of following the selection (true), let it follow the selection again from where it is (false) or toggle (omitted), as the bar's More Options menu does; returns the new state", ), ("window.taskBar.reset", "Reset Bar Position", "", "{} unpin the Contextual Task Bar and put it back under the selection"), + ( + "window.taskBar.actions", + "Bar Actions", + "", + "{action: \"imageTrace\"|\"cropImage\"|\"removeBackground\"|\"removeAnchorPoints\"|\"join\"|\"cutPath\"|\"convertToCorner\"|\"convertToSmooth\"|\"group\"|\"makeClippingMask\"|\"unite\"|\"expand\"|\"editClippingPath\"|\"releaseClippingMask\"|\"ungroup\"|\"isolate\"|\"editPath\"|\"releaseCompoundPath\"|\"createOutlines\"|\"convertToPointType\"|\"convertToAreaType\"|\"typeOnPathOptions\"|\"centerOnTop\"|\"centerOnBottom\"|\"dynamicText\"|\"offsetPath\"|\"simplify\"|\"smooth\"|\"duplicate\"|\"drawPencil\"|\"placeImage\"|\"fidelity\"|\"smoothToolOptions\"|\"resizeArtboard\"|\"duplicateArtboards\"|\"rearrangeArtboards\"|\"exportArtboards\"|\"fill\"|\"stroke\"|\"recolor\"|\"lock\"|\"shapeProperties\", visible?: bool} show (true), hide (false) or toggle (omitted or null) one of the Contextual Task Bar's actions or chips, as the bar's More Options › Bar Actions does; an action that is off stays out of the bar and out of More Options, and turning one off changes only the bar; `join` is both Connect and Join; every action starts on; kept with the preferences and with the workspace; another action, or a `visible` that is not true, false or null, is an error and changes nothing; returns {action, visible}", + ), + ( + "window.taskBar.resetActions", + "Reset Bar Actions", + "", + "{} show every Contextual Task Bar action and chip that Bar Actions turned off, as the bar's More Options › Reset Bar Actions does; returns the ids shown again", + ), + ( + "window.quickPenToolbar", + "Quick Pen Toolbar", + "", + "{} show or hide the toolbar the Quick Pen tool shows on the canvas (toggles; returns whether it shows), as Window › Quick Pen Toolbar and the toolbar's More Options › Hide Toolbar do; selecting the Quick Pen tool shows it again", + ), + ( + "window.quickPenToolbar.pin", + "Pin Toolbar Position", + "", + "{pinned?: bool} keep the Quick Pen toolbar where it is in the canvas window instead of following the drawing (true), let it follow the drawing again from where it is (false) or toggle (omitted), as the toolbar's More Options menu does; returns the new state", + ), + ("window.quickPenToolbar.reset", "Reset Toolbar Position", "", "{} unpin the Quick Pen toolbar and put it back beside the drawing"), + ( + "tool.quickPen.flipArc", + "Flip Arc", + "", + "{} flip the last sharp-corner arc of the path the Quick Pen tool is drawing to the other side of its chord, as C and the toolbar's Flip Arc button do, as one undo step; first finishes any pending tool edit (which can change the document), then returns false, changing nothing more, when the Quick Pen tool is not active, no path is being drawn or the last piece is not a sharp-corner arc", + ), ( "window.dock", "Panels", @@ -1001,6 +1032,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ ("help.about", "About VectorCraft", "", "{}"), ("help.checkForUpdates", "Check for Updates…", "", "{}"), ("help.commandPalette", "Search Commands…", "Cmd+Shift+/", "{}"), + ( + "help.clearRecentCommands", + "Clear Recent Commands", + "", + "{} empty the recent picks of Help › Search Commands (the list an empty search shows and the Recent Commands list), the saved list and the pick counts that rank the results; a pick of it is not kept as a recent pick or counted. Not enabled while no picks or counts are saved", + ), ( "help.discover", "VectorCraft Help…", @@ -1139,7 +1176,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "tool.options", "Tool Options…", "", - "{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview; with flares selected, the fields show the first one's settings, `flares` lists them and OK runs shape.editFlare with the settings changed instead, leaving the tool's options), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront, filledLines and lineWidth held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool (the tool whose options show; the Tool row changes it), diameter (pt), intensity and density (1–10), usePressure, method: userDefined|average|random (not used by the Sprayer and the Shifter), showBrush, sprayScrunch, spraySize, spraySpin, sprayScreen, sprayStain and sprayStyle: average|userDefined (the Symbol Sprayer's), proportional and affectsDensity (the Symbol Sizer's), shared by the eight tools; OK runs tool.setOption {tool, values}, after symbol.setDensity from the density the dialog opened with to the new one when symbol sets are selected and it changed), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (px for pencil, paintbrush and smooth, the same at any zoom; pt for blobBrush), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is drawn, and the path's fill and stroke on release), size (pt), angle (°, −180–180; 0) and roundness (%, 1–100; 100) of the eraser's tip; OK runs tool.setOption {tool, values}), livePaintSelection → Live Paint Selection Tool Options (dialog `livePaintSelectionOptions`, fields selectFills and selectStrokes (both on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the highlight's width, 1–20 px; 4); OK runs tool.setOption {tool: \"livePaintSelection\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), livePaintBucket → Live Paint Bucket Options (dialog `livePaintBucketOptions`, fields paintFills (on) and paintStrokes (off), cursorSwatchPreview (on: the active fill or stroke shows above the pointer between the color swatches before and after it; Left and Right without modifiers step it through the color swatches whether it is on or off), highlight (on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the face highlight's width, 1–20 px; 4; an edge's highlight is half as wide); OK runs tool.setOption {tool: \"livePaintBucket\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), shapeBuilder → Shape Builder Tool Options (dialog `shapeBuilderOptions`, fields gapDetection (off), gapLength (pt, 0–72; 3), openFilledAsClosed (on), clickStrokeSplitsPath (off), pickColorFrom: artwork|swatches (artwork), cursorSwatchPreview (off), selection: freeform|straightLine (freeform), highlightFill (on), highlightStroke (on), highlightColor (#rrggbb or a layer color's name; #ff4f4f); OK runs tool.setOption {tool: \"shapeBuilder\", values}; a highlightColor with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), objectsOnPath → Objects on Path Tool Options (dialog `objectsOnPathOptions`, fields pivot (0–8, row by row from the top left; 4, the center) and rotate (°, −360–360; 0); Reset puts 4 and 0 back; Save runs tool.setOption {tool: \"objectsOnPath\", values}: the objects attached next use them, groups attached before keep theirs)", + "{tool: id} what double-clicking a tool button opens: hand → fits the artboard in the window (view.fitArtboard), zoom → 100% (view.actualSize), rotate|scale|reflect|shear → that Object › Transform dialog (dialog `rotate`, `scale`, `reflect` or `shear`; error `nothing selected` without a selection), selection|directSelection|groupSelection → the Move dialog (dialog `move`; the same error), gradient|magicWand → the Gradient or Magic Wand panel (window.panel), artboard → Artboard Options of the active artboard (dialog `artboardOptions`, fields index, name, x, y, width, height, showCenterMark, showCrossHairs; OK runs artboard.setProps, and with other artboards selected with the Artboard tool a new width or height goes to each of them too, in its `artboards` list, each resized about the reference point the form used for that size, or about its top-left corner when the size was set in the fields directly), flare → Flare Tool Options (dialog `flareOptions`, fields diameter and pathLength (pt), opacity, brightness, growth, fuzziness, longest, rayFuzziness, largest (%), rays, rings, direction (°), raysOn, ringsOn; OK runs tool.setOption {tool: \"flare\", values}: the next flare dragged out uses them, and a Flare click's dialog, which also has x, y and preview (on initially), previews one there and accepts it as one Undo step; Cancel rolls back the preview; with flares selected, the fields show the first one's settings, `flares` lists them and OK runs shape.editFlare with the settings changed instead, leaving the tool's options), lineSegment|arc|rectangularGrid|polarGrid → that tool's Tool Options, its click dialog without x and y (dialog kind = the tool id, `__toolOptions: true`; lineSegment: length (pt), angle (°), fillLine; arc: lengthX, lengthY (pt), reference (0–8), arcType: open|closed, baseAlong: x|y, slope (−100…100), fillArc; rectangularGrid: width, height (pt, the Default Size), reference (0–8), rows, columns, rowSkew, columnSkew (%), frame, fill; polarGrid: the same with concentric, radial, concentricSkew, radialSkew and compound for rows, columns, the skews and frame; OK runs tool.setOption {tool, values} and draws nothing: the next drag uses them (Fill Line, the arc's type, base, slope and fill, the grids' dividers, skews and switches) and a click's dialog opens at them), circle → Circle Tool Options (dialog `circleOptions`, fields center, radii, diameter (all on), color (red|blue|magenta|green|black|gray; blue), standardAnchors (on) and dragThird (on); OK runs tool.setOption {tool: \"circle\", values}), columnGraph|stackedColumnGraph|barGraph|stackedBarGraph|lineGraph|areaGraph|scatterGraph|pieGraph|radarGraph → Graph Type for the selected graph, or for the series picked in it with Group Selection (dialog `graphType`, fields the options graph.setType {} returns under their names, with legend, pieLegend, piePosition, pieSort, firstRowInFront, firstColumnInFront, filledLines and lineWidth held for every type; overrideValues and rightOverrideValues, Override Calculated Values of the left or only value axis and of the right one: while one is on OK sends axisMin, axisMax and ticks, or rightAxisMin, rightAxisMax and rightTicks, filled with the calculated values where the graph has none, and one turned off sends null, null and 0; __page: options|valueAxis|rightAxis|categoryAxis, the page shown, options when the type picked has no such page; OK runs graph.setType, and with nothing changed closes without a step of history; an overridden value axis whose maximum is not more than its minimum is an error and the dialog stays open; an error without a selected graph), typeOnPath|verticalTypeOnPath → Type on a Path Options for the selected type on a path (dialog `command` running type.pathOptions; error `nothing selected` without a selection, and the command's error when no type on a path is selected),symbolSprayer|symbolShifter|symbolScruncher|symbolSizer|symbolSpinner|symbolStainer|symbolScreener|symbolStyler → Symbolism Tools Options (dialog `symbolismOptions`, fields tool (the tool whose options show; the Tool row changes it), diameter (pt), intensity and density (1–10), usePressure, method: userDefined|average|random (not used by the Sprayer and the Shifter), showBrush, sprayScrunch, spraySize, spraySpin, sprayScreen, sprayStain and sprayStyle: average|userDefined (the Symbol Sprayer's), proportional and affectsDensity (the Symbol Sizer's), shared by the eight tools; OK runs tool.setOption {tool, values}, after symbol.setDensity from the density the dialog opened with to the new one when symbol sets are selected and it changed), blend → Blend Options, perspectiveGrid → Perspective Grid Options, eyedropper → Eyedropper Options (dialog `eyedropperOptions`, fields sampleSize, pickUp, apply; OK runs eyedropper.setOptions), printTiling → resets the print tiling (print.tiling.set {reset: true}), warp|twirl|pucker|bloat|scallop|crystallize|wrinkle → that tool's Tool Options (dialog `liquifyOptions`, fields tool, width, height, angle, intensity %, usePressure, detail, simplify, simplifyOn, rate, complexity, horizontal %, vertical %, affectAnchors, affectIn, affectOut, showBrush; OK runs tool.setOption {tool, values}), pencil|paintbrush|smooth|blobBrush|eraser → that tool's Tool Options (dialog `freehandOptions`, fields tool and the options the tool keeps: fidelity (px for pencil, paintbrush and smooth, the same at any zoom; pt for blobBrush), fill, keepSelected (on for pencil and paintbrush, off for blobBrush), mergeOnlySelection (off), closeWithin and editWithin (px, 0 is off), livePreview (pencil, on: off draws a thin line while the stroke is drawn, and the path's fill and stroke on release), size (pt), angle (°, −180–180; 0) and roundness (%, 1–100; 100) of the eraser's tip; OK runs tool.setOption {tool, values}), livePaintSelection → Live Paint Selection Tool Options (dialog `livePaintSelectionOptions`, fields selectFills and selectStrokes (both on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the highlight's width, 1–20 px; 4); OK runs tool.setOption {tool: \"livePaintSelection\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), livePaintBucket → Live Paint Bucket Options (dialog `livePaintBucketOptions`, fields paintFills (on) and paintStrokes (off), cursorSwatchPreview (on: the active fill or stroke shows above the pointer between the color swatches before and after it; Left and Right without modifiers step it through the color swatches whether it is on or off), highlight (on), color (the highlight color, #rrggbb or a layer color's name; #ff2a2a), width (the face highlight's width, 1–20 px; 4; an edge's highlight is half as wide); OK runs tool.setOption {tool: \"livePaintBucket\", values}; a color with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), shapeBuilder → Shape Builder Tool Options (dialog `shapeBuilderOptions`, fields gapDetection (off), gapLength (pt, 0–72; 3), openFilledAsClosed (on), clickStrokeSplitsPath (off), pickColorFrom: artwork|swatches (artwork), cursorSwatchPreview (off), selection: freeform|straightLine (freeform), highlightFill (on), highlightStroke (on), highlightColor (#rrggbb or a layer color's name; #ff4f4f); OK runs tool.setOption {tool: \"shapeBuilder\", values}; a highlightColor with an alpha part (#rrggbbaa or #rgba) is an error and OK changes nothing), objectsOnPath → Objects on Path Tool Options (dialog `objectsOnPathOptions`, fields pivot (0–8, row by row from the top left; 4, the center) and rotate (°, −360–360; 0); Reset puts 4 and 0 back; Save runs tool.setOption {tool: \"objectsOnPath\", values}: the objects attached next use them, groups attached before keep theirs)", ), ( "ui.colorGuideOptions", @@ -1313,6 +1350,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{params?: tracing settings (default: the Default preset's), rename?: a saved preset's name} the Image Trace panel's Manage Presets: open Save as New Preset… for those settings, or with `rename`, Rename… for that saved preset (dialog `imageTracePreset`, field `name`: a new \"Tracing Preset N\" or the preset's name); OK runs imageTrace.presets.save with the name (as `newName` when renaming), and the panel shows the preset it made from its settings", ), + ( + "ui.tracingPresetsDialog", + "Tracing Presets…", + "", + "{selected?: preset name (default Default)} open Edit → Tracing Presets (dialog `tracingPresets`, field `selected`): the built-in presets (in brackets, read-only) and the saved ones, with the selected one's settings. New… (from the selected preset) and Edit… (a saved one) open the preset editor (dialog `tracingPreset`, fields `name` and `params`, the tracing settings): OK runs imageTrace.presets.save and returns to Tracing Presets, and a name of a built-in preset, Custom or another saved preset keeps the editor open; Cancel returns with nothing saved. Delete runs imageTrace.presets.delete; Import… runs imageTrace.presets.import, and when saved presets have names in the file, asks (dialog `tracingPresetsReplace`) whether to replace them (OK) or keep them (Cancel); Export… runs imageTrace.presets.export on every saved preset", + ), ( "ui.flattenerPreview", "Flattener Preview", @@ -1562,7 +1605,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.colorWheel", "Color Wheel Options", "", - "{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, harmony?: bool, harmonyRule?: complementary|splitComplementary|leftComplement|rightComplement|analogous|analogous2|triad|tetrad|tetrad2|tetrad3|compound|compound2|highContrast|highContrast3|pentagram, vision?: bool} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, and pick the box's channel, as Box Channel does: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); harmony shows a marker on the wheel's ring for each other color of harmonyRule (the Color Guide's rule of that id; a rule's label is taken too), as Show Harmony and Harmony Rule do, and a click on a marker applies its color; vision shows Show Color Vision Preview's row under the wheel or the box, four chips with the current color as simulated for protanopia, deuteranopia and tritanopia (the simulations of view.proofSetup's protanopia, deuteranopia and tritanopia targets) and for achromatopsia (the gray with the color's CIE L*), each named with its hex value in its tooltip and to screen readers, and taking the keyboard focus; a click or a key on a chip does not apply its color; keys left out or null keep their values ({} reads them), params that are not an object, another key or a value off the list are an error and change nothing, the settings are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel, harmony, harmonyRule, vision}", + "{view?: wheel|box, channel?: hue|saturation|brightness|red|green|blue, sliders?: none|oklch|hsl, gamut?: bool, harmony?: bool, harmonyRule?: complementary|splitComplementary|leftComplement|rightComplement|analogous|analogous2|triad|tetrad|tetrad2|tetrad3|compound|compound2|highContrast|highContrast3|pentagram, vision?: bool, documentColors?: bool} show the Color Wheel panel's wheel or its box, as the panel menu's Wheel View and Box View do, pick the box's channel, as Box Channel does, and show no slider rows under the wheel or the box (none), OKLCH Sliders (oklch) or HSL Sliders (hsl), as the menu items of those names do: the box is a color field with the channel's strip at its right, and the field shows the other two components (hue: saturation across and brightness up; saturation: hue across and brightness up; brightness: hue across and saturation up; red: blue across and green up; green: blue across and red up; blue: red across and green up); OKLCH Sliders edit lightness 0 to 100 %, chroma 0 to 100 % of 0.4 and hue 0 to 360°, CSS Color 4's OKLCH of the display sRGB, and a color outside sRGB keeps L and H and takes the largest chroma that fits; HSL Sliders edit hue 0 to 360°, saturation 0 to 100 % and lightness 0 to 100 %, CSS Color 4's HSL of the display sRGB; gamut true grays out the parts of the wheel's square and the box's field whose colors the CMYK space cannot print (the out-of-gamut warning's test, as color.gamutCheck answers it), as Show Out-of-Gamut Colors does, and false shows them again; the shading is approximate: each cell of a 16 by 16 grid over the square or the field is grayed out or not by the color at its center, so a grayed cell can hold printable colors and a clear cell can hold colors that cannot print; harmony shows a marker on the wheel's ring for each other color of harmonyRule (the Color Guide's rule of that id; a rule's label is taken too), as Show Harmony and Harmony Rule do, and a click on a marker applies its color; vision shows Show Color Vision Preview's row under the wheel or the box, four chips with the current color as simulated for protanopia, deuteranopia and tritanopia (the simulations of view.proofSetup's protanopia, deuteranopia and tritanopia targets) and for achromatopsia (the gray with the color's CIE L*), each named with its hex value in its tooltip and to screen readers, and taking the keyboard focus; a click or a key on a chip does not apply its color; documentColors shows or hides the row the panel menu's Show Document Colors adds under the wheel or the box: the colors color.used {} lists, headed Selection Colors when something is selected and Document Colors otherwise, most used first and as many as fit in one row (a chip's tooltip gives its hex value and how many times the art uses it; a click applies it to the active proxy or to the selected gradient stop, keeping its color model and its link to a global swatch, or to the selected freeform point, which takes the color alone, and Alt+click applies it to the other proxy; the row reads the colors again when the document or the selection changes, not during a drag, and in art with more than 5,000 color uses at most once every half second after an edit); keys left out or null keep their values ({} reads them), params that are not an object, another key or a value off the list are an error and change nothing, oklch is an error while the working RGB space is not sRGB, the settings are kept with the preferences, and the command does not open the panel (window.panel {panel: \"colorWheel\"} does) (ui.inspect: ui.color_wheel) → {view, channel, sliders, gamut, harmony, harmonyRule, vision, documentColors}", ), ( "ui.savePdfDialog", @@ -1890,7 +1933,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.hpglOptionsDialog", "HP-GL Options Dialog", "", - "{path?, useArtboards?, range?, hpglVersion?, curveTolerance?, origin?, pens?, sortPaths?, insideFirst?} open HP-GL Options (dialog `hpglOptions`: fields = these document.export options over the ones used last; pens null is One Pen per Color); OK checks them, remembers them and writes path (else asks). Export As… → HP-GL opens it too", + "{path?, useArtboards?, range?, hpglVersion?, curveTolerance?, origin?, pens?, sortPaths?, insideFirst?} open HP-GL Options (dialog `hpglOptions`: fields = these document.export options over the ones used last; pens null is One Pen per Color); OK checks them, remembers them and writes path (else asks); OK after another document has become active closes the dialog and writes nothing. Export As… → HP-GL opens it too", ), ( "file.saveForWeb", diff --git a/crates/ui-egui/src/palette.rs b/crates/ui-egui/src/palette.rs index 8cda77bb7b..a3c5fed207 100644 --- a/crates/ui-egui/src/palette.rs +++ b/crates/ui-egui/src/palette.rs @@ -319,8 +319,8 @@ pub(crate) struct Entry { names_item: bool, } -/// The last query, the recent picks it was ranked with, and its ranked results. -type Ranked = (String, Vec, Arc<[u32]>); +/// The last query, the recent picks and the pick counts it was ranked with, and its ranked results. +type Ranked = (String, Vec, CommandUses, Arc<[u32]>); /// The palette's entries, the index a query is looked up in, and the last query's ranked results. pub(crate) struct Catalog { @@ -442,9 +442,10 @@ fn build_in(lang: crate::i18n::Lang, native: bool) -> Vec { /// Runs the palette result `id`: selects a tool, or invokes a command with the params its entry /// stands for. A command whose menu bar item gives params runs what a click on that item runs /// ([`crate::shortcut_editor::menu_target_now`]), so Clean Up… and Find and Replace… open their -/// dialogs. While that item is dimmed, no dialog opens and the status line says why the command -/// can't run. A panel's result shows the panel, and an effect's result runs what its Effect menu -/// item runs ([`crate::keymap::command_of`]). Returns what the pick did. +/// dialogs. While a result is dimmed ([`unavailable`]), its pick runs nothing, opens no dialog or +/// panel, and the status line says why the command can't run. A panel's result shows the panel, +/// and an effect's result runs what its Effect menu item runs ([`crate::keymap::command_of`]). +/// Returns what the pick did. pub(crate) fn run_pick(app: &mut VectorcraftApp, id: &str) -> Picked { let had_dialog = app.ui.dialog.is_some(); let ran = if let Some(tool) = id.strip_prefix("tool:") { @@ -470,17 +471,15 @@ pub(crate) fn run_pick(app: &mut VectorcraftApp, id: &str) -> Picked { } } else if id.starts_with("plugin:") || id.starts_with("effect:") { let command = crate::keymap::command_of(id); - let on = menus::enabled(app, &command.id); - // While the Effect menu dims the item (nothing selected), no dialog opens and the status - // line says why. - if id.starts_with("effect:") && !on { - if let Err(why) = crate::shortcut_editor::dimmed(app, &command.id) { - app.status(why); - } + // While the item is dimmed (an effect with nothing selected), no dialog opens and the + // status line says why. + if let Some(why) = crate::shortcut_editor::dimmed(app, &command.id, &command.id) { + app.status(why); + false } else { menus::invoke(app, &command.id, command.params); + true } - on } else { match crate::shortcut_editor::menu_target_now(app, id) { Some(Ok((id, p))) => { @@ -491,13 +490,18 @@ pub(crate) fn run_pick(app: &mut VectorcraftApp, id: &str) -> Picked { app.status(why); false } - None => { - // The command is invoked while its menu item is dimmed too, and its own check - // reports why it can't run. - let on = menus::enabled(app, id); - menus::invoke(app, id, json!({})); - on - } + // A dimmed result does not run: the Asset Export commands with no document open show + // no panel. + None => match crate::shortcut_editor::dimmed(app, id, id) { + Some(why) => { + app.status(why); + false + } + None => { + menus::invoke(app, id, json!({})); + true + } + }, } }; // A dimmed command that still opens its dialog counts as opening it. @@ -522,19 +526,97 @@ pub(crate) enum Picked { Refused, } -/// The entries the query `q` matches, best first ([`search::rank`]), with the picks that Recent -/// Commands lists for the ids `recent_ids` ([`recent`]) first among the entries that match as well. -/// The ranking of the last query is kept, so a frame that draws the same query with the same recent -/// picks does not rank again. [`show`] lists the first [`MAX_RESULTS`] and counts the rest. -fn matching<'a>(catalog: &'a Catalog, q: &str, recent_ids: &[String]) -> Vec<&'a Entry> { +/// Why the result `id`, shown as `name`, can't run now, as an English status message, or `None` +/// while it can: the status line a pick of its dimmed menu item gives +/// ([`crate::shortcut_editor::dimmed`]), with the engine's reason when it gives one and `name` in +/// place of the command's id. A panel can't be shown in Presentation Mode, a tool can always be +/// chosen, and every other result asks about the command its pick runs. +fn unavailable(app: &VectorcraftApp, id: &str, name: &str) -> Option { + if id.starts_with("tool:") { + return None; + } + if id.starts_with("panel:") && app.ui.screen_mode >= 3 { + return Some("panels can't be shown in Presentation Mode".to_string()); + } + // The command the pick runs. + let id = if id.starts_with("panel:") || id.starts_with("plugin:") || id.starts_with("effect:") { + crate::keymap::command_of(id).id + } else { + id.to_string() + }; + crate::shortcut_editor::dimmed(app, &id, name) +} + +/// The drawn results' [`unavailable`] answers for the state `key` ([`availability_key`]) they were +/// read in. An engine check can take tens of milliseconds on a large selection, so each result is +/// asked once per state instead of on every frame. +#[derive(Clone, Default)] +struct Availability { + key: u64, + /// Each asked result's answer: why it can't run now, in English, or `None` while it can. + known: std::collections::HashMap>, + /// How many results were asked since the key was set. + #[cfg(test)] + asked: usize, +} + +impl Availability { + /// Why the result `e` can't run now, in the interface language, or `None` while it can. + fn why(&mut self, app: &VectorcraftApp, e: &Entry) -> Option { + let why = match self.known.get(&e.id) { + Some(why) => why.clone(), + None => { + #[cfg(test)] + { + self.asked += 1; + } + let why = unavailable(app, &e.id, &e.shown); + self.known.insert(e.id.clone(), why.clone()); + why + } + }; + why.map(|why| crate::i18n::msg(&why)) + } +} + +/// What the results' availability depends on: what the native menu bar's rows depend on +/// ([`crate::native_menu::state_hash`]: commands run, the document's revision, selection, history +/// and clipboard, the language and more), whether the document has unsaved changes, the screen +/// mode, an open dialog, and the background saves and exports, file reads, plug-in runs and traces +/// that run or show their progress. A click asks again for what it leaves out (a panel shown, a +/// tool chosen) without changing it ([`show`]); typing in the search field does not. +fn availability_key(app: &VectorcraftApp) -> u64 { + use std::hash::{Hash, Hasher}; + let mut h = std::collections::hash_map::DefaultHasher::new(); + crate::native_menu::state_hash(app, None).hash(&mut h); + let running = app.background.jobs.iter().filter(|j| j.progress.is_some() && !j.cancelled()).count(); + (app.ui.screen_mode, app.ui.dialog.is_some(), app.background.jobs.len(), running).hash(&mut h); + (app.opening.pending.len(), crate::opening::any_shown(app)).hash(&mut h); + // A background save marks the document saved without a new revision. + app.session.active().map(|d| (d.path.is_some(), d.converted, d.is_dirty())).hash(&mut h); + let plugins = (crate::plugin_runs::any_running(app), crate::plugin_runs::any_shown(app)); + (plugins, crate::trace_runs::any_running(app), crate::trace_runs::any_shown(app)).hash(&mut h); + h.finish() +} + +/// The entries the query `q` matches, best first ([`search::rank`]), with the commands picked most +/// often (`uses`) first among the entries that match as well, and then the picks that Recent +/// Commands lists for the ids `recent_ids` ([`recent`]). The ranking of the last query is kept, so +/// a frame that draws the same query with the same counts and recent picks does not rank again. +/// [`show`] lists the first [`MAX_RESULTS`] and counts the rest. +fn matching<'a>(catalog: &'a Catalog, q: &str, recent_ids: &[String], uses: &CommandUses) -> Vec<&'a Entry> { let q = search::normalize(q); let picks: Vec = recent_places(&catalog.list, recent_ids).into_iter().filter_map(|i| u32::try_from(i).ok()).collect(); - let kept = catalog.ranked.lock().ok().and_then(|last| last.as_ref().filter(|(k, p, _)| *k == q && *p == picks).map(|(_, _, r)| r.clone())); + let kept = catalog + .ranked + .lock() + .ok() + .and_then(|last| last.as_ref().filter(|(k, p, c, _)| *k == q && *p == picks && c == uses).map(|(_, _, _, r)| r.clone())); let ranked = kept.unwrap_or_else(|| { - let ranked: Arc<[u32]> = search::rank(&catalog.list, &catalog.index, &q, &picks).into(); + let ranked: Arc<[u32]> = search::rank(&catalog.list, &catalog.index, &q, &picks, &uses.grades(&catalog.list)).into(); // A poisoned lock only loses the kept ranking: the next frame ranks again. if let Ok(mut last) = catalog.ranked.lock() { - *last = Some((q, picks, ranked.clone())); + *last = Some((q, picks, uses.clone(), ranked.clone())); } ranked }); @@ -1065,6 +1147,132 @@ fn recent_places(entries: &[Entry], ids: &[String]) -> Vec { .collect() } +/// How many command ids [`CommandUses`] counts at most. +const MAX_COUNTED_COMMANDS: usize = 200; + +/// The count at which [`CommandUses::count`] halves every count. +const HALVING_COUNT: u32 = 1_000; + +/// How many times each command was picked in the palette: commands picked often rank first among +/// the results that match a query as well ([`matching`]). It counts at most +/// [`MAX_COUNTED_COMMANDS`] ids. When a count reaches [`HALVING_COUNT`], every count is halved, so +/// a count is at most 999. +#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize)] +pub struct CommandUses { + /// The number of the last pick; each pick takes the next one. + pick: u32, + /// For each command id, its count and the number of its last pick. + uses: std::collections::BTreeMap, +} + +impl CommandUses { + /// Counts a pick of `id`. A new id when [`MAX_COUNTED_COMMANDS`] are counted first removes + /// one id from the half of the ids picked longest ago: the one with the lowest count, of those + /// the one picked longest ago. It then counts once. When the pick number is at its limit, the + /// counted ids' pick numbers are first renumbered from 1 in their order ([`renumbered`]), so + /// the pick still takes a number above all of them. + pub(crate) fn count(&mut self, id: &str) { + if self.pick == u32::MAX { + let lasts: Vec = self.uses.values().map(|&(_, last)| u64::from(last)).collect(); + for ((_, last), number) in self.uses.values_mut().zip(renumbered(&lasts)) { + *last = number; + } + self.pick = self.uses.values().map(|&(_, last)| last).max().unwrap_or(0); + } + self.pick = self.pick.saturating_add(1); + let pick = self.pick; + if let Some((n, last)) = self.uses.get_mut(id) { + *n = n.saturating_add(1); + *last = pick; + } else { + if self.uses.len() >= MAX_COUNTED_COMMANDS { + let mut by_age: Vec<(u32, u32, &String)> = self.uses.iter().map(|(k, &(n, last))| (last, n, k)).collect(); + by_age.sort_unstable(); + let older = by_age.len().div_ceil(2); + if let Some(least) = by_age.iter().take(older).min_by_key(|&&(last, n, _)| (n, last)).map(|&(_, _, k)| k.clone()) { + self.uses.remove(&least); + } + } + self.uses.insert(id.to_string(), (1, pick)); + } + if self.uses.get(id).is_some_and(|&(n, _)| n >= HALVING_COUNT) { + for (n, _) in self.uses.values_mut() { + *n /= 2; + } + self.uses.retain(|_, (n, _)| *n > 0); + } + } + + /// Whether no command is counted. + pub(crate) fn is_empty(&self) -> bool { + self.uses.is_empty() + } + + /// The count of `id`'s picks as a grade from 0 (never picked) to 9: the base-2 logarithm of + /// the count plus one, so 1 pick gives 1, 3 give 2, 7 give 3, and so on. + fn grade(&self, id: &str) -> u8 { + self.uses.get(id).map_or(0, |&(n, _)| u8::try_from(n.min(HALVING_COUNT - 1).saturating_add(1).ilog2()).unwrap_or(u8::MAX)) + } + + /// The grade ([`CommandUses::grade`]) of each of `entries`, in their order, or none when no + /// command was picked. + fn grades(&self, entries: &[Entry]) -> Vec { + if self.uses.is_empty() { + return vec![]; + } + entries.iter().map(|e| self.grade(&e.id)).collect() + } +} + +/// The pick numbers `lasts` renumbered from 1 in their order, in the order of `lasts`: equal +/// numbers stay equal, and the lowest becomes 1. +fn renumbered(lasts: &[u64]) -> Vec { + let mut distinct = lasts.to_vec(); + distinct.sort_unstable(); + distinct.dedup(); + lasts.iter().map(|last| u32::try_from(distinct.partition_point(|d| d < last) + 1).unwrap_or(u32::MAX)).collect() +} + +/// Serde reader for the saved pick counts ([`crate::UiState::command_uses`]): an entry that is not +/// a pair of counts is dropped, a count above 999 reads as 999, and of more than +/// [`MAX_COUNTED_COMMANDS`] ids the ones picked most recently are kept. When a kept pick number or +/// the last pick number is above the largest the counts hold, the kept pick numbers are +/// renumbered from 1 in their order ([`renumbered`]). Anything else reads as no picks, so an +/// unknown value doesn't lose the rest of the preferences. +pub fn deserialize_command_uses<'de, D: serde::Deserializer<'de>>(d: D) -> Result { + use std::cmp::Reverse; + let v = ::deserialize(d)?; + let number = |v: Option<&serde_json::Value>| v.and_then(serde_json::Value::as_u64); + // The heap holds at most MAX_COUNTED_COMMANDS + 1 entries, the least recent pick on top (of + // equal picks, the id that sorts last), so a long saved list is not collected whole. Pick + // numbers are compared as saved, before any is renumbered. + let mut kept: std::collections::BinaryHeap, u32)>> = std::collections::BinaryHeap::new(); + for (id, u) in v.get("uses").and_then(serde_json::Value::as_object).into_iter().flatten() { + let (Some(n), Some(last)) = (number(u.get(0)), number(u.get(1))) else { continue }; + if n == 0 || !u.as_array().is_some_and(|a| a.len() == 2) { + continue; + } + let n = u32::try_from(n.min(u64::from(HALVING_COUNT - 1))).unwrap_or(HALVING_COUNT - 1); + kept.push(Reverse((last, Reverse(id), n))); + if kept.len() > MAX_COUNTED_COMMANDS { + kept.pop(); + } + } + let kept: Vec<(&String, u32, u64)> = kept.into_iter().map(|Reverse((last, Reverse(id), n))| (id, n, last)).collect(); + // The pick number stays above every saved last pick, so the next pick is the most recent. + let newest = kept.iter().map(|&(_, _, last)| last).max().unwrap_or(0); + let pick = number(v.get("pick")).unwrap_or(0).max(newest); + if let Ok(pick) = u32::try_from(pick) { + let uses = kept.into_iter().map(|(id, n, last)| (id.clone(), (n, u32::try_from(last).unwrap_or(pick)))).collect(); + return Ok(CommandUses { pick, uses }); + } + let lasts: Vec = kept.iter().map(|&(_, _, last)| last).collect(); + let uses: std::collections::BTreeMap = + kept.into_iter().zip(renumbered(&lasts)).map(|((id, n, _), last)| (id.clone(), (n, last))).collect(); + let pick = uses.values().map(|&(_, last)| last).max().unwrap_or(0); + Ok(CommandUses { pick, uses }) +} + /// The id of the Recent Commands list's popup. fn recent_list_id() -> egui::Id { egui::Id::unique("palette-recent-commands") @@ -1075,6 +1283,13 @@ pub(crate) fn recent_list_open(ctx: &egui::Context) -> bool { egui::Popup::is_id_open(ctx, recent_list_id()) } +/// Opens the palette with an empty search when it is closed, and closes it when it is open. +pub(crate) fn toggle(app: &mut VectorcraftApp) { + app.ui.palette_open = !app.ui.palette_open; + app.ui.palette_query.clear(); + app.ui.palette_toggled = true; +} + pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { // The widget that had the keyboard focus when the palette opened takes it back when the palette // closes, unless a modal window is up (a pick opened a dialog, which focuses its own first @@ -1083,6 +1298,12 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { let focus_id = egui::Id::unique("palette-focus-before"); let field_id = egui::Id::unique("palette-field"); let sel_id = egui::Id::unique("palette-selected"); + let availability_id = egui::Id::unique("palette-availability"); + // A toggle can close the palette and open it again before it is drawn closed, as two runs of its + // command in one step do, so the palette forgets its highlight after any toggle. + if std::mem::take(&mut app.ui.palette_toggled) { + ctx.data_mut(|d| d.remove::(sel_id)); + } // The Recent Commands rows drawn in the last frame, so a pick with the keyboard, which leaves the // focus on its row, gives the focus back too. let rows_id = egui::Id::unique("palette-recent-rows"); @@ -1100,9 +1321,11 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { } if !app.ui.palette_open { // The palette opens again with its first row highlighted and its list scrolled to the top - // (a list height of 0 scrolls it to the highlighted row). + // (a list height of 0 scrolls it to the highlighted row), and asks its results again + // whether they can run. let (field, rows) = ctx.data_mut(|d| { d.remove::(sel_id); + d.remove::(availability_id); let field = d.get_temp::(field_id); d.remove::(field_id); let rows = d.get_temp::>(rows_id).unwrap_or_default(); @@ -1129,7 +1352,7 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { let recent = recent(&entries.list, &app.ui.recent_commands); // An empty search lists the recent picks, most recent first, so Enter runs the last pick again. let empty = app.ui.palette_query.trim().is_empty(); - let mut matches = if empty { recent.clone() } else { matching(&entries, &q, &app.ui.recent_commands) }; + let mut matches = if empty { recent.clone() } else { matching(&entries, &q, &app.ui.recent_commands, &app.ui.command_uses) }; let total = matches.len(); // The highlighted result (#1757): Up and Down move it (wrapping), Page Up and Page Down move it // by a page, the pointer over a result takes it, and a new query starts again from the first. @@ -1205,6 +1428,16 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { }); } let screen = ctx.content_rect(); + // The drawn results' availability, kept while the state it was read in lasts. A frame with a + // pointer button release asks again, once, for what the state leaves out. + let key = availability_key(app); + let mut availability = ctx + .data_mut(|d| d.remove_temp::(availability_id)) + .filter(|a| a.key == key) + .unwrap_or_else(|| Availability { key, ..Default::default() }); + if ctx.input(|i| i.events.iter().any(|e| matches!(e, egui::Event::PointerButton { pressed: false, .. }))) { + availability.known.clear(); + } // The highlighted result the rows and the field's description are drawn with. let mut drawn = sel; // The control that shows where the highlighted result lives, the callout's text, and how the @@ -1251,7 +1484,25 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { ui.add_enabled(false, egui::Button::new(tl!("No recent commands"))); } for (i, e) in recent.iter().enumerate() { - let row = ui.add(egui::Button::new(e.shown.as_str()).shortcut_text(menus::shown_shortcut(&e.shortcut))); + // A pick that can't run now is drawn dimmed, as in the results, and says + // why on hover and to screen readers; it can still be chosen. + let why = availability.why(app, e); + let (name, shortcut) = (egui::RichText::new(e.shown.as_str()), egui::RichText::new(menus::shown_shortcut(&e.shortcut))); + let (name, shortcut) = match why { + Some(_) => (name.color(t.text_disabled), shortcut.color(t.text_disabled)), + None => (name, shortcut), + }; + let row = ui.add(egui::Button::new(name).shortcut_text(shortcut)); + ui.ctx().accesskit_node_builder(row.id, |node| { + if let Some(why) = &why { + node.set_disabled(); + node.set_description(why.clone()); + } + }); + let row = match why { + Some(why) => row.on_hover_text(why), + None => row, + }; rows.push(row.id); if i == rsel { row.request_focus(); @@ -1285,14 +1536,18 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { // keep the highlighted result in view. let resized = (view - last_view).abs() > 0.5; // Screen readers stay on the field: its description names the highlighted result and - // its place among every match, as the footer counts them. + // its place among every match, as the footer counts them, and on a second line why it + // can't run now when it can't. let mut described = None; if let Some(e) = matches.get(sel) { let rank = if sel + 1 == matches.len() { kept.unwrap_or(sel) } else { sel }; let pos = (rank + 1).to_string(); let of = total.to_string(); let name = row_label(e, &home_text(app, e)); - let said = crate::i18n::fmt(tl!("{pos} of {total}: {name}"), &[("pos", &pos), ("total", &of), ("name", &name)]); + let mut said = crate::i18n::fmt(tl!("{pos} of {total}: {name}"), &[("pos", &pos), ("total", &of), ("name", &name)]); + if let Some(why) = availability.why(app, e) { + said = format!("{said}\n{why}"); + } described = Some(said.clone()); ui.ctx().accesskit_node_builder(r.id, |node| node.set_description(said)); } @@ -1316,32 +1571,46 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { if on { ui.painter().rect_filled(rect, 4.0, ui.visuals().selection.bg_fill); } + // A result that can't run now stays in its place, drawn dimmed, and says + // why on hover and to screen readers. + let why = availability.why(app, e); + let (name_color, shortcut_color) = if why.is_some() { (t.text_disabled, t.text_disabled) } else { (t.text, t.text_dim) }; let font = egui::TextStyle::Body.resolve(ui.style()); let shortcut = menus::shown_shortcut(&e.shortcut); let home = home_text(app, e); let said = row_label(e, &home); let p = ui.painter(); let shortcut_at = rect.right_center() - egui::vec2(8.0, 0.0); - let used = p.text(shortcut_at, egui::Align2::RIGHT_CENTER, &shortcut, font.clone(), t.text_dim); + let used = p.text(shortcut_at, egui::Align2::RIGHT_CENTER, &shortcut, font.clone(), shortcut_color); let name_end = if shortcut.is_empty() { rect.right() - 8.0 } else { used.left() - 12.0 }; let icon = egui::Rect::from_center_size( egui::pos2(rect.left() + 8.0 + KIND_ICON / 2.0, rect.center().y), egui::Vec2::splat(KIND_ICON), ); - crate::icons::paint(ui, kind_of(e).0, icon, t.icon); + crate::icons::paint(ui, kind_of(e).0, icon, if why.is_some() { t.text_disabled } else { t.icon }); let name_at = icon.right() + 6.0; - let (label, home, cut) = row_galleys(p, e, &home, font, t.text, t.text_dim, name_end - name_at); + let home_color = if why.is_some() { t.text_disabled } else { t.text_dim }; + let (label, home, cut) = row_galleys(p, e, &home, font, name_color, home_color, name_end - name_at); let home_at = name_at + label.size().x + 10.0; - p.galley(egui::pos2(name_at, rect.center().y - label.size().y / 2.0), label, t.text); + p.galley(egui::pos2(name_at, rect.center().y - label.size().y / 2.0), label, name_color); if let Some(home) = home { - p.galley(egui::pos2(home_at, rect.center().y - home.size().y / 2.0), home, t.text_dim); + p.galley(egui::pos2(home_at, rect.center().y - home.size().y / 2.0), home, home_color); } // A row whose text is cut short shows all of it while the pointer rests on it. let resp = if cut { resp.on_hover_text(said.clone()) } else { resp }; // `WidgetInfo::selected` reaches screen readers as a toggled state, so the // row sets the selected state on its node itself. - resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::ListItem, true, said.clone())); - ui.ctx().accesskit_node_builder(resp.id, |node| node.set_selected(on)); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::ListItem, why.is_none(), said.clone())); + ui.ctx().accesskit_node_builder(resp.id, |node| { + node.set_selected(on); + if let Some(why) = &why { + node.set_description(why.clone()); + } + }); + let resp = match why { + Some(why) => resp.on_hover_text(why), + None => resp, + }; if resp.clicked() { run = Some(e.id.clone()); } @@ -1356,6 +1625,9 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { } }); } + // While the highlighted result can't run now, the footer also says why, so a keyboard + // user reads it too, in place of the line that names its home. + let why = matches.get(sel).and_then(|e| availability.why(app, e)); // The highlighted result's home, after a pointer or a scroll moved the highlight too. In // the pass that opens the palette, the menu bar and the toolbars have noted nothing yet, // and the next pass shows it. @@ -1377,7 +1649,12 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { && let Some(said) = &described && !said.contains(text.as_str()) { - let said = format!("{said}, {text}"); + // The text goes on the first line, before the line that says why the + // result can't run now. + let said = match said.split_once('\n') { + Some((first, why)) => format!("{first}, {text}\n{why}"), + None => format!("{said}, {text}"), + }; ui.ctx().accesskit_node_builder(r.id, |node| node.set_description(said)); } pointed = Some((place, text, how)); @@ -1385,9 +1662,11 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { Some(Pointer::Footer(text)) => hint = Some(text), None => {} } - // Under the recent picks no count is shown, only where the highlighted pick's home is when - // no callout shows it; with no picks, one dimmed line says what a search finds. - if !empty || (n > 0 && hint.is_some()) { + // Under the recent picks no count is shown, only why the highlighted pick can't run now, + // or where its home is when no callout shows it; with no picks, one dimmed line says + // what a search finds. + let line = why.or(hint); + if !empty || (n > 0 && line.is_some()) { ui.add_space(6.0); ui.scope(|ui| { // The footer stays one line of text tall, as the list's height counts it. @@ -1396,8 +1675,8 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { if !empty { ui.label(egui::RichText::new(footer(n, total)).color(t.text_dim)); } - if let Some(hint) = hint { - ui.add(egui::Label::new(egui::RichText::new(hint).color(t.text_dim)).truncate()); + if let Some(line) = line { + ui.add(egui::Label::new(egui::RichText::new(line).color(t.text_dim)).truncate()); } }); }); @@ -1405,12 +1684,20 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { ui.add_space(6.0); ui.label(egui::RichText::new(tl!("Type to search commands, tools, panels and effects")).color(t.text_dim)); } - if !list_open - && !history_focused - && ui.input(|i| i.key_pressed(egui::Key::Enter)) - && let Some(e) = matches.get(sel) - { - run = Some(e.id.clone()); + if !list_open && !history_focused && ui.input(|i| i.key_pressed(egui::Key::Enter)) { + // Text typed in the frame that pressed Enter changed the query after the results + // were listed: Enter runs the first result of the new query. + let typed = app.ui.palette_query.to_lowercase(); + let picked = if typed == q { + matches.get(sel).copied() + } else if typed.trim().is_empty() { + recent.first().copied() + } else { + matching(&entries, &typed, &app.ui.recent_commands, &app.ui.command_uses).first().copied() + }; + if let Some(e) = picked { + run = Some(e.id.clone()); + } } }); }); @@ -1453,23 +1740,35 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { ctx.request_repaint(); } let sel_key = matches.get(sel).map(|e| e.id.clone()).unwrap_or_default(); + // A palette that closes on this frame forgets its highlight and its answers here, as a closed + // frame does, so a command that opens it again before that frame starts it afresh. + let closing = run.is_some() || outside; ctx.data_mut(|d| { - d.insert_temp::(sel_id, (sel, q, offset, view, sel_key)); + if closing { + d.remove::(sel_id); + d.remove::(availability_id); + } else { + d.insert_temp::(sel_id, (sel, q, offset, view, sel_key)); + d.insert_temp(availability_id, availability); + } d.insert_temp(rsel_id, rsel); }); if let Some(id) = run { app.ui.palette_open = false; // A pick goes first in Recent Commands before it runs, and stays there when it ran or // opened a dialog, even when the dialog is then canceled. A refused pick puts the list - // back as it was. - let before = (id != PALETTE_TOGGLE).then(|| app.ui.recent_commands.clone()); + // back as it was. The pick is counted with it, before it runs, so Clear Recent Commands + // clears its own pick and count, and a refused pick puts the counts back too. + let before = (id != PALETTE_TOGGLE).then(|| (app.ui.recent_commands.clone(), app.ui.command_uses.clone())); if before.is_some() { remember(&mut app.ui.recent_commands, &id, |c| entries.list.iter().any(|e| e.id == c)); + app.ui.command_uses.count(&id); } if run_pick(app, &id) == Picked::Refused - && let Some(before) = before + && let Some((recent, uses)) = before { - app.ui.recent_commands = before; + app.ui.recent_commands = recent; + app.ui.command_uses = uses; } } else if outside { app.ui.palette_open = false; @@ -1486,6 +1785,11 @@ mod tests { use super::*; use crate::i18n::Lang; + /// The entries `q` matches, best first, with the recent picks `recent_ids` and no pick counts. + fn matching<'a>(catalog: &'a Catalog, q: &str, recent_ids: &[String]) -> Vec<&'a Entry> { + super::matching(catalog, q, recent_ids, &CommandUses::default()) + } + #[test] fn entries_are_built_once_per_language_and_match_english_shown_text_and_ids() { let ctx = egui::Context::default(); @@ -1644,6 +1948,22 @@ mod tests { } } + /// With no document open, the Asset Export commands are dimmed, and a pick of one shows no panel + /// and says why it can't run, as the row's description does. + #[test] + fn a_dimmed_asset_export_command_does_not_open_its_panel() { + let ids = ["assets.export", "assets.remove", "assets.rename", "assets.settings.set", "assets.export3D", "assets.set3DFormat"]; + for id in ids { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + let why = unavailable(&app, id, id); + assert!(why.is_some(), "{id} is dimmed with no document open"); + app.ui.status.clear(); + run_pick(&mut app, id); + assert!(!crate::panel_docking::showing(&app.ui, crate::panels::asset_export::ID), "{id}: {}", app.ui.status); + assert_eq!(Some(app.ui.status.clone()), why, "{id}"); + } + } + /// The open dialog's kind and fields, the active document's undo depth and the status line. type Outcome = (Option<(String, serde_json::Map)>, Option, String); @@ -1823,6 +2143,10 @@ mod tests { remember(&mut list, id, |_| true); } assert_eq!(list, ["j", "i", "h", "g", "f", "e", "d", "c"]); + // A palette toggle saved before its picks were left out takes none of the eight places. + let mut list: Vec = [PALETTE_TOGGLE, "a", "b", "c", "d", "e", "f", "g"].map(str::to_string).into(); + remember(&mut list, "h", |_| true); + assert_eq!(list, ["h", "a", "b", "c", "d", "e", "f", "g"]); let entries = build(Lang::EN); let many: Vec = entries.iter().take(MAX_RECENT_COMMANDS + 2).map(|e| e.id.clone()).collect(); assert_eq!(recent(&entries, &many).len(), MAX_RECENT_COMMANDS); @@ -2083,7 +2407,7 @@ mod tests { assert_eq!(after.first().map(String::as_str), Some(effect)); assert_eq!(after.get(1).map(String::as_str), Some(tool), "only the pick moves"); let label = open.said(effect); - assert_eq!(field_description(&nodes), format!("1 of {}: {label}", after.len())); + assert_eq!(field_place(&nodes), format!("1 of {}: {label}", after.len())); open.press(egui::Key::Enter, 1); assert!(open.app.ui.dialog.is_some(), "Enter ran the effect again: {}", open.app.ui.status); assert_eq!(open.app.ui.recent_commands, [effect]); @@ -2104,6 +2428,250 @@ mod tests { assert_eq!(ids(&["plugin:test.UI.palette_removed".to_string(), effect.clone()]).first(), Some(&effect)); } + /// Pick counts for the ids `counts`, picked in that order. + fn counted(counts: &[(&str, u32)]) -> CommandUses { + let uses = counts.iter().zip(1..).map(|(&(id, n), last)| (id.to_string(), (n, last))).collect(); + CommandUses { pick: u32::try_from(counts.len()).unwrap(), uses } + } + + /// A command picked often ranks first among the results that match the query as well as it + /// does, also when it is no longer a recent pick, and the count is saved with the other + /// interface settings. + #[test] + fn a_command_picked_often_ranks_first_among_results_that_match_as_well() { + let (tool, effect) = ("tool:rectangle", "effect:convertToShape.rectangle"); + let mut open = Open::new("rect", egui::vec2(1200.0, 900.0)); + // The fixture has art selected, so the effect is not dimmed and its pick is counted. + open.app = VectorcraftApp::new(vectorcraft_testkit::fixtures::Fixture::Multi.session(), crate::Services::default()); + open.app.ui.palette_open = true; + open.app.ui.palette_query = "rect".into(); + open.frame(vec![]); + let before = open.listed(); + assert_eq!(before.first().map(String::as_str), Some(tool)); + let at = before.iter().position(|id| id == effect).unwrap(); + open.press(egui::Key::ArrowDown, at); + open.press(egui::Key::Enter, 1); + assert_eq!(open.app.ui.command_uses.grade(effect), 1); + assert_eq!(open.app.ui.command_uses.grade(tool), 0); + + open.app.ui.recent_commands.clear(); + open.app.ui.dialog = None; + open.app.ui.palette_open = true; + open.app.ui.palette_query = "rect".into(); + open.frame(vec![]); + let after = open.listed(); + assert_eq!(after.first().map(String::as_str), Some(effect)); + assert_eq!(after.get(1).map(String::as_str), Some(tool), "only the pick moves"); + let restored: crate::state::UiState = serde_json::from_str(&serde_json::to_string(&open.app.ui).unwrap()).unwrap(); + assert_eq!(restored.command_uses, open.app.ui.command_uses); + } + + /// The kept ranking of a query is ranked again when a pick count changes. + #[test] + fn the_kept_ranking_follows_the_pick_counts() { + let ctx = egui::Context::default(); + let entries = entries(&ctx, Lang::EN); + let first = |uses: &CommandUses| super::matching(&entries, "rect", &[], uses).first().map(|e| e.id.clone()); + let effect = "effect:convertToShape.rectangle"; + assert_eq!(first(&CommandUses::default()).as_deref(), Some("tool:rectangle")); + let mut uses = counted(&[("tool:rectangle", 1)]); + assert_eq!(first(&uses).as_deref(), Some("tool:rectangle")); + uses.count(effect); + assert_eq!(first(&uses).as_deref(), Some("tool:rectangle"), "the same grade: the catalog order"); + uses.count(effect); + uses.count(effect); + assert_eq!(first(&uses).as_deref(), Some(effect), "three picks reach grade 2"); + assert_eq!(first(&CommandUses::default()).as_deref(), Some("tool:rectangle")); + } + + /// A count does not lift a result above one that matches the query better: the exact id + /// `view.goto1` lists Saved View 1 before Saved View 10, however often that was picked. + #[test] + fn a_count_does_not_pass_a_better_match() { + let ctx = egui::Context::default(); + let entries = entries(&ctx, Lang::EN); + let uses = counted(&[("view.goto10", 999)]); + let ids: Vec<&str> = super::matching(&entries, "view.goto1", &[], &uses).into_iter().map(|e| e.id.as_str()).collect(); + assert_eq!(ids.first(), Some(&"view.goto1"), "{ids:?}"); + assert!(ids.contains(&"view.goto10"), "{ids:?}"); + } + + /// Counts grow in grades that double: 1 pick gives grade 1, 3 give 2, 7 give 3, and 999 give 9. + #[test] + fn pick_counts_rank_in_grades_that_double() { + let mut uses = CommandUses::default(); + let grades: Vec = (0..8) + .map(|_| { + let g = uses.grade("a"); + uses.count("a"); + g + }) + .collect(); + assert_eq!(grades, [0, 1, 1, 2, 2, 2, 2, 3]); + assert_eq!(counted(&[("a", 999)]).grade("a"), 9); + assert_eq!(counted(&[("a", u32::MAX)]).grade("a"), 9); + assert!(CommandUses::default().grades(&[]).is_empty(), "no grades without counts"); + } + + /// A new id when 200 are counted removes, of the 100 ids picked longest ago, the id with the + /// lowest count, of those the one picked longest ago, and keeps the new one. + #[test] + fn the_201st_command_removes_the_least_used_and_keeps_itself() { + let ids: Vec = (0..MAX_COUNTED_COMMANDS).map(|i| format!("c{i}")).collect(); + let counts: Vec<(&str, u32)> = ids.iter().enumerate().map(|(i, id)| (id.as_str(), if i == 5 || i == 9 { 1 } else { 2 })).collect(); + let mut uses = counted(&counts); + uses.count("new"); + assert_eq!(uses.uses.len(), MAX_COUNTED_COMMANDS); + assert!(!uses.uses.contains_key("c5") && uses.uses.contains_key("c9")); + assert_eq!(uses.uses.get("new"), Some(&(1, 201))); + uses.count("newer"); + assert!(!uses.uses.contains_key("c9"), "c9 was picked before new"); + assert!(uses.uses.contains_key("new") && uses.uses.contains_key("newer")); + assert_eq!(uses.uses.len(), MAX_COUNTED_COMMANDS); + } + + /// When all 200 counted ids have 2 picks or more, new ids picked in turn keep their places and + /// their counts grow; the ids removed are the ones picked longest ago. + #[test] + fn new_commands_build_up_counts_when_every_counted_one_has_more_picks() { + let ids: Vec = (0..MAX_COUNTED_COMMANDS).map(|i| format!("c{i}")).collect(); + let counts: Vec<(&str, u32)> = ids.iter().map(|id| (id.as_str(), 2)).collect(); + let mut uses = counted(&counts); + for _ in 0..3 { + for id in ["a", "b", "c"] { + uses.count(id); + } + } + assert_eq!(uses.uses.len(), MAX_COUNTED_COMMANDS); + for id in ["a", "b", "c"] { + assert_eq!(uses.uses.get(id).map(|&(n, _)| n), Some(3), "{id}"); + } + assert!(!uses.uses.contains_key("c0") && !uses.uses.contains_key("c2") && uses.uses.contains_key("c3")); + assert!(uses.uses.contains_key("c199")); + } + + /// When a count reaches 1,000, every count is halved and ids left at 0 are removed. + #[test] + fn counts_are_halved_at_one_thousand() { + let mut uses = counted(&[("a", 999), ("b", 1), ("c", 5)]); + uses.count("a"); + assert_eq!(uses.uses.get("a"), Some(&(500, 4))); + assert_eq!(uses.uses.get("c"), Some(&(2, 3))); + assert!(!uses.uses.contains_key("b")); + } + + /// At the pick number's limit, the counted ids' pick numbers are renumbered from 1 in their + /// order, so a pick still takes a number above all of them and a command picked again leaves + /// the half of the ids picked longest ago. + #[test] + fn picks_keep_their_order_at_the_pick_number_limit() { + let ids: Vec = (0..MAX_COUNTED_COMMANDS).map(|i| format!("c{i:03}")).collect(); + let mut uses = CommandUses { pick: u32::MAX, uses: ids.iter().map(|id| (id.clone(), (2, u32::MAX))).collect() }; + uses.uses.insert("c000".into(), (1, u32::MAX)); + uses.count("c000"); + assert_eq!(uses.uses.get("c000"), Some(&(2, 2))); + assert_eq!(uses.uses.get("c001"), Some(&(2, 1))); + uses.count("new"); + assert!(uses.uses.contains_key("c000"), "c000 was picked last: {:?}", uses.uses.get("c000")); + assert!(!uses.uses.contains_key("c001")); + assert_eq!(uses.uses.get("new"), Some(&(1, 3))); + // Equal pick numbers stay equal, and the order of the others is kept. + let mut uses = + CommandUses { pick: u32::MAX, uses: [("a", (1, 7)), ("b", (1, u32::MAX)), ("c", (1, 7))].map(|(k, v)| (k.to_string(), v)).into() }; + uses.count("d"); + assert_eq!( + uses, + CommandUses { pick: 3, uses: [("a", (1, 1)), ("b", (1, 2)), ("c", (1, 1)), ("d", (1, 3))].map(|(k, v)| (k.to_string(), v)).into() } + ); + } + + /// Saved counts load what is readable: a count above 999 reads as 999, entries that are not a + /// pair of counts are dropped, of more than 200 ids the most recent picks are kept, and a value + /// of the wrong kind, or none (an older settings file), reads as no picks. + #[test] + fn saved_pick_counts_load_what_is_readable() { + let load = |v: serde_json::Value| serde_json::from_value::(json!({ "command_uses": v })).unwrap().command_uses; + let uses = load(json!({ + "pick": 3, + "uses": {"a": [5000, 2], "b": "x", "c": [1], "d": [0, 1], "e": [2, 3, 4], "f": [-1, 2], "g": [4, 1], "h": [1.5, 1], "i": [3, 9]} + })); + assert_eq!(uses, CommandUses { pick: 9, uses: [("a", (999, 2)), ("g", (4, 1)), ("i", (3, 9))].map(|(k, v)| (k.to_string(), v)).into() }); + for wrong in [json!("x"), json!(null), json!([1, 2]), json!({"uses": [1]}), json!({"pick": "x", "uses": {}})] { + assert_eq!(load(wrong.clone()), CommandUses::default(), "{wrong}"); + } + let older: crate::state::UiState = serde_json::from_value(json!({})).unwrap(); + assert_eq!(older.command_uses, CommandUses::default()); + let many: serde_json::Map = (1..=250).map(|i| (format!("c{i}"), json!([1, i]))).collect(); + let uses = load(json!({ "pick": 250, "uses": many })); + assert_eq!(uses.uses.len(), MAX_COUNTED_COMMANDS); + assert!(uses.uses.contains_key("c51") && !uses.uses.contains_key("c50")); + // The next pick is the most recent, also when the saved pick number is behind. + let mut uses = load(json!({ "pick": 1, "uses": {"a": [1, 9]} })); + uses.count("b"); + assert_eq!(uses.uses.get("b"), Some(&(1, 10))); + // Saved pick numbers above the largest the counts hold are compared as saved, and the kept + // ones are renumbered from 1 in their order. + let big = u64::from(u32::MAX) + 1; + let mut many: serde_json::Map = (0..MAX_COUNTED_COMMANDS).map(|i| (format!("c{i:03}"), json!([1, big]))).collect(); + many.insert("z".into(), json!([1, big + 1])); + let uses = load(json!({ "pick": big + 1, "uses": many })); + assert_eq!(uses.uses.len(), MAX_COUNTED_COMMANDS); + assert_eq!(uses.uses.get("z"), Some(&(1, 2)), "the newest pick is kept"); + assert_eq!(uses.uses.get("c000"), Some(&(1, 1))); + assert_eq!(uses.pick, 2); + let uses = load(json!({ "pick": big, "uses": {"a": [1, 5], "b": [1, 3]} })); + assert_eq!(uses, CommandUses { pick: 2, uses: [("a", (1, 2)), ("b", (1, 1))].map(|(k, v)| (k.to_string(), v)).into() }); + } + + /// A pick is counted only when Recent Commands records it: a refused pick and a pick of the + /// palette's own toggle are not counted, and a pick that opens a dialog is. + #[test] + fn only_a_pick_recorded_in_recent_commands_is_counted() { + for (query, id) in [("find and replace", "edit.findReplace"), ("search commands", PALETTE_TOGGLE)] { + let mut open = Open::new(query, WINDOW); + let k = open.listed().iter().position(|c| c == id).unwrap_or_else(|| panic!("{query:?} finds {id}")); + open.frame(vec![]); + open.press(egui::Key::ArrowDown, k); + assert_eq!(open.highlighted(), k, "{id}"); + open.press(egui::Key::Enter, 1); + assert!(open.app.ui.recent_commands.is_empty(), "{id}"); + assert_eq!(open.app.ui.command_uses, CommandUses::default(), "{id}"); + } + let id = "object.path.cleanUp"; + let mut open = Open::new("clean up", WINDOW); + open.app = VectorcraftApp::new(vectorcraft_testkit::fixtures::Fixture::Single.session(), crate::Services::default()); + open.app.ui.palette_open = true; + open.app.ui.palette_query = "clean up".into(); + let k = open.listed().iter().position(|c| c == id).expect("the search finds Clean Up…"); + open.frame(vec![]); + open.press(egui::Key::ArrowDown, k); + open.press(egui::Key::Enter, 1); + assert!(open.app.ui.dialog.is_some()); + assert_eq!(open.app.ui.recent_commands, [id]); + assert_eq!(open.app.ui.command_uses.grade(id), 1); + } + + /// A refused pick leaves the recent picks and the pick counts saved before it as they were. + #[test] + fn a_refused_pick_leaves_the_earlier_counts_as_they_were() { + let id = "edit.findReplace"; + let mut open = Open::new("find and replace", WINDOW); + open.app.ui.recent_commands = vec!["paint.swap".into(), "object.group".into()]; + for _ in 0..2 { + open.app.ui.command_uses.count("paint.swap"); + } + open.app.ui.command_uses.count("object.group"); + let (recent, uses) = (open.app.ui.recent_commands.clone(), open.app.ui.command_uses.clone()); + let k = open.listed().iter().position(|c| c == id).expect("the search finds Find and Replace…"); + open.frame(vec![]); + open.press(egui::Key::ArrowDown, k); + open.press(egui::Key::Enter, 1); + assert!(open.app.ui.dialog.is_none(), "no document: the pick is refused"); + assert_eq!(open.app.ui.recent_commands, recent); + assert_eq!(open.app.ui.command_uses, uses); + assert_eq!(open.app.ui.command_uses.grade(id), 0); + } + /// #6376: with nothing picked yet, Recent Commands shows a dimmed No recent commands row. #[test] fn recent_commands_without_picks_show_a_dimmed_row() { @@ -2169,6 +2737,90 @@ mod tests { assert_eq!(open.app.ui.recent_commands, ["paint.swap", "object.group"]); } + /// Text typed into an empty search in the frame that presses Enter runs the first result of the + /// new query, not the last pick the empty search listed. + #[test] + fn enter_with_text_typed_in_its_frame_runs_the_new_querys_first_result() { + let mut open = Open::new("", WINDOW); + open.app = VectorcraftApp::new(vectorcraft_testkit::fixtures::Fixture::Multi.session(), crate::Services::default()); + open.app.ui.recent_commands = vec!["paint.swap".into()]; + open.app.ui.palette_open = true; + open.frame(vec![]); + open.frame(vec![]); + let entries = entries(&open.ctx, Lang::EN); + let first = super::matching(&entries, "select all", &open.app.ui.recent_commands, &open.app.ui.command_uses)[0].id.clone(); + assert_ne!(first, "paint.swap"); + let enter = egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }; + open.frame(vec![egui::Event::Text("select all".into()), enter]); + assert!(!open.app.ui.palette_open, "the palette closes"); + assert_eq!(open.app.ui.recent_commands.first(), Some(&first), "{}", open.app.ui.status); + } + + /// A pick of Clear Recent Commands empties the recent picks without keeping itself, so the + /// empty search then says what to type, and the saved UI state holds an empty list. + #[test] + fn clear_recent_commands_empties_the_recent_picks() { + const CLEAR: &str = "help.clearRecentCommands"; + let mut open = Open::new("clear recent commands", WINDOW); + open.app.ui.recent_commands = vec!["paint.swap".into(), "object.group".into()]; + assert!(menus::enabled(&open.app, CLEAR)); + let k = open.listed().iter().position(|id| id == CLEAR).expect("the command's result"); + open.frame(vec![]); + open.press(egui::Key::ArrowDown, k); + assert_eq!(open.highlighted(), k); + open.press(egui::Key::Enter, 1); + assert!(!open.app.ui.palette_open, "the palette closes"); + assert!(open.app.ui.recent_commands.is_empty(), "{:?}", open.app.ui.recent_commands); + assert!(!menus::enabled(&open.app, CLEAR), "not enabled with nothing to clear"); + let saved: serde_json::Value = serde_json::to_value(&open.app.ui).unwrap(); + assert_eq!(saved["recent_commands"], serde_json::json!([])); + open.app.ui.palette_query.clear(); + open.app.ui.palette_open = true; + let nodes = open.frame(vec![]); + assert!(rows(&nodes).is_empty(), "{:?}", rows(&nodes)); + let labels = labels(&nodes); + assert!(labels.iter().any(|l| l == tl!("Type to search commands, tools, panels and effects")), "{labels:?}"); + // Run as a command, it empties the list too. + open.app.ui.recent_commands = vec!["paint.swap".into()]; + open.app.run(CLEAR, serde_json::json!({})).unwrap(); + assert!(open.app.ui.recent_commands.is_empty()); + // A saved id the list leaves out (a plug-in that is not loaded) still counts, and is cleared. + open.app.ui.recent_commands = vec!["plugin.notLoaded.filter".into()]; + assert!(menus::enabled(&open.app, CLEAR)); + open.app.run(CLEAR, serde_json::json!({})).unwrap(); + assert!(open.app.ui.recent_commands.is_empty()); + } + + /// Clear Recent Commands also empties the pick counts, and a pick of it from the search is not + /// counted afterward; with counts left and no recent picks, it is still enabled. + #[test] + fn clear_recent_commands_also_clears_the_pick_counts() { + const CLEAR: &str = "help.clearRecentCommands"; + let mut open = Open::new("clear recent commands", WINDOW); + open.app.ui.recent_commands = vec!["paint.swap".into()]; + for _ in 0..3 { + open.app.ui.command_uses.count("paint.swap"); + } + open.app.ui.command_uses.count("object.group"); + let k = open.listed().iter().position(|id| id == CLEAR).expect("the command's result"); + open.frame(vec![]); + open.press(egui::Key::ArrowDown, k); + assert_eq!(open.highlighted(), k); + open.press(egui::Key::Enter, 1); + assert!(open.app.ui.recent_commands.is_empty(), "{:?}", open.app.ui.recent_commands); + assert_eq!(open.app.ui.command_uses, CommandUses::default(), "the pick of Clear is not counted either"); + let saved: crate::state::UiState = serde_json::from_value(serde_json::to_value(&open.app.ui).unwrap()).unwrap(); + assert_eq!(saved.command_uses, CommandUses::default()); + assert!(!menus::enabled(&open.app, CLEAR)); + // Counts without recent picks (Recent Commands emptied some other way) still enable it, + // and running it as a command empties them. + open.app.ui.command_uses.count("paint.swap"); + assert!(menus::enabled(&open.app, CLEAR), "enabled while a count is saved"); + open.app.run(CLEAR, serde_json::json!({})).unwrap(); + assert_eq!(open.app.ui.command_uses, CommandUses::default()); + assert_eq!(open.app.ui.command_uses.grade("paint.swap"), 0); + } + /// The palette opens again with its first row highlighted, even when it shows the same rows. #[test] fn the_palette_opens_again_with_its_first_row_highlighted() { @@ -2226,6 +2878,30 @@ mod tests { assert_eq!(open.app.ui.recent_commands, ["paint.swap", "object.group"]); } + /// A palette that its command closes and opens again before it is drawn closed starts at its + /// first row, so Enter on an empty search runs the last pick. + #[test] + fn the_palette_toggled_closed_and_open_between_frames_starts_at_its_first_row() { + let mut open = Open::new("", WINDOW); + open.app = VectorcraftApp::new(vectorcraft_testkit::fixtures::Fixture::Multi.session(), crate::Services::default()); + open.app.ui.recent_commands = vec!["paint.swap".into(), "object.group".into()]; + open.app.ui.palette_open = true; + open.frame(vec![]); + open.press(egui::Key::ArrowDown, 1); + assert_eq!(open.highlighted(), 1); + open.app.run("help.commandPalette", json!({})).unwrap(); + assert!(!open.app.ui.palette_open, "the command closes the palette"); + open.app.run("help.commandPalette", json!({})).unwrap(); + assert!(open.app.ui.palette_open, "and opens it again"); + open.frame(vec![]); + assert_eq!(open.highlighted(), 0); + let before = open.app.session.active().unwrap().history.undo.len(); + open.press(egui::Key::Enter, 1); + assert!(!open.app.ui.palette_open, "the palette closes"); + assert_eq!(open.app.session.active().unwrap().history.undo.len(), before + 1, "{}", open.app.ui.status); + assert_eq!(open.app.ui.recent_commands, ["paint.swap", "object.group"]); + } + /// A pick of the palette's own toggle is not recorded, and one saved earlier is not listed, so /// Enter on an empty search runs the last other pick. #[test] @@ -2362,6 +3038,27 @@ mod tests { assert_eq!(open.app.ui.recent_commands, [id, "paint.swap"]); } + /// A palette closed by a press outside it and opened again before a closed frame is drawn + /// starts with its first row highlighted and asks its results again whether they can run. + #[test] + fn the_palette_opened_again_at_once_after_closing_starts_afresh() { + let mut open = Open::new("", WINDOW); + open.app.ui.recent_commands = vec!["paint.swap".into(), "object.group".into(), "view.zoomIn".into()]; + open.frame(vec![]); + open.press(egui::Key::ArrowDown, 2); + assert_eq!(open.highlighted(), 2); + let at = egui::pos2(2.0, 2.0); + assert!(!open.popup().contains(at), "{at:?} is outside {:?}", open.popup()); + let press = egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE }; + open.frame(vec![egui::Event::PointerMoved(at), press]); + assert!(!open.app.ui.palette_open, "the press outside closes the palette"); + let availability = egui::Id::unique("palette-availability"); + assert!(open.ctx.data(|d| d.get_temp::(availability)).is_none(), "the answers go when the palette closes"); + open.app.ui.palette_open = true; + open.frame(vec![]); + assert_eq!(open.highlighted(), 0, "the first row is highlighted"); + } + /// #1757: Up and Down move the highlighted result, wrapping at the ends; a new query starts /// from the first again. #[test] @@ -2845,6 +3542,8 @@ mod tests { time: f64, /// Whether the last frame asked for another one at once. repaint: bool, + /// What the last frame drew. + shapes: Vec, } impl Open { @@ -2858,7 +3557,7 @@ mod tests { ctx.enable_accesskit(); crate::theme::install_fonts(&ctx); crate::theme::apply(&ctx, Default::default()); - let mut open = Open { app, ctx, size, time: 0.0, repaint: false }; + let mut open = Open { app, ctx, size, time: 0.0, repaint: false, shapes: Vec::new() }; open.frame(vec![]); open } @@ -2872,6 +3571,7 @@ mod tests { let mut out = self.ctx.run_ui(input, |ui| show(app, ui.ctx())); out.textures_delta.clear(); self.repaint = out.viewport_output.get(&egui::ViewportId::ROOT).is_some_and(|v| v.repaint_delay.is_zero()); + self.shapes = std::mem::take(&mut out.shapes); out.platform_output.accesskit_update.map(|u| u.nodes.into_iter().map(|(_, n)| n).collect()).unwrap_or_default() } @@ -2881,6 +3581,18 @@ mod tests { self.frame(vec![key; times]) } + /// The color the last frame drew the text `text` in. + fn color_of(&self, text: &str) -> Option { + fn find(shape: &egui::Shape, text: &str) -> Option { + match shape { + egui::Shape::Text(t) if t.galley.text() == text => Some(t.fallback_color), + egui::Shape::Vec(shapes) => shapes.iter().find_map(|s| find(s, text)), + _ => None, + } + } + self.shapes.iter().find_map(|s| find(&s.shape, text)) + } + /// The highlighted result's index. fn highlighted(&self) -> usize { self.ctx.data(|d| d.get_temp::(egui::Id::unique("palette-selected"))).unwrap().0 @@ -2904,7 +3616,7 @@ mod tests { let listed = if self.app.ui.palette_query.trim().is_empty() { recent(&entries.list, &self.app.ui.recent_commands) } else { - matching(&entries, &self.app.ui.palette_query.to_lowercase(), &self.app.ui.recent_commands) + super::matching(&entries, &self.app.ui.palette_query.to_lowercase(), &self.app.ui.recent_commands, &self.app.ui.command_uses) }; listed.iter().take(MAX_RESULTS).map(|e| e.id.clone()).collect() } @@ -2935,6 +3647,12 @@ mod tests { field.description().unwrap_or_default().to_string() } + /// The first line of the search field's description: the highlighted result's place and name, + /// without the reason a result that can't run now adds under it. + fn field_place(nodes: &[egui::accesskit::Node]) -> String { + field_description(nodes).lines().next().unwrap_or_default().to_string() + } + const WINDOW: egui::Vec2 = egui::vec2(1280.0, 900.0); /// Each result is a 20-point row, rows touch, and 12 show at once; the popup is shorter than @@ -3181,7 +3899,7 @@ mod tests { let lit: Vec = rows(&nodes).into_iter().filter(|r| r.1).map(|r| r.0).collect(); let label = open.said(&listed[3]); assert_eq!(lit, std::slice::from_ref(&label)); - assert_eq!(field_description(&nodes), format!("4 of {}: {label}", matching(&entries, "select", &[]).len())); + assert_eq!(field_place(&nodes), format!("4 of {}: {label}", matching(&entries, "select", &[]).len())); } /// A name too long for its row is cut short with "…" and stays inside the width it is given. @@ -3391,7 +4109,8 @@ mod tests { assert_eq!(said, "Effect, Round Corners…, Effect › Stylize"); let row = rows(&nodes).into_iter().find(|r| r.0 == said).expect("its row is drawn"); assert!((row.3 - row.2 - f64::from(ROW_HEIGHT)).abs() < 0.01, "{row:?}"); - assert!(field_description(&nodes).ends_with(&said), "{}", field_description(&nodes)); + // With no document, Round Corners can't run now, and the reason goes on a second line. + assert!(field_place(&nodes).ends_with(&said), "{}", field_description(&nodes)); let open = Open::new("group selection", WINDOW); assert_eq!(open.said("tool:groupSelection"), "Tool, Group Selection Tool, Toolbar, in the Direct Selection Tool group"); let mut open = Open::new("layers", WINDOW); @@ -3443,6 +4162,329 @@ mod tests { assert!(crate::panel_docking::showing(&open.app.ui, &panel), "{panel}: {}", open.app.ui.status); } + /// The open palette on `query` over the session `session`. + fn open_on(query: &str, session: vectorcraft_engine::Session) -> Open { + let mut open = Open::new(query, WINDOW); + open.app = VectorcraftApp::new(session, crate::Services::default()); + open.app.ui.palette_open = true; + open.app.ui.palette_query = query.into(); + open.frame(vec![]); + open + } + + /// The screen-reader node of the result row named `name`. + fn row_named<'a>(nodes: &'a [egui::accesskit::Node], name: &str) -> &'a egui::accesskit::Node { + nodes + .iter() + .filter(|n| n.role() == egui::accesskit::Role::ListItem) + .find(|n| n.label().is_some_and(|l| l == name || l.starts_with(&format!("{name}, ")))) + .unwrap_or_else(|| panic!("a row named {name}: {:?}", rows(nodes))) + } + + /// Highlights the result `id` with the arrow keys: the frame's screen-reader tree. + fn highlight(open: &mut Open, id: &str) -> Vec { + let k = open.listed().iter().position(|e| e == id).unwrap_or_else(|| panic!("{id} is listed")); + assert!(k < VISIBLE_ROWS, "{:?}", open.listed()); + let nodes = open.press(egui::Key::ArrowDown, k); + assert_eq!(open.highlighted(), k); + nodes + } + + /// With nothing selected, Ungroup stays listed in its place, dimmed, with the engine's reason in + /// its screen-reader description and in the footer while it is highlighted. Selecting art while + /// the palette stays open shows it as available on the next frame, in the same order. (A query + /// other tests' plug-in names do not match, so the list stays the same between frames.) + #[test] + fn a_result_that_cannot_run_now_is_dimmed_and_says_why() { + let mut session = vectorcraft_testkit::fixtures::Fixture::Multi.session(); + session.execute("select.none", &json!({})).unwrap(); + let why = ungroup_reason(&session); + let mut open = open_on("ungroup", session); + let entries = entries(&open.ctx, Lang::EN); + let entry = entries.iter().find(|e| e.id == "object.ungroup").unwrap(); + let name = open.said("object.ungroup"); + let order = open.listed(); + let nodes = highlight(&mut open, "object.ungroup"); + let ungroup = row_named(&nodes, &name); + assert!(ungroup.is_disabled(), "{ungroup:?}"); + assert_eq!(ungroup.description(), Some(why.as_str())); + let t = Tokens::get(&open.ctx); + // The row draws the name without the menu path its home shows. + assert_eq!(open.color_of(label_of(entry)), Some(t.text_disabled), "the name is drawn dimmed"); + let footer_says = |nodes: &[egui::accesskit::Node]| labels(nodes).contains(&why); + assert!(footer_says(&nodes), "{:?}", labels(&nodes)); + // The arrow keys leave screen readers on the search field, so its description says why too. + let place = format!("{} of {}: {name}", open.highlighted() + 1, order.len()); + assert_eq!(field_description(&nodes), format!("{place}\n{why}")); + let dimmed_rows: Vec = rows(&nodes).into_iter().map(|r| r.0).collect(); + + open.app.run("select.all", json!({})).unwrap(); + let nodes = open.frame(vec![]); + let ungroup = row_named(&nodes, &name); + assert!(!ungroup.is_disabled() && ungroup.description().is_none(), "{ungroup:?}"); + assert_eq!(open.color_of(label_of(entry)), Some(t.text)); + assert!(!footer_says(&nodes), "{:?}", labels(&nodes)); + assert_eq!(field_description(&nodes), place); + // Whether a result can run never moves it. + assert_eq!(open.listed(), order); + assert_eq!(rows(&nodes).into_iter().map(|r| r.0).collect::>(), dimmed_rows); + } + + /// Why Object › Ungroup can't run in `session`, as the palette shows it: the engine's reason, + /// with the result's name and no command id. + fn ungroup_reason(session: &vectorcraft_engine::Session) -> String { + let reason = (vectorcraft_engine::find_command("object.ungroup").unwrap().enabled)(session).unwrap_err(); + let why = crate::i18n::msg(&format!("command `Object › Ungroup` is not available right now: {reason}")); + assert!(!why.contains("object.ungroup"), "{why}"); + why + } + + /// The pointer resting on a result that can't run now shows why in a tooltip, as well as in + /// the footer of the result it highlights. + #[test] + fn hovering_a_result_that_cannot_run_now_says_why() { + let mut session = vectorcraft_testkit::fixtures::Fixture::Multi.session(); + session.execute("select.none", &json!({})).unwrap(); + let why = ungroup_reason(&session); + let mut open = open_on("ungroup", session); + let name = open.said("object.ungroup"); + let nodes = open.frame(vec![]); + let b = row_named(&nodes, &name).bounds().unwrap(); + let at = egui::pos2(((b.x0 + b.x1) / 2.0) as f32, ((b.y0 + b.y1) / 2.0) as f32); + open.frame(vec![egui::Event::PointerMoved(at)]); + let says = |nodes: &[egui::accesskit::Node]| labels(nodes).iter().filter(|l| **l == why).count(); + let shown = (0..30).map(|_| says(&open.frame(vec![]))).max().unwrap_or(0); + assert_eq!(shown, 2, "the footer and the tooltip"); + } + + /// Under an empty search, a highlighted recent pick that can't run now is dimmed and the line + /// under the picks says why. + #[test] + fn a_recent_pick_that_cannot_run_now_says_why() { + let mut session = vectorcraft_testkit::fixtures::Fixture::Multi.session(); + session.execute("select.none", &json!({})).unwrap(); + let why = ungroup_reason(&session); + let mut open = open_on("", session); + open.app.ui.recent_commands = vec!["object.ungroup".to_string(), "object.group".to_string()]; + let nodes = open.frame(vec![]); + assert_eq!(open.highlighted(), 0); + let rows: Vec<_> = nodes.iter().filter(|n| n.role() == egui::accesskit::Role::ListItem).collect(); + assert_eq!(rows.len(), 2, "{rows:?}"); + assert!(rows.iter().all(|n| n.is_disabled()), "{rows:?}"); + assert!(labels(&nodes).contains(&why), "{:?}", labels(&nodes)); + let popup = open.popup(); + assert!(popup.bottom() <= WINDOW.y, "{popup:?}"); + } + + /// The Recent Commands list beside the search field draws a pick that can't run now dimmed, + /// disabled for screen readers with the reason as its description, and says why on hover. + #[test] + fn a_recent_command_that_cannot_run_now_is_dimmed_in_the_list() { + use egui::accesskit::Role; + use egui_kittest::kittest::{NodeT, Queryable}; + let mut app = VectorcraftApp::new(vectorcraft_testkit::fixtures::Fixture::Multi.session(), crate::Services::default()); + app.run("select.none", json!({})).unwrap(); + let why = ungroup_reason(&app.session); + app.ui.recent_commands = vec!["object.ungroup".into(), "select.all".into()]; + let mut h = palette_harness(app); + h.ctx.all_styles_mut(|s| s.interaction.tooltip_delay = 0.0); + h.get_by_label(tl!("Recent Commands")).click(); + h.run_steps(2); + let shown = |id: &str| entries(&h.ctx, Lang::EN).iter().find(|e| e.id == id).map(|e| e.shown.clone()).unwrap(); + let (ungroup, all) = (shown("object.ungroup"), shown("select.all")); + // A row's label also holds its shortcut. + let row = |name: &str| { + let name = name.to_string(); + move |n: &egui_kittest::kittest::AccessKitNode<'_>| n.role() == Role::Button && n.label().is_some_and(|l| l.contains(&name)) + }; + let ungroup_row = h.get_by(row(&ungroup)); + assert!(ungroup_row.accesskit_node().is_disabled()); + assert_eq!(ungroup_row.accesskit_node().description().as_deref(), Some(why.as_str())); + let all_row = h.get_by(row(&all)); + assert!(!all_row.accesskit_node().is_disabled() && all_row.accesskit_node().description().is_none()); + h.get_by(row(&ungroup)).hover(); + h.run_steps(3); + assert!(h.query_by_label(&why).is_some(), "the tooltip says why"); + } + + /// The palette drops its answers when it closes, so opening it again, with the keyboard too, + /// asks its results again. + #[test] + fn the_palette_asks_again_when_it_opens_again() { + let mut session = vectorcraft_testkit::fixtures::Fixture::Multi.session(); + session.execute("select.none", &json!({})).unwrap(); + let mut open = open_on("ungroup", session); + let id = egui::Id::unique("palette-availability"); + let kept = |open: &Open| open.ctx.data(|d| d.get_temp::(id)); + assert!(kept(&open).is_some_and(|a| a.known.contains_key("object.ungroup"))); + open.app.ui.palette_open = false; + open.frame(vec![]); + assert!(kept(&open).is_none(), "the answers go when the palette closes"); + open.app.ui.palette_open = true; + open.frame(vec![]); + assert!(kept(&open).is_some_and(|a| a.asked > 0 && a.known.contains_key("object.ungroup")), "asked again"); + } + + /// What the results' availability depends on changes the key it is kept under: an open dialog, + /// the screen mode, a background job, and a save that marks the document saved without a new + /// revision. + #[test] + fn availability_is_asked_again_when_what_it_depends_on_changes() { + let write_shared: crate::background::SharedWriteFn = std::sync::Arc::new(|_: &str, _: &[u8]| Ok(())); + let services = crate::Services { write_shared: Some(write_shared), ..Default::default() }; + let mut app = VectorcraftApp::new(vectorcraft_testkit::fixtures::Fixture::Multi.session(), services); + let mut key = availability_key(&app); + let mut changed = |app: &VectorcraftApp, what: &str| { + let now = availability_key(app); + assert_ne!(now, key, "{what}"); + key = now; + }; + app.ui.dialog = Some(crate::state::Dialog::new("about", json!({}))); + changed(&app, "a dialog opens"); + app.ui.dialog = None; + changed(&app, "the dialog closes"); + app.ui.screen_mode = 3; + changed(&app, "Presentation Mode"); + let started = crate::background::run(&mut app, true, "Saving".into(), None, |_| Ok(json!({})), |_, r| r).unwrap(); + assert_eq!(started.get("background"), Some(&json!(true)), "{started}"); + changed(&app, "a background job starts"); + app.run("select.all", json!({})).unwrap(); + app.run("object.group", json!({})).unwrap(); + changed(&app, "an edit"); + let revision = app.session.active().map(|d| d.revision); + app.session.active_mut().unwrap().mark_saved(); + assert_eq!(app.session.active().map(|d| d.revision), revision); + changed(&app, "the document is saved"); + } + + /// The drawn results are asked whether they can run once per state: keys pressed in the palette + /// keep the answers, a command run asks again, and a frame with a click asks again once, + /// without changing the state the answers are kept for. + #[test] + fn availability_is_read_once_per_state() { + let mut session = vectorcraft_testkit::fixtures::Fixture::Multi.session(); + session.execute("select.none", &json!({})).unwrap(); + let mut open = open_on("ungroup", session); + let id = egui::Id::unique("palette-availability"); + let read = |open: &Open| open.ctx.data(|d| d.get_temp::(id)).expect("the availability is kept"); + let first = read(&open); + assert!(first.known.get("object.ungroup").is_some_and(Option::is_some), "{:?}", first.known); + // The key also takes in state shared by every test (the language, the loaded fonts, the + // installed plug-ins), which other tests change at the same time, so the presses are tried + // again until one try keeps the key. + let kept = (0..20).any(|_| { + open.frame(vec![]); + let before = read(&open).key; + open.press(egui::Key::ArrowDown, 1); + open.press(egui::Key::X, 1); + read(&open).key == before + }); + assert!(kept, "key presses keep the answers"); + let first = read(&open); + open.app.run("select.all", json!({})).unwrap(); + open.frame(vec![]); + let after = read(&open); + assert_ne!(after.key, first.key); + assert_eq!(after.known.get("object.ungroup"), Some(&None), "asked again: {:?}", after.known); + let release = egui::Event::PointerButton { + pos: egui::pos2(1.0, 1.0), + button: egui::PointerButton::Primary, + pressed: false, + modifiers: egui::Modifiers::NONE, + }; + // The same retries as for the key presses. + let once = (0..20).any(|_| { + open.frame(vec![]); + let before = read(&open); + open.frame(vec![release.clone()]); + let clicked = read(&open); + open.frame(vec![]); + let next = read(&open); + let asked_again = clicked.key == before.key && clicked.asked > before.asked; + asked_again && (next.key, next.asked) == (clicked.key, clicked.asked) + }); + assert!(once, "a click asks again on its own frame only"); + } + + /// Paste is dimmed while the clipboard is empty and nothing can be pasted from the system + /// clipboard, and not while the system clipboard can be pasted. + #[test] + fn paste_is_dimmed_only_while_nothing_can_be_pasted() { + let mut open = open_on("paste", vectorcraft_testkit::fixtures::Fixture::Multi.session()); + open.app.system_paste = false; + let name = open.said("edit.paste"); + let nodes = open.frame(vec![]); + let paste = row_named(&nodes, &name); + assert!(paste.is_disabled(), "{paste:?}"); + assert_eq!(paste.description(), Some("command `Edit › Paste` is not available right now: clipboard is empty")); + open.app.system_paste = true; + let nodes = open.frame(vec![]); + assert!(!row_named(&nodes, &name).is_disabled()); + } + + /// With no document open, Paste is dimmed with the engine's reason, though the system + /// clipboard still reads as pasteable until its next check. + #[test] + fn paste_is_dimmed_with_no_document_open() { + let mut open = open_on("paste", vectorcraft_engine::Session::new()); + open.app.system_paste = true; + let name = open.said("edit.paste"); + let nodes = open.frame(vec![]); + let paste = row_named(&nodes, &name); + assert!(paste.is_disabled(), "{paste:?}"); + let reason = (vectorcraft_engine::find_command("edit.paste").unwrap().enabled)(&open.app.session).unwrap_err(); + let why = format!("command `Edit › Paste` is not available right now: {reason}"); + assert_eq!(paste.description(), Some(why.as_str())); + assert!(!menus::enabled(&open.app, "edit.paste")); + } + + /// A tool can always be chosen; a panel can't be shown in Presentation Mode, and says so. + #[test] + fn tools_are_never_dimmed_and_panels_are_in_presentation_mode() { + let app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + let tools: Vec = build(Lang::EN).into_iter().map(|e| e.id).filter(|id| id.starts_with("tool:")).collect(); + assert!(!tools.is_empty()); + assert!(tools.iter().all(|id| unavailable(&app, id, id).is_none()), "{tools:?}"); + let mut app = VectorcraftApp::new(vectorcraft_testkit::fixtures::Fixture::Multi.session(), crate::Services::default()); + assert_eq!(unavailable(&app, "panel:layers", "Window › Layers"), None); + app.ui.screen_mode = 3; + assert_eq!(unavailable(&app, "panel:layers", "Window › Layers").as_deref(), Some("panels can't be shown in Presentation Mode")); + } + + /// A UI command without an engine reason says it is not available, and a filter plug-in or an + /// effect asks about the command its pick runs. The message names the result as the palette + /// shows it, never by the command's id. + #[test] + fn a_result_without_an_engine_reason_says_it_is_not_available() { + let app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + assert!(vectorcraft_engine::find_command("ui.newBrush").is_none()); + let brush = unavailable(&app, "ui.newBrush", "New Brush…"); + assert_eq!(brush.as_deref(), Some("command `New Brush…` is not available right now")); + let filter = unavailable(&app, "plugin:any.filter", "Object › Plug-ins › Any Filter…"); + assert_eq!(filter.as_deref(), Some("command `Object › Plug-ins › Any Filter…` is not available right now")); + let effect = crate::shortcut_editor::effect_items().first().map(|e| format!("effect:{}", e.effect)).expect("an Effect menu item"); + let why = unavailable(&app, &effect, "Effect › Any").unwrap_or_else(|| panic!("{effect}")); + assert!(why.starts_with("command `Effect › Any` is not available right now"), "{why}"); + let app = VectorcraftApp::new(vectorcraft_testkit::fixtures::Fixture::Multi.session(), crate::Services::default()); + assert_eq!(unavailable(&app, "ui.newBrush", "New Brush…"), None); + assert_eq!(unavailable(&app, "plugin:any.filter", "Any Filter…"), None); + assert_eq!(unavailable(&app, &effect, "Effect › Any"), None, "{effect}"); + } + + /// Every result's reason names it as the palette shows it: no command id appears in it. + #[test] + fn no_reason_shows_a_command_id() { + let app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + let entries = build(Lang::EN); + let reasons: Vec<(String, String)> = + entries.iter().filter_map(|e| unavailable(&app, &e.id, &e.shown).map(|why| (e.id.clone(), why))).collect(); + assert!(reasons.len() > 100, "with no document most results can't run: {}", reasons.len()); + for (id, why) in &reasons { + let command = crate::keymap::command_of(id).id; + assert!(!why.contains(&format!("`{command}`")), "{id}: {why}"); + } + } + /// Screen readers stay on the field: its description names the highlighted result and its /// place, and follows the highlight; the rows are list items, the highlighted one selected, and /// the footer's count is a label. @@ -3457,19 +4499,19 @@ mod tests { // More results match than the list holds: the place counts every match, as the footer does. let total = matching(&entries, "show panel", &[]).len(); assert!(total > MAX_RESULTS && listed.len() == MAX_RESULTS, "{total}"); - assert_eq!(field_description(&nodes), format!("1 of {total}: {}", label(0))); + assert_eq!(field_place(&nodes), format!("1 of {total}: {}", label(0))); let lit: Vec = rows(&nodes).into_iter().filter(|r| r.1).map(|r| r.0).collect(); assert_eq!(lit, [label(0)]); assert!(labels(&nodes).contains(&format!("50 of {total} results. Keep typing to narrow them.")), "{:?}", labels(&nodes)); let nodes = open.press(egui::Key::ArrowDown, 1); - assert_eq!(field_description(&nodes), format!("2 of {total}: {}", label(1))); + assert_eq!(field_place(&nodes), format!("2 of {total}: {}", label(1))); // Fewer results match than the list holds. let mut open = Open::new("eyedropper", WINDOW); let n = open.listed().len(); assert!((1..MAX_RESULTS).contains(&n), "{n}"); let first = open.said(&open.listed()[0]); let nodes = open.frame(vec![]); - assert_eq!(field_description(&nodes), format!("1 of {n}: {first}")); + assert_eq!(field_place(&nodes), format!("1 of {n}: {first}")); assert!(labels(&nodes).contains(&footer(n, n)), "{:?}", labels(&nodes)); } @@ -4077,7 +5119,7 @@ mod tests { assert_eq!((sel, &now), (MAX_RESULTS - 1, &id), "the highlight stays on its result, in the last row"); let label = row_label(ranked[MAX_RESULTS], &home_text(&open.app, ranked[MAX_RESULTS])); assert!(rows(&nodes).iter().any(|r| r.1 && r.0 == label), "its row is drawn and highlighted"); - assert_eq!(field_description(&nodes), format!("{} of {}: {label}", MAX_RESULTS + 1, ranked.len())); + assert_eq!(field_place(&nodes), format!("{} of {}: {label}", MAX_RESULTS + 1, ranked.len())); } impl Window { diff --git a/crates/ui-egui/src/palette/search.rs b/crates/ui-egui/src/palette/search.rs index 1be7bd5a3c..ed49600660 100644 --- a/crates/ui-egui/src/palette/search.rs +++ b/crates/ui-egui/src/palette/search.rs @@ -682,9 +682,9 @@ fn phrase(e: &Entry, query: &str, initials: bool) -> u8 { /// What results are ordered by, compared field by field: whether a word matched only through a /// description, whether a word matched only through a typo, how the whole query matches, the worst /// grade a word gets, the sum of the grades, how the whole query matches when read with the words -/// of the same meaning it matched through, the result's place among the recent picks, the kind of -/// result and the label's length. -type RankKey = (bool, bool, u8, u8, u32, u8, usize, u8, usize); +/// of the same meaning it matched through, how often the result was picked (higher first), the +/// result's place among the recent picks, the kind of result and the label's length. +type RankKey = (bool, bool, u8, u8, u32, u8, std::cmp::Reverse, usize, u8, usize); /// The results of `entries` that the lowercased `query` matches, best first, as places in /// `entries`. A result matches when every word of the query is text in one of its names or ids @@ -705,12 +705,14 @@ type RankKey = (bool, bool, u8, u8, u32, u8, usize, u8, usize); /// worst grade a word gets, the sum of the grades, how the whole query matches when read with each /// word matched through a word of the same meaning replaced by that word ("colour" as "color"; of /// several such words the result holds, the ones that match the whole query best), -/// then by the result's place in `recent`, the places in `entries` of the recent picks, most -/// recent first (a result not in it comes after every result in it), then the kind of result -/// ([`kind`]), the label's length and the catalog order. So a recent pick ranks above the results -/// that match the query as well as it does and below every result that matches it better. An -/// empty query lists every result in catalog order. -pub(crate) fn rank(entries: &[Entry], index: &Index, query: &str, recent: &[u32]) -> Vec { +/// then by the grade in `uses` of how often the result was picked, highest first (`uses` holds one +/// grade per entry of `entries`, in their order; a missing grade is 0), then by the result's place +/// in `recent`, the places in `entries` of the recent picks, most recent first (a result not in it +/// comes after every result in it), then the kind of result ([`kind`]), the label's length and the +/// catalog order. So a result picked often, or recently, ranks above the results that match the +/// query as well as it does and below every result that matches it better. An empty query lists +/// every result in catalog order. +pub(crate) fn rank(entries: &[Entry], index: &Index, query: &str, recent: &[u32], uses: &[u8]) -> Vec { let query = normalize(query); if query.is_empty() { return (0..entries.len()).filter_map(|i| u32::try_from(i).ok()).collect(); @@ -858,7 +860,8 @@ pub(crate) fn rank(entries: &[Entry], index: &Index, query: &str, recent: &[u32] let meant_tier = if synonym { best_reading(&query, &starts, &tokens, &meant, |read| phrase(e, read, false)) } else { tier }; let length = split_name(&e.shown).0.chars().count(); let picked = recent.iter().position(|&r| r == place).unwrap_or(recent.len()); - ranked.push(((described, typo, tier, worst, sum, meant_tier, picked, e.kind, length), place)); + let used = std::cmp::Reverse(uses.get(i).copied().unwrap_or(0)); + ranked.push(((described, typo, tier, worst, sum, meant_tier, used, picked, e.kind, length), place)); } ranked.sort_by_key(|&(key, place)| (key, place)); ranked.into_iter().map(|(_, place)| place).collect() @@ -966,8 +969,15 @@ mod tests { /// The ids of the results `query` lists, best first, with the results of ids `picked` as the /// recent picks, most recent first. fn recently(c: &Catalog, query: &str, picked: &[&str]) -> Vec { + used(c, query, picked, &[]) + } + + /// The ids of the results `query` lists, best first, with the results of ids `picked` as the + /// recent picks, most recent first, and the results of ids `counted` given those use grades. + fn used(c: &Catalog, query: &str, picked: &[&str], counted: &[(&str, u8)]) -> Vec { let recent: Vec = picked.iter().filter_map(|id| c.list.iter().position(|e| e.id == *id)).filter_map(|i| u32::try_from(i).ok()).collect(); - rank(&c.list, &c.index, query, &recent).iter().filter_map(|&i| c.list.get(i as usize)).map(|e| e.id.clone()).collect() + let uses: Vec = c.list.iter().map(|e| counted.iter().find(|(id, _)| e.id == *id).map_or(0, |&(_, g)| g)).collect(); + rank(&c.list, &c.index, query, &recent, &uses).iter().filter_map(|&i| c.list.get(i as usize)).map(|e| e.id.clone()).collect() } /// A result named `name` (`›`-separated, its last part the label) with id `id`. @@ -1095,13 +1105,11 @@ mod tests { assert_eq!(ranked(&c, "same zz"), ranked(&c, "same zz")); } - /// For each pair of adjacent grades and whole-query tiers, a recent pick ranks above a result - /// that matches the query as well as it does and comes earlier in the catalog, and below the - /// result that matches better; of two such recent picks, the more recent ranks first. - #[test] - fn a_recent_pick_ranks_first_within_its_grades() { + /// For each pair of adjacent grades and whole-query tiers: a query, a result that matches it + /// better, one that matches it as the next grade or tier, and the description of the latter. + fn adjacent_grades() -> [(&'static str, Entry, Entry, &'static str); 14] { let description = "{} keeps the art central on the page"; - for (query, better, worse, said) in [ + [ ("cut zz", entry("Zz Cut", "a.one"), entry("Zz Cutter", "b.two"), ""), ("scale zz", entry("Zz Scale", "a.one"), entry("Zz Scaling", "b.two"), ""), ("scale zz", entry("Zz Scaling", "a.one"), entry("Zz Scalers", "scale.two"), ""), @@ -1120,7 +1128,15 @@ mod tests { ("remove", entry("Zz Remove", "a.one"), entry("Zz Delete", "b.two"), ""), // Matches through a word of the same meaning: the whole label, then a word of it. ("colour", entry("Color", "a.one"), entry("Zz Color", "b.two"), ""), - ] { + ] + } + + /// For each pair of adjacent grades and whole-query tiers, a recent pick ranks above a result + /// that matches the query as well as it does and comes earlier in the catalog, and below the + /// result that matches better; of two such recent picks, the more recent ranks first. + #[test] + fn a_recent_pick_ranks_first_within_its_grades() { + for (query, better, worse, said) in adjacent_grades() { let (b, w) = (better.id.clone(), worse.id.clone()); // A second result that matches as the worse one does and comes before it. let twin = entry(&worse.shown, &format!("{w}x")); @@ -1137,6 +1153,31 @@ mod tests { assert_eq!(recently(&c, "", &["b.two"]), ["a.one", "b.two"]); } + /// For each pair of adjacent grades and whole-query tiers, a result picked often ranks above a + /// result that matches the query as well as it does and comes earlier in the catalog, and below + /// the result that matches better, which was never picked. Of two such results, the + /// one with the higher use grade ranks first, and a recent pick ranks first only among results + /// of the same use grade. + #[test] + fn a_command_picked_often_ranks_first_within_its_grades() { + for (query, better, worse, said) in adjacent_grades() { + let (b, w) = (better.id.clone(), worse.id.clone()); + // A second result that matches as the worse one does and comes before it. + let twin = entry(&worse.shown, &format!("{w}x")); + let t = twin.id.clone(); + let c = described(vec![twin, worse, better], &[said, said, ""]); + let (b, w, t) = (b.as_str(), w.as_str(), t.as_str()); + assert_eq!(used(&c, query, &[], &[(w, 1)]), [b, w, t], "{query}: one pick ranks above none"); + assert_eq!(used(&c, query, &[], &[(w, 9), (t, 3)]), [b, w, t], "{query}: the higher grade first"); + assert_eq!(used(&c, query, &[], &[(w, 1), (t, 3)]), [b, t, w], "{query}: the higher grade first"); + assert_eq!(used(&c, query, &[w], &[(t, 1)]), [b, t, w], "{query}: a recent pick within its use grade"); + assert_eq!(used(&c, query, &[w], &[(w, 1), (t, 1)]), [b, w, t], "{query}: a recent pick within its use grade"); + } + // An empty query lists every result in catalog order. + let c = synthetic(vec![entry("Zz One", "a.one"), entry("Zz Two", "b.two")]); + assert_eq!(used(&c, "", &[], &[("b.two", 9)]), ["a.one", "b.two"]); + } + /// A query that is a menu's title ranks a result whose label holds it as a word above the items /// of that menu, which match only by their menu path. A query that names the menu with `›` /// still starts the item's name. @@ -1147,7 +1188,7 @@ mod tests { assert_eq!(ranked(&c, "object › pa"), ["a.one"]); let en = catalog(Lang::EN, false); for q in ["object", "effect", "select", "view", "type", "edit"] { - let first = rank(&en.list, &en.index, q, &[]).first().and_then(|&i| en.list.get(i as usize)).map(|e| e.shown.to_lowercase()); + let first = rank(&en.list, &en.index, q, &[], &[]).first().and_then(|&i| en.list.get(i as usize)).map(|e| e.shown.to_lowercase()); let label = first.as_deref().map(|n| split_name(n).0.to_string()).unwrap_or_default(); assert!(words(&label).any(|w| w.starts_with(q)), "{q}: {first:?}"); } @@ -1362,7 +1403,7 @@ mod tests { ] { assert!(substring_rule(&c, typo).is_empty(), "{typo} matched nothing before"); let top = |q: &str| ranked(&c, q).into_iter().take(4).collect::>(); - let spelled_right: Vec = rank(&c.list, &plain, word, &[]).iter().take(4).map(id).collect(); + let spelled_right: Vec = rank(&c.list, &plain, word, &[], &[]).iter().take(4).map(id).collect(); assert_eq!(top(typo), spelled_right, "{typo}"); assert!(place(&c, typo, tool).is_some_and(|p| p < 4), "{typo}: {:?}", ranked(&c, typo)); } @@ -1609,7 +1650,16 @@ mod tests { assert_eq!(first("outline text"), "type.createOutlines"); assert!(within("flip", "object.reflect", 3), "{:?}", ranked(&c, "flip")); assert!(within("combine", "object.pathfinder.unite", 3), "{:?}", ranked(&c, "combine")); - assert!(ranked(&c, "vectorize").iter().take(3).any(|id| id.starts_with("imageTrace.")), "{:?}", ranked(&c, "vectorize")); + // "vectorize" lists an image trace command in the first five, and only results whose label + // holds a word that is "trace" or stems to it rank above it. + let vectorize = ranked(&c, "vectorize"); + let trace_word = |w: &str| { + let w = w.to_lowercase(); + w == "trace" || stems(&w).iter().any(|s| s == "trace") + }; + let traced = |id: &String| c.list.iter().any(|e| &e.id == id && words(split_name(&e.shown).0).any(trace_word)); + let traces = vectorize.iter().position(|id| id.starts_with("imageTrace.")); + assert!(traces.is_some_and(|p| p < 5 && vectorize.get(..p).is_some_and(|above| above.iter().all(traced))), "{vectorize:?}"); assert_eq!(first("colour"), "panel:color", "{:?}", ranked(&c, "colour")); // A word that only starts other labels is in a group, and its labels follow the direct match. assert_eq!(first("unite"), "object.pathfinder.unite"); @@ -1923,7 +1973,7 @@ mod tests { let started = std::time::Instant::now(); let runs = 100; for _ in 0..runs { - std::hint::black_box(rank(&c.list, &c.index, q, &[])); + std::hint::black_box(rank(&c.list, &c.index, q, &[], &[])); } println!("{:>12}: {:?} per query", q.get(..12).unwrap_or(q), started.elapsed() / runs); } diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index f7bb31bd9e..6c4d7860e7 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -96,8 +96,9 @@ pub(crate) fn field_width(ui: &Ui) -> f32 { } /// The Corner Radius field of a live rectangle's properties: [`corner_radius`], which a new value -/// sets on those corners. The link behind it is the `singleCornerRadius` preference: off, a field -/// for each of the four corners follows, each setting its own corner. +/// sets on those corners. The link behind it is the `singleCornerRadius` preference: on, a Corner +/// menu follows that sets the kind of all four corners; off, a row for each of the four corners +/// follows, each with a radius field and a Corner menu that set its own corner. pub(crate) fn corner_radius_row(app: &mut VectorcraftApp, ui: &mut Ui, n: &Node, id: &str) { let fw = field_width(ui); let single = app.session.prefs.single_corner_radius; @@ -111,27 +112,97 @@ pub(crate) fn corner_radius_row(app: &mut VectorcraftApp, ui: &mut Ui, n: &Node, transform::set_pref(app, "singleCornerRadius", !single); } }); - if !single { + if single { + corner_kind_row(app, ui, n, id, fw); + } else { corner_fields(app, ui, n, id, fw); } } +/// The Corner menu of a live rectangle whose corners share one radius field: the kind of all four +/// corners, also while some of them are Direct-Selected, blank when they differ. A pick sets it on +/// every corner of each selected live rectangle ([`set_rectangle_kinds`]). +fn corner_kind_row(app: &mut VectorcraftApp, ui: &mut Ui, n: &Node, id: &str, width: f32) { + let Some(lc) = LiveCorners::of(n) else { return }; + let current = lc.style(&lc.all()).1; + ui.horizontal(|ui| { + dim_label(ui, tl!("Corner:")); + if let Some(kind) = corner_kind_menu(ui, (id, "kind"), tl!("Corner:"), current, width) { + set_rectangle_kinds(app, kind, None); + } + }); +} + +/// Set `kind` on corner `corner` (every corner for None) of each selected live rectangle +/// ([`set_rectangle_corners`]). +fn set_rectangle_kinds(app: &mut VectorcraftApp, kind: CornerKind, corner: Option) { + set_rectangle_corners(app, json!({"kind": kind}), corner); +} + +/// Run `object.setLiveShape` with `p` (a `kind` or `radius`) on corner `corner` (every corner for +/// None) of each selected live rectangle, leaving other selected objects as they are: one undo +/// step, or none when nothing changes. +fn set_rectangle_corners(app: &mut VectorcraftApp, mut p: Value, corner: Option) { + p["corners"] = corner.map_or(json!([0, 1, 2, 3]), |k| json!([k])); + // The edit the tool computes on another thread comes first: the rectangles are the ones + // selected after it. + match app.session.finish_tool_edit() { + Ok(reqs) => crate::canvas::apply_requests(app, Ok(reqs)), + Err(e) => { + app.status(e.to_string()); + return; + } + } + if app.session.active().is_none() { + return; + } + // The live rectangles of the selection when it runs, so an action that records it acts on the + // rectangles selected when it plays. + p["rectanglesOnly"] = json!(true); + if let Err(e) = app.run("object.setLiveShape", p) { + app.status(e); + } +} + +/// A menu of the corner kinds, `width` wide, showing `current` (blank for None) and named `name` +/// for screen readers. Returns the kind picked. +fn corner_kind_menu(ui: &mut Ui, id: impl std::hash::Hash, name: &str, current: Option, width: f32) -> Option { + let names: Vec<&str> = CornerKind::ALL.iter().map(|k| crate::dialogs::corners::kind_label(*k)).collect(); + let shown = current.map_or("", crate::dialogs::corners::kind_label); + crate::widgets::dropdown_names_named(ui, id, Some(name), shown, &names, width).and_then(|i| CornerKind::ALL.get(i).copied()) +} + /// The corners of a live rectangle in the order their fields show, with their labels. fn rectangle_corners() -> [(usize, &'static str); 4] { [(0, tl!("Top Left:")), (1, tl!("Top Right:")), (2, tl!("Bottom Right:")), (3, tl!("Bottom Left:"))] } -/// One Corner Radius field per corner of a live rectangle, each on its own row with its label, -/// the fields in line. +/// One Corner Radius field and one Corner menu per corner of a live rectangle, each pair on its own +/// row with the corner's label, the fields and menus in line; in a panel too narrow for that, each +/// menu goes on the row under its field. A value typed or a kind picked is set on that corner +/// alone, of each selected live rectangle ([`set_rectangle_corners`]). fn corner_fields(app: &mut VectorcraftApp, ui: &mut Ui, n: &Node, id: &str, width: f32) { let Some(lc) = LiveCorners::of(n) else { return }; let unit = app.session.general_unit(); - egui::Grid::new((id, "corners")).num_columns(2).spacing(vec2(6.0, 4.0)).show(ui, |ui| { + let widest = |names: &mut dyn Iterator| names.map(|t| crate::widgets::dim_label_width(ui, t)).fold(0.0, f32::max); + let labels = widest(&mut rectangle_corners().into_iter().map(|(_, label)| label)); + // The longest kind name, with the room the menu's button gives around it and its arrow. + let menu_width = width.max(widest(&mut CornerKind::ALL.into_iter().map(crate::dialogs::corners::kind_label)) + 26.0); + // The two gaps between the grid's three columns are 6 points each. + let in_line = labels + width + menu_width + 12.0 <= ui.available_width(); + egui::Grid::new((id, "corners")).num_columns(if in_line { 3 } else { 2 }).spacing(vec2(6.0, 4.0)).show(ui, |ui| { for (k, label) in rectangle_corners() { dim_label(ui, label); if let Some(v) = crate::widgets::num_field_named(ui, (id, "corner", k), Some(label), Some(lc.radius(k)), unit, width) { // A negative radius typed in rounds nothing: the command takes 0 or more. - app.run("object.setLiveShape", json!({"radius": v.max(0.0), "corners": [k]})).ok(); + set_rectangle_corners(app, json!({"radius": v.max(0.0)}), Some(k)); + } + if !in_line { + ui.end_row(); + ui.label(""); + } + if let Some(kind) = corner_kind_menu(ui, (id, "kind", k), label, Some(lc.kind(k)), menu_width) { + set_rectangle_kinds(app, kind, Some(k)); } ui.end_row(); } @@ -341,10 +412,10 @@ pub(crate) fn current_paints(app: &VectorcraftApp) -> (Paint, Paint) { /// document revision, Appearance panel item and picked gradient mesh points (picking points /// changes no revision). pub(crate) fn mixed_paints(app: &VectorcraftApp, ctx: &egui::Context) -> (bool, bool) { - type Key = (u64, u64, Option, Vec<(NodeId, Vec)>, &'static str); + type Key = (u64, u64, Option, Vec<(NodeId, Vec)>, bool); let Some(st) = app.session.active() else { return (false, false) }; - // The tool too: while the Live Paint Bucket is active the proxies show its colors. - let key: Key = (st.uid, st.revision, app.session.appearance_item(), app.session.fill_mesh_points(), app.session.tool_id()); + // Whether the proxies show the Live Paint Bucket's colors too. + let key: Key = (st.uid, st.revision, app.session.appearance_item(), app.session.fill_mesh_points(), app.session.bucket_paints()); match pstate::>(ctx, "proxy-mixed") { Some((k, mixed)) if k == key => mixed, _ => { @@ -373,7 +444,7 @@ pub(crate) fn stroke_mixed(app: &VectorcraftApp, ctx: &egui::Context) -> StrokeM if character::text_editing(app).is_some() { return StrokeMixed { can_align: true, ..Default::default() }; } - if app.session.tool_id() == "livePaintBucket" { + if app.session.bucket_paints() { return StrokeMixed { can_align: true, ..Default::default() }; } let Some(st) = app.session.active() else { return StrokeMixed::default() }; @@ -819,6 +890,10 @@ mod tests_color_wheel; #[cfg(test)] mod tests_color_wheel_box; #[cfg(test)] +mod tests_color_wheel_document_colors; +#[cfg(test)] +mod tests_color_wheel_gamut; +#[cfg(test)] mod tests_color_wheel_harmony; #[cfg(test)] mod tests_color_wheel_vision; diff --git a/crates/ui-egui/src/panels/actions.rs b/crates/ui-egui/src/panels/actions.rs index b4bfc4a5b5..d5d759c9ed 100644 --- a/crates/ui-egui/src/panels/actions.rs +++ b/crates/ui-egui/src/panels/actions.rs @@ -1267,8 +1267,12 @@ pub const INSERT_MENU_ITEM: &str = "ui.action.insertMenuItem"; /// runs. An Object › Align item's step holds the params that clicking the item sends now /// ([`crate::panels::align::menu_align_params`]): with whole objects selected, the `to` of the key /// object, the artboard or the selection, so a later Align To choice does not change the step, and a -/// step that aligns to the key object fails in playback when there is none then. A View menu item that the app runs itself -/// ([`crate::menus::plays_in_app`]) plays on its own, with no undo step ([`play`]). The place is as +/// step that aligns to the key object fails in playback when there is none then. An Effect › +/// Pathfinder item's step holds the Pathfinder Options in force now +/// ([`crate::dialogs::pathfinder_options::menu_effect_params`]), as clicking the item applies the +/// effect with them, so a later Pathfinder Options change does not change the step. A View menu +/// item that the app runs itself ([`crate::menus::plays_in_app`]) plays on its own, with no undo +/// step ([`play`]). The place is as /// [`insert_stop`] takes it, and the step is selected as a stop is. A command and params that no such /// item has, a param of another type, params that are not an object, or a place [`insert_stop`] /// refuses is an error, and then nothing changes. Insert Menu Item's OK runs this. → {set, action, @@ -1287,7 +1291,11 @@ pub fn insert_menu_item(app: &mut VectorcraftApp, p: &Value) -> Result super::align::menu_align_params(app, params), + "effect.apply" => crate::dialogs::pathfinder_options::menu_effect_params(app, params), + _ => params, + }; insert(app, p, (command.to_string(), params)) } @@ -6628,7 +6636,8 @@ mod tests { /// A listed menu item runs from the menu what its step runs in playback: the click opens no /// dialog, and it journals the item's own command with the params its step holds. An Object › - /// Align item's step holds the Align To choice that the click sends, and the app adds the active + /// Align item's step holds the Align To choice that the click sends, an Effect › Pathfinder + /// item's step holds the Pathfinder Options that the click applies, and the app adds the active /// artboard to both. #[test] fn every_listed_menu_item_runs_from_the_menu_what_its_step_holds() { @@ -6666,6 +6675,62 @@ mod tests { assert_eq!(steps[4], ("object.align".to_string(), json!({"horizontal": "left", "to": "selection"}))); } + /// An Effect › Pathfinder item's step holds the Pathfinder Options in force at insertion, as the + /// click applies the effect with them: a later Pathfinder Options change does not change the step, + /// and playback applies the effect with the step's options. + #[test] + fn an_inserted_pathfinder_effect_item_keeps_the_pathfinder_options_of_its_insertion() { + let (mut app, _, ids) = app_with_two_rectangles(); + app.run("select.set", json!({ "ids": ids })).unwrap(); + app.run("object.pathfinder.options", json!({"precision": 0.5, "removeRedundantPoints": true})).unwrap(); + app.ui.action_sets[0].actions[0].steps.clear(); + app.run(INSERT_MENU_ITEM, json!({"set": 0, "action": 0, "command": "effect.apply", "params": {"effect": "pathfinder.add"}})).unwrap(); + app.run("object.pathfinder.options", json!({"precision": 0.01, "removeRedundantPoints": false})).unwrap(); + let options = json!({"precision": 0.5, "removeRedundantPoints": true, "removeUnpainted": false}); + let held = json!({"effect": "pathfinder.add", "params": options}); + assert_eq!(app.ui.action_sets[0].actions[0].steps, [("effect.apply".to_string(), held)]); + app.run("select.set", json!({ "ids": ids })).unwrap(); + app.run("object.group", json!({})).unwrap(); + play(&mut app, 0, 0).unwrap(); + let group = app.session.doc().unwrap().selection.objects[0]; + let effects = &app.session.doc().unwrap().doc.node(group).unwrap().appearance.effects; + assert_eq!((effects.len(), effects[0].id.as_str(), &effects[0].params), (1, "pathfinder.add", &options)); + } + + /// Every Effect › Pathfinder item's step holds the Pathfinder Options that clicking the item + /// journals, with options other than the defaults in force. + #[test] + fn every_pathfinder_effect_item_step_holds_the_options_its_click_applies() { + let options = json!({"precision": 0.25, "removeRedundantPoints": false, "removeUnpainted": true}); + let items: Vec<_> = crate::menus::insertable_items(false) + .into_iter() + .filter(|item| { + item.command == "effect.apply" + && item.params.get("effect").and_then(Value::as_str).is_some_and(vectorcraft_effects::takes_pathfinder_options) + }) + .collect(); + assert!(!items.is_empty()); + for item in items { + let (mut app, _, ids) = app_with_two_rectangles(); + app.run("object.pathfinder.options", options.clone()).unwrap(); + app.ui.action_sets[0].actions[0].steps.clear(); + app.run(INSERT_MENU_ITEM, json!({"set": 0, "action": 0, "command": item.command, "params": item.params})).unwrap(); + let held = app.ui.action_sets[0].actions[0].steps[0].1.clone(); + assert_eq!(held["params"], options, "{item:?}"); + app.run("select.set", json!({ "ids": ids })).unwrap(); + let start = app.session.journal.len(); + crate::menus::invoke(&mut app, item.command, item.params.clone()); + let ran: Vec<_> = app.session.journal_for_action(start).into_iter().filter(|(c, _)| c == item.command).collect(); + assert!(!ran.is_empty(), "{item:?} did not run"); + for (_, mut p) in ran { + if let Some(o) = p.as_object_mut() { + o.remove("artboard"); + } + assert_eq!(p, held, "{item:?}"); + } + } + } + /// With anchor points selected, an Object › Align item sends its params unchanged, and the points /// align to their own bounds: its step holds the same params, without the Align To choice. #[test] diff --git a/crates/ui-egui/src/panels/appearance.rs b/crates/ui-egui/src/panels/appearance.rs index 938a805c83..16b0f1f7f2 100644 --- a/crates/ui-egui/src/panels/appearance.rs +++ b/crates/ui-egui/src/panels/appearance.rs @@ -488,7 +488,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { _ => None, }; let label = match style { - Some(name) => std::borrow::Cow::Owned(format!("{label}: {name}")), + Some(name) => std::borrow::Cow::Owned(format!("{} {name}", crate::i18n::colon(label))), None => std::borrow::Cow::Borrowed(label), }; if !hide_thumb { @@ -1239,9 +1239,10 @@ fn effect_row(app: &mut VectorcraftApp, ui: &mut Ui, item: Option, k: usi (row_rect, resp) } -/// Does the effect have a dialog (any parameters)? +/// Does the effect have a dialog (any parameters, or a Pathfinder effect's Pathfinder Options)? fn has_options(id: &str) -> bool { - vectorcraft_effects::default_params(id).is_some_and(|d| d.as_object().is_some_and(|o| !o.is_empty())) + vectorcraft_effects::takes_pathfinder_options(id) + || vectorcraft_effects::default_params(id).is_some_and(|d| d.as_object().is_some_and(|o| !o.is_empty())) } /// Inline editor for an applied effect's parameters, labeled as the effect dialogs' generic fields diff --git a/crates/ui-egui/src/panels/appearance/tests.rs b/crates/ui-egui/src/panels/appearance/tests.rs index 67bea32636..4816d0838d 100644 --- a/crates/ui-egui/src/panels/appearance/tests.rs +++ b/crates/ui-egui/src/panels/appearance/tests.rs @@ -915,6 +915,13 @@ fn with_nothing_selected_it_lists_what_new_art_gets() { for want in ["No Selection: Fancy".to_string(), effect_label("stylize.dropShadow"), "Opacity: 50%".into(), "Dashed".into()] { assert!(shown.contains(&want), "{want} in {shown:?}"); } + // The style name follows the UI language's colon (#7991). + let fr = crate::i18n::Lang::from_code("fr").unwrap(); + crate::i18n::set_current(fr); + let shown = frame(&mut app); + crate::i18n::set_current(crate::i18n::Lang::EN); + let want = format!("{}\u{a0}: Fancy", crate::i18n::tr(fr, "No Selection")); + assert!(shown.contains(&want), "{want} in {shown:?}"); } /// Both stroke rows expose named Weight inputs, and the drop-shadow effect names its Blur input and diff --git a/crates/ui-egui/src/panels/brushes.rs b/crates/ui-egui/src/panels/brushes.rs index 7bc9ebad21..eb4b882ad0 100644 --- a/crates/ui-egui/src/panels/brushes.rs +++ b/crates/ui-egui/src/panels/brushes.rs @@ -199,13 +199,21 @@ fn multi(app: &VectorcraftApp, ctx: &egui::Context, list: &[(String, String)], c set_pstate(ctx, "br-selected", (None::>, None::)); return None; } - let (names, _): (Option>, Option) = pstate(ctx, "br-selected"); + let (names, key): (Option>, Option) = pstate(ctx, "br-selected"); let names = names?; if names.is_empty() { return Some(names); } + let orig_len = names.len(); let kept: Vec = names.into_iter().filter(|n| list.iter().any(|b| &b.0 == n)).collect(); - (!kept.is_empty()).then_some(kept) + if kept.is_empty() { + set_pstate(ctx, "br-selected", (None::>, key)); + return None; + } + if kept.len() != orig_len { + set_pstate(ctx, "br-selected", (Some(kept.clone()), key)); + } + Some(kept) } /// The brushes Delete Brush and Duplicate Brush act on: the multi-selection, else the selected @@ -300,6 +308,53 @@ fn replace_drop(ui: &Ui, resp: &egui::Response, name: &str, ty: &str, replaced: } } +/// A brush item's right-click context menu. +fn item_context_menu(app: &mut VectorcraftApp, ui: &mut Ui, name: &str) { + let (current_list, current) = brushes(app); + let multi_names = multi(app, ui.ctx(), ¤t_list, current.as_deref()); + let is_multi = multi_names.as_ref().is_some_and(|m| m.len() > 1 && m.iter().any(|b| b == name)); + let targets = if is_multi { multi_names.unwrap_or_default() } else { vec![name.to_string()] }; + + let all_exist = app.session.active().is_some_and(|st| { + let lib = vectorcraft_brush::library(&st.doc); + targets.iter().all(|n| lib.iter().any(|b| &b.name == n)) + }); + + let can_delete = all_exist && targets.len() < current_list.len() && current_list.len() > 1; + let can_duplicate = all_exist; + + if is_multi { + if menu_item(ui, tl!("Duplicate Brushes"), can_duplicate, false) { + if let Err(e) = app.run("brush.duplicate", json!({ "names": targets })) { + app.status(e); + } + ui.close(); + } + if menu_item(ui, tl!("Delete Brushes"), can_delete, false) { + delete(app, &targets, true); + ui.close(); + } + } else { + let can_options = all_exist; + if menu_item(ui, tl!("Brush Options…"), can_options, false) { + if let Err(e) = app.run("ui.brushOptions", json!({ "name": name })) { + app.status(e); + } + ui.close(); + } + if menu_item(ui, tl!("Duplicate Brush"), can_duplicate, false) { + if let Err(e) = app.run("brush.duplicate", json!({ "name": name })) { + app.status(e); + } + ui.close(); + } + if menu_item(ui, tl!("Delete Brush"), can_delete, false) { + delete(app, &[name.to_string()], true); + ui.close(); + } + } +} + pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let t = Tokens::get(ui.ctx()); let (list, current) = brushes(app); @@ -316,6 +371,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let mut options: Option = None; let mut moved: Option = None; let mut replaced: Option<(String, Vec)> = None; + let mut secondary_selected: Option = None; let list_rect = widgets::list_box(ui, |ui| { ui.set_min_height(110.0); ui.set_width(ui.available_width()); @@ -366,8 +422,25 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { resp.on_hover_text(name) }; // A click applies or selects the brush; the second click of a double-click opens its - // options. + // options; a right-click selects if unselected and displays its item context menu. let mut pick = |resp: egui::Response, name: &String| { + if resp.secondary_clicked() { + let is_selected = match &multi { + Some(m) => m.iter().any(|b| b == name), + None => sel_brush.as_deref() == Some(name) || (sel_brush.is_none() && current.as_deref() == Some(name)), + }; + if !is_selected { + set_pstate(&resp.ctx, "br-anchor", name.clone()); + if let Err(e) = app.run("brush.setCurrent", json!({ "name": name })) { + app.status(e); + } + let now = brushes(app).1; + let key = click_key(app, now.as_deref()); + set_pstate(&resp.ctx, "br-selected", (Some(vec![name.clone()]), key)); + secondary_selected = Some(name.clone()); + } + } + resp.context_menu(|ui| item_context_menu(app, ui, name)); if resp.double_clicked() { options = Some(name.clone()); } else if resp.clicked() { @@ -417,6 +490,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { { app.status(e); } + if let Some(name) = secondary_selected { + multi = Some(vec![name]); + } let highlighted = sel_brush.clone().or(current.clone()); match clicked { // Shift and Cmd/Ctrl only select, as in the Swatches panel: they start from the diff --git a/crates/ui-egui/src/panels/brushes/tests.rs b/crates/ui-egui/src/panels/brushes/tests.rs index a6dc1c304c..28357bca63 100644 --- a/crates/ui-egui/src/panels/brushes/tests.rs +++ b/crates/ui-egui/src/panels/brushes/tests.rs @@ -888,3 +888,135 @@ fn rows_of_two_brushes_with_one_name_show_the_first() { assert_eq!(shown.ty, "art"); assert_eq!(shown.def, got, "the first of two rows of one name is the one shown"); } + +/// Right-clicking a brush in the Brushes panel selects it (if unselected), displays +/// the context menu ("Brush Options…", "Duplicate Brush", "Delete Brush"), and clicking +/// an item dispatches the corresponding command. Multi-selection right-click preserves +/// selection and offers "Duplicate Brushes" / "Delete Brushes". "Delete Brush" is disabled +/// when it is the last brush in the library. +#[test] +fn right_click_context_menu_in_brushes_panel() { + use egui_kittest::kittest::{NodeT, Queryable}; + + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 40})).unwrap(); + app.run("brush.apply", json!({"name": "Tapered Stroke"})).unwrap(); + + let mut h = egui_kittest::Harness::builder().with_size(vec2(260.0, 500.0)).with_accessibility_check(false).build_ui_state( + |ui, app: &mut VectorcraftApp| { + show(app, ui); + }, + app, + ); + h.run_steps(2); + + let right_click = |h: &mut egui_kittest::Harness<'static, VectorcraftApp>, label: &str| { + let node = h.get_by_label(label); + let pos = node.rect().center(); + h.event(egui::Event::PointerMoved(pos)); + h.event(egui::Event::PointerButton { pos, button: egui::PointerButton::Secondary, pressed: true, modifiers: Default::default() }); + h.event(egui::Event::PointerButton { pos, button: egui::PointerButton::Secondary, pressed: false, modifiers: Default::default() }); + h.run_steps(2); + }; + + // 1. Initial state: artwork uses Tapered Stroke; Charcoal is not current + assert_eq!(selected_brush(h.state()).as_deref(), Some("Tapered Stroke")); + assert_ne!(brushes(h.state_mut()).1.as_deref(), Some("Charcoal")); + + // Right-click unselected "Charcoal" + right_click(&mut h, "Charcoal"); + + // Right-clicking selects Charcoal in panel without applying it to the selected artwork + assert_eq!(brushes(h.state_mut()).1.as_deref(), Some("Charcoal")); + assert_eq!(selected_brush(h.state()).as_deref(), Some("Tapered Stroke"), "right-click must not apply brush to artwork"); + let (multi_sel, _): (Option>, Option) = pstate(&h.ctx, "br-selected"); + assert_eq!(multi_sel, Some(vec!["Charcoal".to_string()]), "right-clicked brush is recorded as panel selection"); + let (b_list, b_cur) = brushes(h.state_mut()); + assert_eq!(targets(h.state(), &h.ctx, &b_list, b_cur.as_deref()), vec!["Charcoal".to_string()]); + + // Context menu displays Brush Options…, Duplicate Brush, Delete Brush + let opt = h.get_by_label(" Brush Options…"); + let dup = h.get_by_label(" Duplicate Brush"); + let del = h.get_by_label(" Delete Brush"); + assert!(!opt.accesskit_node().is_disabled()); + assert!(!dup.accesskit_node().is_disabled()); + assert!(!del.accesskit_node().is_disabled()); + + // 2. Click "Duplicate Brush" dispatches brush.duplicate and adds a copy + dup.click(); + h.run_steps(2); + + let all_names = names(h.state_mut()); + assert!(all_names.contains(&"Charcoal copy".to_string())); + + // 3. Right-click "Charcoal copy" and click "Delete Brush" + right_click(&mut h, "Charcoal copy"); + + let undo_before = undo_count(h.state()); + h.get_by_label(" Delete Brush").click(); + h.run_steps(2); + + assert!(!names(h.state_mut()).contains(&"Charcoal copy".to_string())); + assert_eq!(undo_count(h.state()), undo_before + 1); + + // Undo restores the deleted copy + h.state_mut().run("edit.undo", json!({})).unwrap(); + assert!(names(h.state_mut()).contains(&"Charcoal copy".to_string())); + + // 4. Click "Brush Options…" opens the Brush Options dialog + right_click(&mut h, "Charcoal"); + h.get_by_label(" Brush Options…").click(); + h.run_steps(2); + + assert_eq!(h.state().ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(crate::dialogs::brush_options::KIND)); + assert_eq!(h.state().ui.dialog.as_ref().unwrap().str("name"), "Charcoal"); + crate::dialogs::cancel(h.state_mut()); + assert!(h.state().ui.dialog.is_none()); + + // 5. Multi-selection: right-clicking within multi-selection preserves it and offers + // "Duplicate Brushes" and "Delete Brushes" + let cur = brushes(h.state_mut()).1; + let key = click_key(h.state(), cur.as_deref()); + set_pstate(&h.ctx, "br-selected", (Some(vec!["Charcoal".to_string(), "Tapered Stroke".to_string()]), key)); + h.run_steps(1); + + right_click(&mut h, "Tapered Stroke"); + + let (multi_sel, _): (Option>, Option) = pstate(&h.ctx, "br-selected"); + assert_eq!(multi_sel, Some(vec!["Charcoal".to_string(), "Tapered Stroke".to_string()])); + + let dup_multi = h.get_by_label(" Duplicate Brushes"); + let del_multi = h.get_by_label(" Delete Brushes"); + assert!(!dup_multi.accesskit_node().is_disabled()); + assert!(!del_multi.accesskit_node().is_disabled()); + + // Click Duplicate Brushes + dup_multi.click(); + h.run_steps(2); + + let all_names = names(h.state_mut()); + assert!(all_names.contains(&"Charcoal copy 2".to_string())); + assert!(all_names.contains(&"Tapered Stroke copy".to_string())); + + // 6. Delete a brush in use by artwork prompts with the brushDelete confirmation dialog + h.state_mut().run("brush.apply", json!({ "name": "Tapered Stroke" })).unwrap(); + assert_eq!(selected_brush(h.state()).as_deref(), Some("Tapered Stroke")); + right_click(&mut h, "Tapered Stroke"); + h.get_by_label(" Delete Brush").click(); + h.run_steps(2); + assert_eq!(h.state().ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(crate::dialogs::brush_delete::KIND)); + crate::dialogs::cancel(h.state_mut()); + assert!(names(h.state_mut()).contains(&"Tapered Stroke".to_string())); + + // 7. Delete Brush is disabled when it is the last brush in the library + let current_brushes = names(h.state_mut()); + let to_delete: Vec = current_brushes.into_iter().filter(|n| n != "Charcoal").collect(); + h.state_mut().run("brush.delete", json!({ "names": to_delete })).unwrap(); + assert_eq!(names(h.state_mut()), vec!["Charcoal".to_string()]); + + h.run_steps(2); + right_click(&mut h, "Charcoal"); + let del_last = h.get_by_label(" Delete Brush"); + assert!(del_last.accesskit_node().is_disabled(), "last remaining brush cannot be deleted"); +} diff --git a/crates/ui-egui/src/panels/color/tests.rs b/crates/ui-egui/src/panels/color/tests.rs index 07295dc256..32897c03e5 100644 --- a/crates/ui-egui/src/panels/color/tests.rs +++ b/crates/ui-egui/src/panels/color/tests.rs @@ -999,6 +999,12 @@ fn a_mixed_selection_has_no_colour_to_edit() { frame(&mut app, &ctx, vec![], egui::Modifiers::NONE); assert_eq!(crate::panels::mixed_paints(&app, &ctx), (true, false)); let _ = ctx.run_ui(Default::default(), |ui| assert_eq!(target(&app, ui).color(), None)); + // The Eyedropper armed for a stop of the Live Paint Bucket's gradient shows the bucket's color. + app.select_tool("eyedropper"); + assert_eq!(crate::panels::mixed_paints(&app, &ctx), (true, false)); + app.session.set_tool_option("stop", &json!("livePaintBucket")); + assert_eq!(crate::panels::mixed_paints(&app, &ctx), (false, false), "arming the pick recomputes it"); + app.session.set_tool_option("stop", &serde_json::Value::Null); app.run("paint.setFill", json!({"color": "#0000ff"})).unwrap(); assert_eq!(crate::panels::mixed_paints(&app, &ctx), (false, false), "a new revision recomputes it"); } diff --git a/crates/ui-egui/src/panels/color_wheel.rs b/crates/ui-egui/src/panels/color_wheel.rs index 028652c9bb..c868f0e2c7 100644 --- a/crates/ui-egui/src/panels/color_wheel.rs +++ b/crates/ui-egui/src/panels/color_wheel.rs @@ -12,6 +12,11 @@ //! Brightness, Red, Green or Blue). The field shows the other two components on the Color //! Picker's axes. //! +//! Show Out-of-Gamut Colors grays out the cells of the wheel's square and the box's field whose +//! colors the CMYK space cannot print, by the out-of-gamut warning's test ([`Cms::out_of_gamut`]), +//! on a [`GAMUT_CELLS`] by [`GAMUT_CELLS`] grid kept until the channel, its value, the color +//! settings or the loaded profiles change. +//! //! Show Harmony puts a marker on the ring for each other color of the harmony rule picked under //! Harmony Rule (the Color Guide's rules whose colors each have a hue of their own), filled with //! that color. The markers follow the current color, and a click on one applies its color as a @@ -22,15 +27,34 @@ //! Setup uses, and for achromatopsia as the gray with the color's CIE L*. The chips only show the //! simulation. //! -//! The view, the channel, Show Harmony, Harmony Rule and Show Color Vision Preview are kept with -//! the preferences (`ui.colorWheel`). +//! The panel menu's Show Document Colors adds a row under the wheel or the box with the colors +//! of the selection, or with nothing selected of the art Select All takes, most used first +//! (`color.used`). A click on one applies it as a pick does. The active proxy and a selected +//! gradient stop keep its swatch link; a freeform point takes the color alone. +//! +//! Panel menu › OKLCH Sliders shows L, C and H rows under the wheel or the box that edit the color +//! by OKLCH lightness, chroma and hue (CSS Color 4: +//! ), while the active document's RGB +//! space ([`cms::active`]: the profile assigned to the document, else the working RGB space of the +//! color settings) is sRGB. Panel menu › HSL Sliders shows H, S and L rows in their place that edit the color by the +//! hue, saturation and lightness of CSS Color 4's HSL +//! (). The choice is kept with the +//! preferences too. +//! +//! The view, the channel, the slider rows, Show Out-of-Gamut Colors, Show Harmony, Harmony Rule, +//! Show Color Vision Preview and Show Document Colors are kept with the preferences +//! (`ui.colorWheel`). -use egui::{Rect, Sense, Stroke, StrokeKind, Ui, UiBuilder, vec2}; +use std::hash::{Hash, Hasher}; +use std::sync::Arc; + +use egui::{Color32, Rect, Sense, Stroke, StrokeKind, Ui, UiBuilder, pos2, vec2}; use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; -use vectorcraft_color::cms::{self, Cms, ProofSetup, ProofTarget}; +use vectorcraft_color::cms::{self, Cms, ColorSettings, ProofSetup, ProofTarget}; use vectorcraft_color::harmony::Harmony; -use vectorcraft_color::{Color, Paint, hsb_to_rgb, rgb_to_hsb}; +use vectorcraft_color::oklab::{self, CHROMA_FULL}; +use vectorcraft_color::{Color, Paint, hsb_to_rgb, hsl_to_rgb, rgb_to_hsb, rgb_to_hsl}; use vectorcraft_doc::{ColorMode, NodeId}; use super::color::{Target, apply, wheel_target}; @@ -82,6 +106,11 @@ pub struct Settings { pub view: View, #[serde(serialize_with = "serialize_channel", deserialize_with = "deserialize_channel")] pub channel: Channel, + #[serde(deserialize_with = "deserialize_sliders")] + pub sliders: Sliders, + /// Show Out-of-Gamut Colors: gray out the colors the CMYK space cannot print. + #[serde(deserialize_with = "deserialize_flag")] + pub gamut: bool, /// Show Harmony: markers on the ring for the other colors of `harmony_rule`. #[serde(deserialize_with = "deserialize_flag")] pub harmony: bool, @@ -92,11 +121,57 @@ pub struct Settings { /// `true` shows the row and any other value hides it. #[serde(deserialize_with = "crate::panels::color::deserialize_rgb_percent")] pub vision: bool, + /// Show Document Colors: the row of the colors the art uses, under the wheel or the box. + #[serde(deserialize_with = "deserialize_flag")] + pub document_colors: bool, +} + +/// The slider rows under the wheel or the box (panel menu, `ui.colorWheel {sliders}`). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase")] +pub enum Sliders { + #[default] + None, + /// OKLCH Sliders: lightness, chroma and hue. + Oklch, + /// HSL Sliders: hue, saturation and lightness. + Hsl, +} + +impl Sliders { + pub const ALL: [Sliders; 3] = [Sliders::None, Sliders::Oklch, Sliders::Hsl]; + + /// The id `ui.colorWheel` and the preferences use. + pub fn id(self) -> &'static str { + match self { + Sliders::None => "none", + Sliders::Oklch => "oklch", + Sliders::Hsl => "hsl", + } + } + + pub fn parse(s: &str) -> Option { + Self::ALL.into_iter().find(|v| v.id() == s) + } +} + +fn deserialize_sliders<'de, D: serde::Deserializer<'de>>(d: D) -> Result { + let v = ::deserialize(d)?; + Ok(v.as_str().and_then(Sliders::parse).unwrap_or_default()) } impl Default for Settings { fn default() -> Self { - Self { view: View::default(), channel: Channel::default(), harmony: false, harmony_rule: Harmony::Complementary, vision: false } + Self { + view: View::default(), + channel: Channel::default(), + sliders: Sliders::default(), + gamut: false, + harmony: false, + harmony_rule: Harmony::Complementary, + vision: false, + document_colors: false, + } } } @@ -146,12 +221,23 @@ pub fn deserialize_settings<'de, D: serde::Deserializer<'de>>(d: D) -> Result Result { - const KEYS: [&str; 5] = ["view", "channel", "harmony", "harmonyRule", "vision"]; + set(&mut app.ui.color_wheel, p, &cms::active())?; + Ok(json!(app.ui.color_wheel)) +} + +/// Set the keys of `ui.colorWheel` params `p` in `settings`, with the color settings `cms`; on an +/// error `settings` stay as they were. +pub(crate) fn set(settings: &mut Settings, p: &Value, cms: &Cms) -> Result<(), String> { + const KEYS: [&str; 8] = ["view", "channel", "sliders", "gamut", "harmony", "harmonyRule", "vision", "documentColors"]; match p { Value::Null => {} Value::Object(o) => { @@ -161,7 +247,7 @@ pub(crate) fn command(app: &mut VectorcraftApp, p: &Value) -> Result return Err(format!("the params must be an object, not {got}")), } - let mut set = app.ui.color_wheel.clone(); + let mut set = settings.clone(); match p.get("view") { None | Some(Value::Null) => {} Some(v) => set.view = v.as_str().and_then(View::parse).ok_or("`view` must be wheel or box")?, @@ -170,6 +256,21 @@ pub(crate) fn command(app: &mut VectorcraftApp, p: &Value) -> Result {} Some(v) => set.channel = v.as_str().and_then(Channel::parse).ok_or("`channel` must be hue, saturation, brightness, red, green or blue")?, } + match p.get("sliders") { + None | Some(Value::Null) => {} + Some(v) => { + let sliders = v.as_str().and_then(Sliders::parse).ok_or("`sliders` must be none, oklch or hsl")?; + if sliders == Sliders::Oklch && !cms.rgb_is_srgb() { + return Err(OKLCH_NEEDS_SRGB.to_string()); + } + set.sliders = sliders; + } + } + let key = "gamut"; + match p.get(key) { + None | Some(Value::Null) => {} + Some(v) => set.gamut = v.as_bool().ok_or_else(|| format!("`{key}` must be true or false"))?, + } let key = "harmony"; match p.get(key) { None | Some(Value::Null) => {} @@ -188,12 +289,16 @@ pub(crate) fn command(app: &mut VectorcraftApp, p: &Value) -> Result; + +/// The row's colors as last read, kept in the panel state behind an `Arc`, so a frame that reads +/// them back copies no list. +#[derive(Debug, PartialEq)] +struct UsedCache { + key: UsedKey, + /// The frame time the colors were read at. + at: f64, + /// The uses of every color (`color.used`'s `uses`). + uses: u64, + /// Whether the colors are the selection's. + selected: bool, + /// The most colors asked for. + limit: usize, + colors: Vec, +} + +/// A color of the row: the color, its hex value, how many times the art uses it, and the global +/// swatch it is linked to with the tint (0..1) of that swatch it is. +#[derive(Clone, Debug, PartialEq)] +struct Used { + color: Color, + hex: String, + count: u64, + link: Option<(String, f32)>, +} + +impl Used { + /// The paint the color applies and drags: linked to its swatch at its tint when it has one. + fn paint(&self) -> Paint { + match &self.link { + Some((name, tint)) => Paint::Solid { color: self.color, swatch: Some(name.clone()), tint: *tint }, + None => Paint::solid(self.color), + } + } +} + +/// The colors the row shows and whether they are the selection's, read with `color.used` once per +/// document revision and selection and kept as they are while an interaction is in progress (a +/// preview raises the revision on every frame of a drag). In art with more than [`LARGE_USES`] +/// color uses, an edit reads them again only after [`LARGE_EVERY`] seconds. A row that holds more +/// than the colors last asked for reads them again once no interaction is in progress, and in such +/// art only after the same wait. +fn used_colors(app: &mut VectorcraftApp, ui: &Ui, per_row: usize) -> Arc { + let limit = per_row.max(MAX_CHIPS); + let key: UsedKey = app.session.active().map(|d| { + let mut h = std::collections::hash_map::DefaultHasher::new(); + d.selection.objects.hash(&mut h); + (d.uid, d.revision, d.selection.objects.len(), h.finish()) + }); + let now = ui.input(|i| i.time); + if let Some(cache) = pstate::>>(ui.ctx(), USED) { + let fits = cache.limit >= per_row || cache.colors.len() < cache.limit; + if app.session.in_interaction() || (cache.key == key && fits) { + return cache; + } + let scope = |k: &UsedKey| k.map(|(doc, _, n, h)| (doc, n, h)); + let wait = LARGE_EVERY - (now - cache.at); + if cache.uses > LARGE_USES && scope(&cache.key) == scope(&key) && wait > 0.0 { + ui.ctx().request_repaint_after_secs(wait as f32); + return cache; + } + } + let r = key.as_ref().and_then(|_| app.session.execute("color.used", &json!({ "limit": limit })).ok()); + let colors: Vec = r + .as_ref() + .and_then(|r| r["colors"].as_array()) + .map(|a| { + a.iter() + .filter_map(|c| { + let color = serde_json::from_value::(c["color"].clone()).ok()?; + let hex = c["hex"].as_str().map_or_else(|| color.to_hex(), str::to_string); + let link = c["swatch"].as_str().zip(c["tint"].as_f64()).map(|(n, t)| (n.to_string(), (t / 100.0).clamp(0.0, 1.0) as f32)); + Some(Used { color, hex, count: c["count"].as_u64().unwrap_or(0), link }) + }) + .collect() + }) + .unwrap_or_default(); + let selected = r.as_ref().is_some_and(|r| r["selection"] == true); + let uses = r.as_ref().and_then(|r| r["uses"].as_u64()).unwrap_or(0); + let cache = Arc::new(UsedCache { key, at: now, uses, selected, limit, colors }); + set_pstate(ui.ctx(), USED, Some(Arc::clone(&cache))); + cache +} + +/// The Show Document Colors row: a heading (Selection Colors or Document Colors) and the colors, +/// most used first, as many as fit in one row. Returns the color clicked. +fn document_colors_row(app: &mut VectorcraftApp, ui: &mut Ui) -> Option { + let width = ui.available_width(); + // Chips are 16 px on a 19 px pitch, inset 3 px, with 2 px kept clear of the right edge, as + // in the Recent Colors row. + let per_row = (((width - 21.0) / 19.0).floor().max(0.0) as usize + 1).max(1); + let cache = used_colors(app, ui, per_row); + widgets::subheader(ui, if cache.selected { tl!("Selection Colors") } else { tl!("Document Colors") }); + let t = Tokens::get(ui.ctx()); + let (r, _) = ui.allocate_exact_size(vec2(width, 22.0), Sense::hover()); + ui.painter().rect_stroke(r, 0.0, egui::Stroke::new(1.0, t.input_border), egui::StrokeKind::Inside); + let mut chosen = None; + for (i, u) in cache.colors.iter().take(per_row).enumerate() { + let cell = Rect::from_min_size(r.min + vec2(3.0 + i as f32 * 19.0, 3.0), vec2(16.0, 16.0)); + let resp = ui.interact(cell, ui.scope_id().with(("document-color", i)), Sense::click_and_drag()); + let paint = u.paint(); + widgets::drag_source(ui, &resp, || widgets::PanelDrag::paint(paint.clone())); + widgets::swatch_tile(ui, cell, &paint, false, resp.hovered()); + let tip = format!("{}\n{}", u.hex, crate::i18n::tn(u.count, "Used {n} time", "Used {n} times")); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, &tip)); + if resp.on_hover_text(&tip).clicked() { + chosen = Some(u.clone()); + } + } + chosen +} + +/// Apply a color of the Show Document Colors row as a pick does, to the inactive proxy when +/// `behind`. A color linked to a swatch stays linked at its tint, except at a freeform gradient's +/// point, which takes the color alone. +fn apply_used(app: &mut VectorcraftApp, tgt: &Target, u: &Used, behind: bool) { + let Some((name, tint)) = &u.link else { return apply(app, tgt, u.color, Live::Released, behind) }; + match tgt { + Target::Stop { paint: Paint::Gradient(g), index, .. } if !behind => { + let mut stops = g.gradient.stops.clone(); + if let Some(s) = stops.get_mut(*index) { + s.set_color(u.color, Some((name.clone(), *tint))); + } + super::gradient::set_stops(app, &stops, None, Live::Released); + } + Target::Point { .. } if !behind => apply(app, tgt, u.color, Live::Released, behind), + _ => { + let mut p = super::paint_params(&u.paint()); + p["focus"] = json!(!behind); + super::live_run(app, "Color", super::proxy_cmd(app, behind), p, Live::Released); + } + } +} + +/// The cells across and down of the grid the out-of-gamut shading tests. +pub(crate) const GAMUT_CELLS: usize = 16; + +/// The cells of a field whose colors are out of the CMYK gamut, a row per [`GAMUT_CELLS`] from the +/// top: bit `i` of a row is its cell `i` from the left. +pub(crate) type GamutGrid = [u16; GAMUT_CELLS]; + +/// The out-of-gamut cells of the box of channel `ch` at strip value `z` through `cms`, each tested +/// at its center by the out-of-gamut warning's test ([`Cms::out_of_gamut`]) on the working-RGB +/// color of a pick there, before any conversion to CMYK or Lab in [`stored`]. The wheel's square is +/// the box of [`Channel::Hue`] at the ring's hue. +pub(crate) fn gamut_grid(cms: &Cms, ch: Channel, z: f32) -> GamutGrid { + let n = GAMUT_CELLS as f32; + let mut grid = [0; GAMUT_CELLS]; + for (row, bits) in grid.iter_mut().enumerate() { + for col in 0..GAMUT_CELLS { + let (x, y) = ((col as f32 + 0.5) / n, (row as f32 + 0.5) / n); + // A gray has no hue, and the hue a gray keeps does not change its color. + let [r, g, b] = cms.srgb_to_rgb(hsb_to_rgb(box_pick(ch, z, x, y, [0.0; 3]))); + if cms.out_of_gamut(&Color::rgb(r, g, b)) { + *bits |= 1 << col; + } + } + } + grid +} + +/// What the out-of-gamut grid depends on: the channel, its value's bits, the color settings and +/// [`cms::profiles_generation`], which changes when a profile is loaded again under the same name. +pub(crate) type GamutKey = (Channel, u32, ColorSettings, u64); + +/// The grid for `key` from `slot`, computed with `compute` and kept in `slot` when `slot` holds +/// another key's. +pub(crate) fn cached_grid(slot: &mut Option<(GamutKey, GamutGrid)>, key: GamutKey, compute: impl FnOnce() -> GamutGrid) -> GamutGrid { + match slot { + Some((k, grid)) if *k == key => *grid, + _ => { + let grid = compute(); + *slot = Some((key, grid)); + grid + } + } +} + +/// Panel state: the out-of-gamut grid drawn last and its [`GamutKey`]. +pub(crate) const GAMUT: &str = "color-wheel-gamut"; + +/// The out-of-gamut grid of channel `ch` at value `z` through `cms`, kept in the panel state so a +/// frame with the same channel, value, color settings and loaded profiles does not test the colors +/// again. +fn gamut_shade(ui: &Ui, cms: &Cms, ch: Channel, z: f32) -> GamutGrid { + let mut slot = pstate::>(ui.ctx(), GAMUT); + let key = (ch, z.to_bits(), cms.settings().clone(), cms::profiles_generation()); + let grid = cached_grid(&mut slot, key, || gamut_grid(cms, ch, z)); + set_pstate(ui.ctx(), GAMUT, slot); + grid } /// The display values of HSB `hsb` in `ch`'s space, from 0 to 1: hue, saturation and brightness, @@ -272,16 +605,19 @@ fn strip_number(ch: Channel, hsb: [f32; 3]) -> (f64, &'static str, f64) { } /// The box in a `size` × `size` area: the field of channel `ch` and its strip, on HSB `hsb`, with -/// markers when `marked`. Returns the HSB a click, a drag, a key or a screen reader's action picks, -/// and its phase. -fn show_box(ui: &mut Ui, ch: Channel, hsb: [f32; 3], marked: bool, size: f32) -> Option<([f32; 3], Live)> { +/// markers when `marked` and the field's out-of-gamut cells grayed out when `gamut`. Returns the +/// HSB a click, a drag, a key or a screen reader's action picks, and its phase. +fn show_box(ui: &mut Ui, ch: Channel, hsb: [f32; 3], marked: bool, size: f32, gamut: Option<&Cms>) -> Option<([f32; 3], Live)> { let (z, x, y) = box_pos(ch, hsb); let mut pick = None; + let grid = gamut.map(|cms| gamut_shade(ui, cms, ch, z)); + let shade = grid.as_ref().map_or(&[][..], |g| &g[..]); ui.horizontal_top(|ui| { ui.spacing_mut().item_spacing.x = STRIP_GAP; let field = vec2((size - STRIP_GAP - STRIP).max(1.0), size); let at = |x: f32, y: f32| widgets::hsb32(box_pick(ch, z, x, y, hsb)); - if let (Some((x, y)), phase) = widgets::color_field(ui, "color-wheel-box", (tl!("Color box"), ch.field_axes()), field, (x, y), marked, &at) { + let labels = (tl!("Color box"), ch.field_axes()); + if let (Some((x, y)), phase) = widgets::color_field_shaded(ui, "color-wheel-box", labels, field, (x, y), marked, (&at, shade)) { pick = Some((box_pick(ch, z, x, y, hsb), phase)); } // The hue strip shows the whole spectrum; the others change only their own component. @@ -299,6 +635,16 @@ fn show_box(ui: &mut Ui, ch: Channel, hsb: [f32; 3], marked: bool, size: f32) -> /// Panel state: the HSB picked last, its [`Owner`] and the display sRGB of the color it stored. const MEMORY: &str = "color-wheel-hsb"; +/// Panel state: the OKLCH the slider rows asked for last, the [`Owner`] of the color they stored +/// and its display sRGB. +const OKLCH_MEMORY: &str = "color-wheel-oklch"; +/// Panel state: the slider rows whose drag previews on an open interaction, until it is released. +const ROWS_LIVE: &str = "color-wheel-rows-live"; +/// The message for OKLCH Sliders while the active document's RGB space is not sRGB. +const OKLCH_NEEDS_SRGB: &str = "OKLCH needs sRGB as the working RGB space"; +/// Panel state: the HSL the slider rows asked for last, the [`Owner`] of the color they stored and +/// its display sRGB. +const HSL_MEMORY: &str = "color-wheel-hsl"; /// The height of the color vision chips and the space between them. const VISION_CHIP: f32 = 16.0; const VISION_GAP: f32 = 3.0; @@ -399,6 +745,28 @@ impl Owner { } } +/// The components remembered under `key` for the target's `color`: the display sRGB the color had +/// when they were stored, and the components. A record whose owner or display color differs from +/// what the panel shows now is dropped, so that it does not come back when the same color returns +/// later. +fn recall( + app: &VectorcraftApp, + ui: &Ui, + key: &str, + tgt: &Target, + color: Option, + cms: &Cms, +) -> Option<([f32; 3], T)> { + let (owner, shown, v) = pstate::>(ui.ctx(), key)?; + match color { + Some(c) if owner == Owner::of(app, tgt, c) && cms.display_rgb(&c) == shown => Some((shown, v)), + _ => { + set_pstate(ui.ctx(), key, None::<(Owner, [f32; 3], T)>); + None + } + } +} + /// The HSB a color shows on the wheel: that of its display sRGB through `cms`. pub(crate) fn display_hsb(cms: &Cms, c: &Color) -> [f32; 3] { rgb_to_hsb(cms.display_rgb(c)) @@ -416,7 +784,12 @@ pub(crate) fn remembered_hsb(cms: &Cms, c: &Color, shown: [f32; 3], hsb: [f32; 3 /// model with the color settings. Anything else (no color, a Gray color, a tint of a global swatch) /// becomes a process color in the document's color mode: managed CMYK when `cmyk_doc`, else RGB. pub(crate) fn stored(cms: &Cms, hsb: [f32; 3], was: Option<&Color>, cmyk_doc: bool) -> Color { - let [r, g, b] = cms.srgb_to_rgb(hsb_to_rgb(hsb)); + stored_srgb(cms, hsb_to_rgb(hsb), was, cmyk_doc) +} + +/// [`stored`] for a pick of display sRGB `srgb`. +pub(crate) fn stored_srgb(cms: &Cms, srgb: [f32; 3], was: Option<&Color>, cmyk_doc: bool) -> Color { + let [r, g, b] = cms.srgb_to_rgb(srgb); let rgb = Color::rgb(r, g, b); let cmyk = || { let [c, m, y, k] = cms.to_cmyk(&rgb, cms.settings().intent); @@ -450,17 +823,219 @@ fn replaced(app: &VectorcraftApp, tgt: &Target, behind: bool) -> Option { } } +/// The OKLCH `[l, c, h°]` the rows show for `c` through `cms` when `lch` was asked for last and `c` +/// then displayed as the sRGB `shown`: `lch` while `c` still displays as `shown` (a chroma past the +/// gamut and the hue of a gray stay), else `c`'s own. +pub(crate) fn remembered_oklch(cms: &Cms, c: &Color, shown: [f32; 3], lch: [f64; 3]) -> [f64; 3] { + if cms.display_rgb(c) == shown { lch } else { oklab::to_oklch(clipped_rgb(cms, c)) } +} + +/// The display sRGB of `c` through `cms` clipped to sRGB: the color the slider rows show and edit +/// for a color outside sRGB. +fn clipped_rgb(cms: &Cms, c: &Color) -> [f32; 3] { + cms.display_rgb(c).map(|v| v.clamp(0.0, 1.0)) +} + +/// The color a track shows at OKLCH `lch`: the color itself inside sRGB, and outside it dimmed. +/// A color outside sRGB shows at the largest chroma that fits at its L and H, the color a pick +/// there stores. With `max_chroma` (the C track, whose L and H stay fixed) that chroma is given +/// for the colors past it; without it, or in a gap below it where the ray leaves sRGB and comes +/// back, it is found for each color. +pub(crate) fn oklch_track(lch: [f64; 3], max_chroma: Option) -> Color32 { + let exact = oklab::oklch_to_srgb(lch[0], lch[1], lch[2]); + let (rgb, outside) = match max_chroma { + Some(m) if lch[1] > m => (oklab::oklch_to_srgb(lch[0], m, lch[2]), true), + Some(_) if oklab::in_srgb(exact) => (exact, false), + _ => { + let (rgb, lowered) = oklab::from_oklch(lch[0], lch[1], lch[2]); + (rgb.map(f64::from), lowered) + } + }; + let [r, g, b] = rgb.map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8); + let c = Color32::from_rgb(r, g, b); + if outside { c.gamma_multiply(0.3) } else { c } +} + +/// Where the C track's tick sits, from 0 at its left to 1 at its right: at the largest chroma +/// `max_chroma`, of the track's 0 to 0.4. +pub(crate) fn chroma_tick(max_chroma: f64) -> f32 { + (max_chroma / CHROMA_FULL).clamp(0.0, 1.0) as f32 +} + +/// The L, C and H rows of OKLCH Sliders for the target's `color` through `cms`: lightness from 0 to +/// 100 %, chroma from 0 to 100 % of 0.4 (as CSS reads a chroma percentage) and hue from 0 to 360°. +/// Each track shows the colors its slider reaches and dims the part outside sRGB, and a tick on the +/// C track marks the largest chroma sRGB holds at the row's L and H. The rows are gray with no +/// color to edit and while the working RGB space is not sRGB. Returns the OKLCH a drag, an arrow +/// key, a screen reader or a field asks for, and its phase. +pub(crate) fn oklch_rows(app: &VectorcraftApp, ui: &mut Ui, tgt: &Target, color: Option, cms: &Cms) -> Option<([f64; 3], Live)> { + let t = Tokens::get(ui.ctx()); + let enabled = color.is_some() && cms.rgb_is_srgb(); + let lch = match (color, recall::<[f64; 3]>(app, ui, OKLCH_MEMORY, tgt, color, cms)) { + (Some(c), Some((shown, lch))) => remembered_oklch(cms, &c, shown, lch), + (Some(c), _) => oklab::to_oklch(clipped_rgb(cms, &c)), + (None, _) => [0.0; 3], + }; + // Each row: its letter, its screen-reader name, the end of its range and the field's suffix. + let rows = [("L", tl!("Lightness"), 100.0, "%"), ("C", tl!("Chroma"), 100.0, "%"), ("H", tl!("Hue"), 360.0, "°")]; + let shown = [lch[0] * 100.0, lch[1] / CHROMA_FULL * 100.0, lch[2]]; + // The OKLCH with row `i` set to `v` in the row's units. + let with = |i: usize, v: f64| { + let mut out = lch; + match i { + 0 => out[0] = (v / 100.0).clamp(0.0, 1.0), + 1 => out[1] = (v / 100.0 * CHROMA_FULL).clamp(0.0, CHROMA_FULL), + _ => out[2] = v.clamp(0.0, 360.0), + } + out + }; + let mut out = None; + // The L and H tracks search the gamut for each color outside sRGB, so their colors are kept + // until the other two components change. + let mut tracks = pstate::<[Option<([u64; 3], Vec)>; 3]>(ui.ctx(), OKLCH_TRACKS); + ui.add_enabled_ui(enabled, |ui| { + let field_w = 48.0; + let slider_w = (ui.available_width() - field_w - 12.0 - 3.0 * ui.spacing().item_spacing.x).max(60.0); + // The C track's L and H stay fixed, so its largest chroma is found once per frame. + let max_c = if enabled { oklab::max_chroma(lch[0], lch[2]) } else { 0.0 }; + for (i, (letter, name, max, suffix)) in rows.into_iter().enumerate() { + ui.horizontal(|ui| { + ui.add_sized(vec2(12.0, 22.0), egui::Label::new(egui::RichText::new(letter).size(12.5).color(t.text))); + let v = shown[i].clamp(0.0, max); + let at = |x: f32| with(i, f64::from(x) * max); + let mut key = lch.map(f64::to_bits); + key[i] = 0; + let colors = match &tracks[i] { + Some((k, colors)) if i != 1 && enabled && *k == key => colors.clone(), + _ if i != 1 && enabled => { + let last = (TRACK_SAMPLES - 1) as f32; + let colors: Vec = (0..TRACK_SAMPLES).map(|s| oklch_track(at(s as f32 / last), None)).collect(); + tracks[i] = Some((key, colors.clone())); + colors + } + _ => Vec::new(), + }; + let track = |x: f32| match colors.get((x.clamp(0.0, 1.0) * (TRACK_SAMPLES - 1) as f32).round() as usize) { + Some(c) => *c, + None if enabled => oklch_track(at(x), (i == 1).then_some(max_c)), + None => t.input, + }; + let value = SliderValue::field(v, 0.0..=max, suffix, 0); + let (dragged, phase, keyed) = + widgets::color_slider_stepped(ui, ("color-wheel-oklch", i), name, Some(value), (v / max) as f32, slider_w, &track); + // The tick goes on the bar of the rail as the row laid it out. + let rail = (i == 1 && enabled).then(|| ui.ctx().read_response(widgets::id_with(ui.scope_id(), ("color-wheel-oklch", i)))).flatten(); + if let Some(rail) = rail { + let bar = widgets::color_rail_bar(rail.rect); + let x = bar.left() + chroma_tick(max_c) * bar.width(); + ui.painter().line_segment([pos2(x, bar.top() - 3.0), pos2(x, bar.bottom())], Stroke::new(1.5, t.text)); + let tip = Rect::from_x_y_ranges(x - 3.0..=x + 3.0, bar.top() - 3.0..=bar.bottom()); + ui.interact(tip, ui.scope_id().with("color-wheel-oklch-tick"), egui::Sense::hover()) + .on_hover_text(tl!("The largest chroma sRGB holds at this lightness and hue")); + } + if let Some(x) = dragged { + out = Some((at(x), phase)); + } + if let Some(k) = keyed { + out = Some((with(i, k), Live::Released)); + } + if let Some(f) = widgets::plain_field_named(ui, ("color-wheel-oklch-field", i), Some(name), v, suffix, 0, field_w) { + out = Some((with(i, f), Live::Released)); + } + }); + } + }); + set_pstate(ui.ctx(), OKLCH_TRACKS, tracks); + out.filter(|_| enabled) +} + +/// Panel state: the colors of the L and H tracks of OKLCH Sliders, each with the OKLCH (its own +/// component left out) they were drawn for. +const OKLCH_TRACKS: &str = "color-wheel-oklch-tracks"; +/// How many colors along a cached track. +const TRACK_SAMPLES: usize = 128; + +/// The HSL `[h°, s, l]` the rows show for `c` through `cms` when `hsl` was asked for last and `c` +/// then displayed as the sRGB `shown`: `hsl` while `c` still displays as `shown` (the hue of a gray +/// and the saturation of black and white stay), else `c`'s own. +pub(crate) fn remembered_hsl(cms: &Cms, c: &Color, shown: [f32; 3], hsl: [f32; 3]) -> [f32; 3] { + if cms.display_rgb(c) == shown { hsl } else { rgb_to_hsl(clipped_rgb(cms, c)) } +} + +/// The color a track shows at HSL `hsl`. +fn hsl32(hsl: [f32; 3]) -> Color32 { + let [r, g, b] = hsl_to_rgb(hsl).map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8); + Color32::from_rgb(r, g, b) +} + +/// The H, S and L rows of HSL Sliders for the target's `color` through `cms`: hue from 0 to 360°, +/// saturation and lightness from 0 to 100 %, CSS Color 4's HSL of the display sRGB. Each track +/// shows the colors its slider reaches. The rows are gray with no color to edit. Returns the HSL a +/// drag, an arrow key, a screen reader or a field asks for, and its phase. +pub(crate) fn hsl_rows(app: &VectorcraftApp, ui: &mut Ui, tgt: &Target, color: Option, cms: &Cms) -> Option<([f32; 3], Live)> { + let t = Tokens::get(ui.ctx()); + let enabled = color.is_some(); + let hsl = match (color, recall::<[f32; 3]>(app, ui, HSL_MEMORY, tgt, color, cms)) { + (Some(c), Some((shown, hsl))) => remembered_hsl(cms, &c, shown, hsl), + (Some(c), _) => rgb_to_hsl(clipped_rgb(cms, &c)), + (None, _) => [0.0; 3], + }; + // Each row: its letter, its screen-reader name, the end of its range and the field's suffix. The + // names start with "HSL" so that they differ from the box strip's HSB Hue and Saturation. + let hsl_name = |name: &str| format!("HSL {name}"); + let rows = + [("H", hsl_name(tl!("Hue")), 360.0, "°"), ("S", hsl_name(tl!("Saturation")), 100.0, "%"), ("L", hsl_name(tl!("Lightness")), 100.0, "%")]; + let shown = [f64::from(hsl[0]), f64::from(hsl[1]) * 100.0, f64::from(hsl[2]) * 100.0]; + // The HSL with row `i` set to `v` in the row's units. + let with = |i: usize, v: f64| { + let mut out = hsl; + match i { + 0 => out[0] = v.clamp(0.0, 360.0) as f32, + 1 => out[1] = (v / 100.0).clamp(0.0, 1.0) as f32, + _ => out[2] = (v / 100.0).clamp(0.0, 1.0) as f32, + } + out + }; + let mut out = None; + ui.add_enabled_ui(enabled, |ui| { + let field_w = 48.0; + let slider_w = (ui.available_width() - field_w - 12.0 - 3.0 * ui.spacing().item_spacing.x).max(60.0); + for (i, (letter, name, max, suffix)) in rows.into_iter().enumerate() { + ui.horizontal(|ui| { + ui.add_sized(vec2(12.0, 22.0), egui::Label::new(egui::RichText::new(letter).size(12.5).color(t.text))); + let v = shown[i].clamp(0.0, max); + let at = |x: f32| with(i, f64::from(x) * max); + let track = |x: f32| if enabled { hsl32(at(x)) } else { t.input }; + let value = SliderValue::field(v, 0.0..=max, suffix, 0); + let (dragged, phase, keyed) = + widgets::color_slider_stepped(ui, ("color-wheel-hsl", i), &name, Some(value), (v / max) as f32, slider_w, &track); + if let Some(x) = dragged { + out = Some((at(x), phase)); + } + if let Some(k) = keyed { + out = Some((with(i, k), Live::Released)); + } + if let Some(f) = widgets::plain_field_named(ui, ("color-wheel-hsl-field", i), Some(&name), v, suffix, 0, field_w) { + out = Some((with(i, f), Live::Released)); + } + }); + } + }); + out.filter(|_| enabled) +} + pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let tgt = wheel_target(app, ui); let color = tgt.color(); let cms = cms::active(); // With None, a pattern or a "?" proxy the wheel shows the last solid color without markers, // and a click, an arrow key or a screen reader's action applies the picked color. - let hsb = match (color, pstate::>(ui.ctx(), MEMORY)) { - (Some(c), Some((owner, shown, hsb))) if owner == Owner::of(app, &tgt, c) => remembered_hsb(&cms, &c, shown, hsb), + let hsb = match (color, recall::<[f32; 3]>(app, ui, MEMORY, &tgt, color, &cms)) { + (Some(c), Some((shown, hsb))) => remembered_hsb(&cms, &c, shown, hsb), (c, _) => display_hsb(&cms, &c.unwrap_or(app.session.last_solid)), }; let marked = color.is_some(); + let gamut = app.ui.color_wheel.gamut.then_some(&*cms); let mut pick: Option<([f32; 3], Live)> = None; ui.horizontal_top(|ui| { ui.vertical(|ui| { @@ -469,7 +1044,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { }); let size = ui.available_width().min(MAX_WHEEL); if app.ui.color_wheel.view == View::Box { - pick = show_box(ui, app.ui.color_wheel.channel, hsb, marked, size); + pick = show_box(ui, app.ui.color_wheel.channel, hsb, marked, size, gamut); return; } let ring = widgets::hue_ring(ui, "color-wheel-ring", tl!("Hue ring"), size, hsb[0], marked); @@ -479,7 +1054,11 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { [FieldAxis { name: tl!("Saturation"), units: 100.0, suffix: "%" }, FieldAxis { name: tl!("Brightness"), units: 100.0, suffix: "%" }]; let at = |x: f32, y: f32| widgets::hsb32([hsb[0], x, 1.0 - y]); let name = tl!("Saturation and brightness"); - let (field, field_phase) = widgets::color_field(&mut field_ui, "field", (name, axes), square.size(), (hsb[1], 1.0 - hsb[2]), marked, &at); + // The square is the hue box at the ring's hue, so it shares the box's grid. + let grid = gamut.map(|cms| gamut_shade(ui, cms, Channel::Hue, box_pos(Channel::Hue, hsb).0)); + let shade = grid.as_ref().map_or(&[][..], |g| &g[..]); + let pos = (hsb[1], 1.0 - hsb[2]); + let (field, field_phase) = widgets::color_field_shaded(&mut field_ui, "field", (name, axes), square.size(), pos, marked, (&at, shade)); // Show Harmony: the rule's other colors for the current one, which follow it. While a press // is held on a marker, the ring's drag under it picks nothing. let set = &app.ui.color_wheel; @@ -512,16 +1091,86 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { pick = Some(([hsb[0], x, 1.0 - y], field_phase)); } }); + let (mut picked_lch, mut picked_hsl) = (None, None); + match app.ui.color_wheel.sliders { + Sliders::None => {} + Sliders::Oklch => { + ui.add_space(4.0); + picked_lch = oklch_rows(app, ui, &tgt, color, &cms); + } + Sliders::Hsl => { + ui.add_space(4.0); + picked_hsl = hsl_rows(app, ui, &tgt, color, &cms); + } + } + // A row drag whose rows were hidden or replaced (`ui.colorWheel {sliders}`), or turned gray + // (OKLCH rows after the working RGB space stops being sRGB), reports no release: its preview is + // kept as one undo step and the interaction ends. + let live = pstate::>(ui.ctx(), ROWS_LIVE); + if live.is_some_and(|rows| rows != app.ui.color_wheel.sliders || (rows == Sliders::Oklch && !cms.rgb_is_srgb())) { + if app.session.in_interaction() + && let Err(e) = app.session.commit_interaction() + { + app.status(e.to_string()); + } + app.sync_views(); + set_pstate(ui.ctx(), ROWS_LIVE, None::); + } if app.ui.color_wheel.vision { ui.add_space(4.0); vision_row(ui, &cms, color.as_ref()); } - let Some((hsb, phase)) = pick else { return }; let behind = super::alt_held(ui); + if app.ui.color_wheel.document_colors + && let Some(u) = document_colors_row(app, ui) + { + apply_used(app, &tgt, &u, behind); + return; + } let cmyk_doc = app.session.active().is_some_and(|d| d.doc.color_mode == ColorMode::Cmyk); + let rows = match (picked_hsl, picked_lch) { + (Some((hsl, phase)), _) => Some((hsl_to_rgb(hsl), phase, HSL_MEMORY, Remembered::Hsl(hsl))), + (_, Some((lch, phase))) => Some((oklab::from_oklch(lch[0], lch[1], lch[2]).0, phase, OKLCH_MEMORY, Remembered::Oklch(lch))), + _ => None, + }; + if let Some((srgb, phase, key, asked)) = rows { + // A hue on a gray, or a saturation on black or white, leaves the displayed color as it is: + // the rows keep what they were given, and the paint (a Gray color too) stays unchanged. + let current = color.filter(|c| { + let d = cms.display_rgb(c); + !behind && live.is_none() && (0..3).all(|i| (d[i] - srgb[i]).abs() <= 1e-5) + }); + if let Some(c) = current { + asked.remember(ui, key, Owner::of(app, &tgt, c), cms.display_rgb(&c)); + return; + } + let c = stored_srgb(&cms, srgb, replaced(app, &tgt, behind).as_ref(), cmyk_doc); + apply(app, &tgt, c, phase, behind); + set_pstate(ui.ctx(), ROWS_LIVE, (phase == Live::Dragging).then_some(app.ui.color_wheel.sliders)); + if !behind { + asked.remember(ui, key, Owner::of(app, &tgt, c), cms.display_rgb(&c)); + } + return; + } + let Some((hsb, phase)) = pick else { return }; let c = stored(&cms, hsb, replaced(app, &tgt, behind).as_ref(), cmyk_doc); apply(app, &tgt, c, phase, behind); if !behind { set_pstate(ui.ctx(), MEMORY, Some((Owner::of(app, &tgt, c), cms.display_rgb(&c), hsb))); } } + +/// What a slider row asked for, kept under its memory key. +enum Remembered { + Hsl([f32; 3]), + Oklch([f64; 3]), +} + +impl Remembered { + fn remember(self, ui: &Ui, key: &str, owner: Owner, shown: [f32; 3]) { + match self { + Remembered::Hsl(v) => set_pstate(ui.ctx(), key, Some((owner, shown, v))), + Remembered::Oklch(v) => set_pstate(ui.ctx(), key, Some((owner, shown, v))), + } + } +} diff --git a/crates/ui-egui/src/panels/gradient.rs b/crates/ui-egui/src/panels/gradient.rs index e04c2780c1..945c18ea0d 100644 --- a/crates/ui-egui/src/panels/gradient.rs +++ b/crates/ui-egui/src/panels/gradient.rs @@ -708,9 +708,11 @@ fn ramp_row(app: &mut VectorcraftApp, ui: &mut Ui, g: &Gradient, is_grad: bool) } /// The stop's eyedropper: the Eyedropper tool samples the next colour clicked on the art into the -/// selected stop, then hands back to the current tool. +/// selected stop, then hands back to the current tool (or, while a pick is already armed, to the +/// tool that armed it). pub(crate) fn stop_eyedropper(app: &mut VectorcraftApp) { - let back = app.session.tool_id(); + let tool = app.session.tool_id(); + let back = (tool == "eyedropper").then(|| app.session.tool_returns_to()).flatten().unwrap_or_else(|| tool.to_string()); app.select_tool("eyedropper"); app.session.set_tool_option("stop", &json!(back)); } diff --git a/crates/ui-egui/src/panels/gradient/tests.rs b/crates/ui-egui/src/panels/gradient/tests.rs index f91d4fbcf5..1a607b8f24 100644 --- a/crates/ui-egui/src/panels/gradient/tests.rs +++ b/crates/ui-egui/src/panels/gradient/tests.rs @@ -740,6 +740,9 @@ fn the_stop_eyedropper_arms_the_eyedropper_for_the_stop() { assert!(texts.iter().any(|(t, _)| t == "#FFFFFF"), "the stop's colour row: {texts:?}"); stop_eyedropper(&mut app); assert_eq!((app.session.tool_id(), app.session.tool_options()), ("eyedropper", json!({"stop": "gradient", "brushKeyColor": false}))); + // A second click on the eyedropper while the pick is armed still hands back to the Gradient tool. + stop_eyedropper(&mut app); + assert_eq!(app.session.tool_options()["stop"], "gradient"); } /// #8024: Escape ends the stop eyedropper's pick and returns to the Gradient tool. The stop keeps diff --git a/crates/ui-egui/src/panels/graphic_styles.rs b/crates/ui-egui/src/panels/graphic_styles.rs index 18b9ecc6f5..4650c88628 100644 --- a/crates/ui-egui/src/panels/graphic_styles.rs +++ b/crates/ui-egui/src/panels/graphic_styles.rs @@ -2,8 +2,10 @@ //! (Small and Large List View), shown on a square or on type; a style with no fill and no stroke //! shows the shape outlined in black and filled with white, under a red slash. Clicking a style applies it to the //! selection (Alt-click adds it on top); Shift-click adds to the panel's selection every style from -//! the last one clicked without Shift through this one; Cmd/Ctrl-click adds or removes one; -//! double-click opens Graphic Style Options. Dragging a style moves it in the list (dropped on +//! the last one clicked without Shift through this one; Cmd/Ctrl-click adds or removes one. The +//! style last clicked into the selection is the one the Symbol Styler and the Symbol Sprayer's User +//! Defined Style apply. Double-click opens +//! Graphic Style Options. Dragging a style moves it in the list (dropped on //! another style with Alt held, replaces that style with its look), applies it //! to the art it is dropped on (`canvas::panel_drop`), or, dropped on New Graphic Style, adds a //! copy of it and of the styles highlighted with it at the end of the list; art dragged off the @@ -24,7 +26,10 @@ use serde_json::{Value, json}; use vectorcraft_color::{BlendMode, Color, Paint}; use vectorcraft_doc::style_libs::STYLE_LIBRARIES; use vectorcraft_doc::text::{CharStyle, TextObject}; -use vectorcraft_doc::{Appearance, AppearanceItem, Document, FillLayer, GraphicStyle, Node, NodeId, NodeKind, PatternDef, StrokeLayer, StyleLibrary}; +use vectorcraft_doc::{ + Appearance, AppearanceItem, DEFAULT_GRAPHIC_STYLE, Document, FillLayer, GraphicStyle, Node, NodeId, NodeKind, PatternDef, StrokeLayer, + StyleLibrary, +}; use vectorcraft_engine::cmd::stylelib; use vectorcraft_engine::cmd::swatchlib::LibraryInfo; use vectorcraft_geom::{Affine, Point, shapes}; @@ -484,21 +489,84 @@ fn zone_input(ui: &Ui, zone: &Response, d: &Document, ev: &mut Events) { } } +/// An item's right-click context menu in the Graphic Styles panel. +fn item_context_menu(app: &mut VectorcraftApp, ui: &mut Ui, name: &str, sel: &[String]) { + let is_default = name == DEFAULT_GRAPHIC_STYLE; + let is_multi = sel.len() > 1 && sel.contains(&name.to_string()); + let targets: Vec = if is_multi { + let doc = app.session.active().map(|st| st.doc.clone()); + if let Some(d) = &doc { d.graphic_styles.iter().filter(|g| sel.contains(&g.name)).map(|g| g.name.clone()).collect() } else { sel.to_vec() } + } else { + vec![name.to_string()] + }; + let doomed: Vec = targets.iter().filter(|s| *s != DEFAULT_GRAPHIC_STYLE).cloned().collect(); + + let can_options = !is_default && !is_multi; + if menu_item(ui, tl!("Graphic Style Options…"), can_options, false) { + if let Err(e) = app.run("ui.graphicStyleOptions", json!({ "name": name })) { + app.status(e); + } + ui.close(); + } + let duplicate_label = if is_multi { tl!("Duplicate Graphic Styles") } else { tl!("Duplicate Graphic Style") }; + if menu_item(ui, duplicate_label, true, false) { + duplicate(app, ui.ctx(), &targets); + ui.close(); + } + let delete_label = if is_multi { tl!("Delete Graphic Styles") } else { tl!("Delete Graphic Style") }; + let can_delete = !is_default && !doomed.is_empty(); + if menu_item(ui, delete_label, can_delete, false) { + let res = if doomed.len() == 1 { + app.run("graphicStyle.delete", json!({ "name": doomed[0] })) + } else { + app.run("graphicStyle.delete", json!({ "names": doomed })) + }; + if res.is_ok() { + set_pstate(ui.ctx(), "gs-sel", Vec::::new()); + } + ui.close(); + } + ui.separator(); + let has_art_sel = selection_len(app) > 0; + if menu_item(ui, tl!("Redefine Graphic Style"), has_art_sel, false) { + if let Err(e) = app.run("graphicStyle.redefine", json!({ "name": name })) { + app.status(e); + } + ui.close(); + } + let is_linked = app.session.selection_graphic_style().is_some_and(|(g, linked)| linked && g.name == name); + if menu_item(ui, tl!("Break Link to Graphic Style"), is_linked, false) { + if let Err(e) = app.run("graphicStyle.breakLink", json!({})) { + app.status(e); + } + ui.close(); + } +} + /// The thumbnail grid (Thumbnail View and the Control bar's picker), `sel` outlined. -fn tiles(app: &VectorcraftApp, ui: &mut Ui, s: &Shown, sel: &[String], ev: &mut Events) { +fn tiles(app: &mut VectorcraftApp, ui: &mut Ui, s: &Shown, sel: &mut Vec, ev: &mut Events, in_panel: bool) { ui.horizontal_wrapped(|ui| { ui.spacing_mut().item_spacing = vec2(3.0, 3.0); for (i, g) in s.d.graphic_styles.iter().enumerate() { let (r, resp) = ui.allocate_exact_size(vec2(TILE, TILE), Sense::click_and_drag()); s.paint(app, ui, r, i); outline(ui, r, sel.contains(&g.name), resp.hovered()); - cell_input(ui, &resp.on_hover_text(&g.name), s.d, i, false, ev); + let resp = resp.on_hover_text(&g.name); + cell_input(ui, &resp, s.d, i, false, ev); + if in_panel { + if resp.secondary_clicked() && !sel.contains(&g.name) { + *sel = vec![g.name.clone()]; + set_pstate(ui.ctx(), "gs-anchor", g.name.clone()); + set_pstate(ui.ctx(), "gs-sel", sel.clone()); + } + resp.context_menu(|ui| item_context_menu(app, ui, &g.name, sel)); + } } }); } /// The list views' rows (`row`: height and thumbnail side), `sel` highlighted. -fn rows(app: &VectorcraftApp, ui: &mut Ui, s: &Shown, sel: &[String], row: (f32, f32), ev: &mut Events) { +fn rows(app: &mut VectorcraftApp, ui: &mut Ui, s: &Shown, sel: &mut Vec, row: (f32, f32), ev: &mut Events) { let t = Tokens::get(ui.ctx()); let (h, side) = row; for (i, g) in s.d.graphic_styles.iter().enumerate() { @@ -512,7 +580,14 @@ fn rows(app: &VectorcraftApp, ui: &mut Ui, s: &Shown, sel: &[String], row: (f32, s.paint(app, ui, th, i); ui.painter().rect_stroke(th, 0.0, Stroke::new(1.0, t.border), StrokeKind::Outside); ui.painter().text(pos2(th.right() + 8.0, r.center().y), egui::Align2::LEFT_CENTER, &g.name, egui::FontId::proportional(12.0), t.text); + let resp = resp.on_hover_text(&g.name); cell_input(ui, &resp, s.d, i, true, ev); + if resp.secondary_clicked() && !sel.contains(&g.name) { + *sel = vec![g.name.clone()]; + set_pstate(ui.ctx(), "gs-anchor", g.name.clone()); + set_pstate(ui.ctx(), "gs-sel", sel.clone()); + } + resp.context_menu(|ui| item_context_menu(app, ui, &g.name, sel)); } } @@ -552,6 +627,11 @@ fn act(app: &mut VectorcraftApp, ui: &Ui, s: &Shown, ev: Events, picker: bool) { Some(Click::Pick(name, m)) => { let order: Vec<&str> = s.d.graphic_styles.iter().map(|g| g.name.as_str()).collect(); let sel = super::swatches::click_selection(ui, "gs-anchor", selected(ui.ctx(), s.d), &order, &name, m); + // The style clicked into the selection is the one the Symbol Styler and the Symbol + // Sprayer's User Defined Style apply (the two share it). + if sel.contains(&name) { + app.run("tool.setOption", json!({"tool": "symbolStyler", "values": {"style": name}})).ok(); + } set_pstate(ui.ctx(), "gs-sel", sel); // A plain click also applies the style (with nothing selected the next object drawn // takes it); Shift and Cmd/Ctrl clicks only select. @@ -581,7 +661,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { }; let looks = look_hashes(ui.ctx(), app); let shown = Shown { d: &doc, looks: &looks, preview: pstate(ui.ctx(), "gs-preview") }; - let sel = selected(ui.ctx(), &doc); + let mut sel = selected(ui.ctx(), &doc); let view = app.ui.graphic_styles_view; let mut ev = Events::default(); // In a sized panel the list fills the space above the footer (#2992), as the Artboards list @@ -602,8 +682,8 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { return; } match view.row() { - Some(row) => rows(app, ui, &shown, &sel, row, &mut ev), - None => tiles(app, ui, &shown, &sel, &mut ev), + Some(row) => rows(app, ui, &shown, &mut sel, row, &mut ev), + None => tiles(app, ui, &shown, &mut sel, &mut ev, true), } }); // The drop zone is the part of the list on screen: when the list shrinks to its rows, @@ -667,8 +747,9 @@ pub(crate) fn picker(app: &mut VectorcraftApp, ui: &mut Ui) { let looks = look_hashes(ui.ctx(), app); let shown = Shown { d: &doc, looks: &looks, preview: pstate(ui.ctx(), "gs-preview") }; let mut ev = Events::default(); + let mut sel = Vec::new(); ui.set_max_width(6.0 * (TILE + 3.0)); - tiles(app, ui, &shown, &[], &mut ev); + tiles(app, ui, &shown, &mut sel, &mut ev, false); act(app, ui, &shown, ev, true); } @@ -1689,15 +1770,23 @@ mod tests { selected(&ctx, &app.session.active().unwrap().doc.clone()) }; let linked = |app: &VectorcraftApp| app.session.selection_graphic_style().map(|(g, _)| g.name.clone()); - // A plain click applies the style and selects it alone. + let styler = |app: &VectorcraftApp| app.session.tool_options_of("symbolStyler")["style"].as_str().map(str::to_string); + // A plain click applies the style and selects it alone; the Symbol Styler takes it. assert_eq!(click(&mut app, 0, egui::Modifiers::NONE), [n[0].clone()]); assert_eq!(linked(&app).as_ref(), Some(&n[0])); + assert_eq!(styler(&app).as_ref(), Some(&n[0])); // Shift-click selects from that style to the clicked one, and applies nothing. assert_eq!(click(&mut app, 3, egui::Modifiers::SHIFT), n[..4]); assert_eq!(linked(&app).as_ref(), Some(&n[0])); - // Cmd/Ctrl-click removes a selected style and adds it back. + assert_eq!(styler(&app).as_ref(), Some(&n[3])); + // Cmd/Ctrl-click removes a selected style and adds it back; the Styler keeps its style + // while one is removed. assert_eq!(click(&mut app, 2, egui::Modifiers::COMMAND), [n[0].clone(), n[1].clone(), n[3].clone()]); + assert_eq!(styler(&app).as_ref(), Some(&n[3])); assert_eq!(click(&mut app, 2, egui::Modifiers::COMMAND), [n[0].clone(), n[1].clone(), n[3].clone(), n[2].clone()]); + assert_eq!(styler(&app).as_ref(), Some(&n[2])); + // The Symbol Sprayer's User Defined Style applies the same style. + assert_eq!(app.session.tool_options_of("symbolSprayer")["style"].as_str(), Some(n[2].as_str())); // Shift-click extends from the style Cmd/Ctrl-clicked last. click(&mut app, 0, egui::Modifiers::NONE); click(&mut app, 2, egui::Modifiers::COMMAND); @@ -1740,4 +1829,184 @@ mod tests { frame_with(&ctx, click(false), |ui| picker(&mut app, ui)); assert_eq!(app.session.selection_graphic_style().map(|(g, linked)| (g.name.clone(), linked)), Some((name, true))); } + + #[test] + fn right_click_context_menu_in_graphic_styles_panel() { + use egui_kittest::kittest::{NodeT, Queryable}; + + let mut app = app(); + app.run("graphicStyle.new", json!({"name": "Style A"})).unwrap(); + app.run("graphicStyle.new", json!({"name": "Style B"})).unwrap(); + + let mut h = egui_kittest::Harness::builder().with_size(vec2(260.0, 400.0)).with_accessibility_check(false).build_ui_state( + |ui, app: &mut VectorcraftApp| { + show(app, ui); + }, + app, + ); + h.run_steps(2); + + // Initially "Style B" was added last; "Style A" is unselected. + let pos_a = h.get_by_label("Style A").rect().center(); + + // 1. Right-click unselected "Style A" + h.event(egui::Event::PointerMoved(pos_a)); + h.event(egui::Event::PointerButton { pos: pos_a, button: egui::PointerButton::Secondary, pressed: true, modifiers: Default::default() }); + h.event(egui::Event::PointerButton { pos: pos_a, button: egui::PointerButton::Secondary, pressed: false, modifiers: Default::default() }); + h.run_steps(2); + + // Right-clicking unselected "Style A" selects it. + let doc = h.state().session.active().unwrap().doc.clone(); + assert_eq!(selected(&h.ctx, &doc), vec!["Style A"]); + + // Context menu items are displayed + let options = h.get_by_label(" Graphic Style Options…"); + let duplicate = h.get_by_label(" Duplicate Graphic Style"); + let delete = h.get_by_label(" Delete Graphic Style"); + let redefine = h.get_by_label(" Redefine Graphic Style"); + let break_link = h.get_by_label(" Break Link to Graphic Style"); + + assert!(!options.accesskit_node().is_disabled()); + assert!(!duplicate.accesskit_node().is_disabled()); + assert!(!delete.accesskit_node().is_disabled()); + assert!(!redefine.accesskit_node().is_disabled()); // Art is selected + assert!(break_link.accesskit_node().is_disabled()); // Art not linked to Style A + + // 2. Click "Duplicate Graphic Style" + duplicate.click(); + h.run_steps(3); + + let doc = h.state().session.active().unwrap().doc.clone(); + assert!(doc.graphic_style("Style A copy").is_some()); + assert_eq!(selected(&h.ctx, &doc), vec!["Style A copy"]); + + // 3. Apply Style A to the active art and verify Break Link + h.state_mut().run("graphicStyle.apply", json!({"name": "Style A"})).unwrap(); + // Modify appearance so style is out of sync (not linked) + h.state_mut().run("paint.setFill", json!({"color": "#ff0000"})).unwrap(); + h.run_steps(2); + + let pos_a = h.get_by_label("Style A").rect().center(); + h.event(egui::Event::PointerMoved(pos_a)); + h.event(egui::Event::PointerButton { pos: pos_a, button: egui::PointerButton::Secondary, pressed: true, modifiers: Default::default() }); + h.event(egui::Event::PointerButton { pos: pos_a, button: egui::PointerButton::Secondary, pressed: false, modifiers: Default::default() }); + h.run_steps(2); + + let break_link = h.get_by_label(" Break Link to Graphic Style"); + assert!(break_link.accesskit_node().is_disabled(), "Break link is disabled when style is out of sync"); + + // Close menu + h.event(egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }); + h.run_steps(2); + + // Reapply Style A so it is in sync + h.state_mut().run("graphicStyle.apply", json!({"name": "Style A"})).unwrap(); + h.run_steps(2); + + let pos_a = h.get_by_label("Style A").rect().center(); + h.event(egui::Event::PointerMoved(pos_a)); + h.event(egui::Event::PointerButton { pos: pos_a, button: egui::PointerButton::Secondary, pressed: true, modifiers: Default::default() }); + h.event(egui::Event::PointerButton { pos: pos_a, button: egui::PointerButton::Secondary, pressed: false, modifiers: Default::default() }); + h.run_steps(2); + + let break_link = h.get_by_label(" Break Link to Graphic Style"); + assert!(!break_link.accesskit_node().is_disabled(), "Break link is enabled when style is in sync"); + break_link.click(); + h.run_steps(3); + + assert!(h.state().session.selection_graphic_style().is_none()); + + // 4. Right-click Style A and click "Delete Graphic Style" + let pos_a = h.get_by_label("Style A").rect().center(); + h.event(egui::Event::PointerMoved(pos_a)); + h.event(egui::Event::PointerButton { pos: pos_a, button: egui::PointerButton::Secondary, pressed: true, modifiers: Default::default() }); + h.event(egui::Event::PointerButton { pos: pos_a, button: egui::PointerButton::Secondary, pressed: false, modifiers: Default::default() }); + h.run_steps(2); + + let delete = h.get_by_label(" Delete Graphic Style"); + assert!(!delete.accesskit_node().is_disabled()); + delete.click(); + h.run_steps(3); + + let doc = h.state().session.active().unwrap().doc.clone(); + assert!(doc.graphic_style("Style A").is_none()); + + // Verify one undo step restores it + h.state_mut().run("edit.undo", json!({})).unwrap(); + let doc = h.state().session.active().unwrap().doc.clone(); + assert!(doc.graphic_style("Style A").is_some()); + } + + #[test] + fn right_click_context_menu_default_style_disables_options_and_delete() { + use egui_kittest::kittest::{NodeT, Queryable}; + + let app = app(); + let mut h = egui_kittest::Harness::builder().with_size(vec2(260.0, 400.0)).with_accessibility_check(false).build_ui_state( + |ui, app: &mut VectorcraftApp| { + show(app, ui); + }, + app, + ); + h.run_steps(2); + + let pos_def = h.get_by_label(DEFAULT_GRAPHIC_STYLE).rect().center(); + h.event(egui::Event::PointerMoved(pos_def)); + h.event(egui::Event::PointerButton { pos: pos_def, button: egui::PointerButton::Secondary, pressed: true, modifiers: Default::default() }); + h.event(egui::Event::PointerButton { pos: pos_def, button: egui::PointerButton::Secondary, pressed: false, modifiers: Default::default() }); + h.run_steps(2); + + let options = h.get_by_label(" Graphic Style Options…"); + let duplicate = h.get_by_label(" Duplicate Graphic Style"); + let delete = h.get_by_label(" Delete Graphic Style"); + + assert!(options.accesskit_node().is_disabled(), "Options disabled on Default Graphic Style"); + assert!(!duplicate.accesskit_node().is_disabled(), "Duplicate enabled on Default Graphic Style"); + assert!(delete.accesskit_node().is_disabled(), "Delete disabled on Default Graphic Style"); + } + + #[test] + fn right_click_context_menu_preserves_multiselection_and_works_in_list_view() { + use egui_kittest::kittest::{NodeT, Queryable}; + + let mut app = app(); + app.ui.graphic_styles_view = View::SmallList; + app.run("graphicStyle.new", json!({"name": "Style 1"})).unwrap(); + app.run("graphicStyle.new", json!({"name": "Style 2"})).unwrap(); + + let mut h = egui_kittest::Harness::builder().with_size(vec2(260.0, 400.0)).with_accessibility_check(false).build_ui_state( + |ui, app: &mut VectorcraftApp| { + show(app, ui); + }, + app, + ); + h.run_steps(2); + + set_pstate(&h.ctx, "gs-sel", vec!["Style 1".to_string(), "Style 2".to_string()]); + h.run_steps(1); + + let pos_2 = h.get_by_label("Style 2").rect().center(); + h.event(egui::Event::PointerMoved(pos_2)); + h.event(egui::Event::PointerButton { pos: pos_2, button: egui::PointerButton::Secondary, pressed: true, modifiers: Default::default() }); + h.event(egui::Event::PointerButton { pos: pos_2, button: egui::PointerButton::Secondary, pressed: false, modifiers: Default::default() }); + h.run_steps(2); + + let doc = h.state().session.active().unwrap().doc.clone(); + assert_eq!(selected(&h.ctx, &doc), vec!["Style 1", "Style 2"]); + + let options = h.get_by_label(" Graphic Style Options…"); + let duplicate = h.get_by_label(" Duplicate Graphic Styles"); + let delete = h.get_by_label(" Delete Graphic Styles"); + + assert!(options.accesskit_node().is_disabled(), "Options disabled on multi-selection"); + assert!(!duplicate.accesskit_node().is_disabled()); + assert!(!delete.accesskit_node().is_disabled()); + + duplicate.click(); + h.run_steps(3); + + let doc = h.state().session.active().unwrap().doc.clone(); + assert!(doc.graphic_style("Style 1 copy").is_some()); + assert!(doc.graphic_style("Style 2 copy").is_some()); + } } diff --git a/crates/ui-egui/src/panels/image_trace.rs b/crates/ui-egui/src/panels/image_trace.rs index b0cdfad7f4..ad6a1e5bf3 100644 --- a/crates/ui-egui/src/panels/image_trace.rs +++ b/crates/ui-egui/src/panels/image_trace.rs @@ -21,14 +21,14 @@ use super::{first_node, pstate, set_pstate, swatches}; use crate::VectorcraftApp; use crate::widgets::{self, menu_item}; -const MODES: [(&str, &str); 4] = [("blackAndWhite", "Black and White"), ("grayscale", "Grayscale"), ("color", "Color"), ("logo", "Flat Logo")]; +pub(crate) const MODES: [(&str, &str); 4] = + [("blackAndWhite", "Black and White"), ("grayscale", "Grayscale"), ("color", "Color"), ("logo", "Flat Logo")]; /// Color mode's palettes (`palette` param ids), in panel order. -const PALETTES: [&str; 4] = ["limited", "fullTone", "automatic", "documentLibrary"]; +pub(crate) const PALETTES: [&str; 4] = ["limited", "fullTone", "automatic", "documentLibrary"]; -/// Palette `id`, in the UI language. /// The colour Ignore Color leaves out in `params` (`ignoreColor`, `#rrggbb`): white when there is none. -fn ignore_color(params: &Value) -> [u8; 3] { +pub(crate) fn ignore_color(params: &Value) -> [u8; 3] { let hex = params["ignoreColor"].as_str().unwrap_or("").trim_start_matches('#'); let channel = |i: usize| hex.get(i * 2..i * 2 + 2).and_then(|h| u8::from_str_radix(h, 16).ok()); match (hex.len(), channel(0), channel(1), channel(2)) { @@ -37,7 +37,8 @@ fn ignore_color(params: &Value) -> [u8; 3] { } } -fn palette_label(id: &str) -> &'static str { +/// Palette `id`, in the UI language. +pub(crate) fn palette_label(id: &str) -> &'static str { match id { "fullTone" => tl!("Full Tone"), "automatic" => tl!("Automatic"), @@ -48,7 +49,7 @@ fn palette_label(id: &str) -> &'static str { /// Document Library's Colors choices with the document's swatches: All, then the document's color /// groups (`current` checked; `None` is All) → the choice, `Some(None)` for All. -fn color_group_list(app: &VectorcraftApp, ui: &mut Ui, current: Option<&str>) -> Option> { +pub(crate) fn color_group_list(app: &VectorcraftApp, ui: &mut Ui, current: Option<&str>) -> Option> { let mut chosen = menu_item(ui, "All", true, current.is_none()).then_some(None); let groups: Vec = app.session.active().map(|d| d.doc.swatch_groups.iter().map(|g| g.name.clone()).collect()).unwrap_or_default(); if !groups.is_empty() { @@ -95,7 +96,7 @@ struct TraceUi { /// A preset: its name, its parameters, those of its enhanced version (null if it has none), and /// whether it is built in (else the user saved it). -type Preset = (String, Value, Value, bool); +pub(crate) type Preset = (String, Value, Value, bool); /// The presets as `imageTrace.presets` listed them at a revision of the saved presets. #[derive(Clone)] @@ -112,8 +113,8 @@ thread_local! { /// Every preset, built-in then saved. `imageTrace.presets` runs once for each revision of the saved /// presets ([`vectorcraft_engine::Session::trace_presets_revision`]); the list is kept in `ctx`'s -/// memory, which the panel, the Control bar and Properties share. -fn presets(app: &mut VectorcraftApp, ctx: &egui::Context) -> Arc> { +/// memory, which the panel, the Control bar, Properties and Edit → Tracing Presets share. +pub(crate) fn presets(app: &mut VectorcraftApp, ctx: &egui::Context) -> Arc> { let id = egui::Id::unique("trace-presets"); let revision = app.session.trace_presets_revision(); if let Some(list) = ctx.data(|d| d.get_temp::(id)).filter(|l| l.revision == revision) { @@ -137,7 +138,7 @@ fn presets(app: &mut VectorcraftApp, ctx: &egui::Context) -> Arc> { /// The listed preset that `name` finds, as the engine finds presets: a built-in one by its name in /// any case, also in brackets (`[Default]`), else a saved one by its exact name in any case. -fn find_preset<'a>(all: &'a [Preset], name: &str) -> Option<&'a Preset> { +pub(crate) fn find_preset<'a>(all: &'a [Preset], name: &str) -> Option<&'a Preset> { let name = name.trim(); let key = name.trim_start_matches('[').trim_end_matches(']'); all.iter().find(|p| p.3 && p.0.eq_ignore_ascii_case(key)).or_else(|| all.iter().find(|p| !p.3 && p.0.eq_ignore_ascii_case(name))) @@ -511,7 +512,7 @@ pub(crate) fn open_settings(app: &mut VectorcraftApp) { /// while the menu is open. /// A preset's name as shown: translated as a preset's name where the catalog has it so (the /// Outline preset is not the Outline view), as any other string else. -fn preset_label(name: &str) -> &str { +pub(crate) fn preset_label(name: &str) -> &str { crate::i18n::tr_ctx(crate::i18n::current(), "imageTrace", name) } @@ -655,7 +656,7 @@ pub(crate) fn traced(app: &VectorcraftApp, r: &Value) { set_pstate(&ctx, "image-trace", st); } -fn slider(ui: &mut Ui, label: &str, v: &mut f64, range: std::ops::RangeInclusive, suffix: &str) -> (bool, bool) { +pub(crate) fn slider(ui: &mut Ui, label: &str, v: &mut f64, range: std::ops::RangeInclusive, suffix: &str) -> (bool, bool) { let mut out = (false, false); ui.horizontal(|ui| { ui.add_sized([74.0, 22.0], egui::Label::new(egui::RichText::new(tl!(label)).size(12.0))); diff --git a/crates/ui-egui/src/panels/info.rs b/crates/ui-egui/src/panels/info.rs index 19fe505c0c..753a4cc20b 100644 --- a/crates/ui-egui/src/panels/info.rs +++ b/crates/ui-egui/src/panels/info.rs @@ -111,7 +111,9 @@ impl Rows { } Some(Readout::Scale { sx, sy }) => rows.right = vec![format!("W: {:.1}%", sx * 100.0), format!("H: {:.1}%", sy * 100.0)], Some(Readout::Rotate { angle, .. } | Readout::Reflect { angle, .. }) => rows.right = vec![format!("A: {angle:.1}°")], - Some(Readout::Shear { axis, angle, .. }) => rows.right = vec![format!("A: {axis:.1}°"), format!("{}: {angle:.1}°", tl!("Shear"))], + Some(Readout::Shear { axis, angle, .. }) => { + rows.right = vec![format!("A: {axis:.1}°"), format!("{} {angle:.1}°", crate::i18n::colon(tl!("Shear")))] + } Some(Readout::Brush { .. }) | None => { let (w, h) = s.size.map(|(w, h, _)| (len(w), len(h))).unwrap_or_default(); rows.right = vec![format!("W: {w}"), format!("H: {h}")]; @@ -177,7 +179,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { }); if app.session.tool_id() == "zoom" { let zoom = app.view().map_or(1.0, |v| v.zoom); - mono(ui, format!("{}: {}", tl!("Zoom"), crate::state::zoom_label(zoom, app.session.prefs.display_print_size))); + mono(ui, format!("{} {}", crate::i18n::colon(tl!("Zoom")), crate::state::zoom_label(zoom, app.session.prefs.display_print_size))); } if let Some(Readout::Brush { name: Some(name) }) = readout { mono(ui, name); @@ -317,6 +319,22 @@ mod tests { assert!(texts(&mut app).contains(&want), "{want}: {:?}", texts(&mut app)); } + /// The Shear and Zoom readouts write their colon as the UI language does (#7991). + #[test] + fn readout_labels_use_the_language_colon() { + let mut app = app_with_rect(); + app.session.select_tool("zoom", view()).unwrap(); + let fr = crate::i18n::Lang::from_code("fr").unwrap(); + crate::i18n::set_current(fr); + let shear = shown(Some(&Readout::Shear { center: Point::new(60.0, 70.0), axis: 90.0, angle: -12.5 }), true); + let shown_texts = texts(&mut app); + crate::i18n::set_current(crate::i18n::Lang::EN); + assert_eq!(shear.right[1], format!("{}\u{a0}: -12.5°", crate::i18n::tr(fr, "Shear"))); + let zoom = app.view().map_or(1.0, |v| v.zoom); + let want = format!("{}\u{a0}: {}", crate::i18n::tr(fr, "Zoom"), crate::state::zoom_label(zoom, app.session.prefs.display_print_size)); + assert!(shown_texts.contains(&want), "{want}: {shown_texts:?}"); + } + #[test] fn the_paintbrush_shows_its_brush() { let mut app = app_with_rect(); diff --git a/crates/ui-egui/src/panels/links.rs b/crates/ui-egui/src/panels/links.rs index 14794de987..4c491efb6b 100644 --- a/crates/ui-egui/src/panels/links.rs +++ b/crates/ui-egui/src/panels/links.rs @@ -519,11 +519,11 @@ pub(super) fn status_tip(r: &Value, mask: Option) -> String { _ => None, }; let tip = match art { - Some(kind) => format!("{tip}\n{kind}: {name}"), + Some(kind) => format!("{tip}\n{} {name}", crate::i18n::colon(kind)), None => tip, }; match owner["maskOf"].as_u64() { - Some(id) => format!("{tip}\n{}: {}", tl!("Opacity Mask"), mask.unwrap_or_else(|| id.to_string())), + Some(id) => format!("{tip}\n{} {}", crate::i18n::colon(tl!("Opacity Mask")), mask.unwrap_or_else(|| id.to_string())), None => tip, } } @@ -622,7 +622,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let Some(st) = app.session.active() else { return }; let doc = st.doc.clone(); let thumbs = super::layers::ThumbSource::of(app, st, &doc); - let selected = selected_links(app, ui.ctx()); + let mut selected = selected_links(app, ui.ctx()); let rows: &[Value] = cache.list["links"].as_array().map_or(&[], Vec::as_slice); let mut clicked: Option<(u64, egui::Modifiers, bool)> = None; widgets::list_box(ui, |ui| { @@ -698,6 +698,14 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { .and_then(|m| doc.node(NodeId(m)).or_else(|| cache.nested_node(m).map(|n| &**n))) .map(|n| super::layers::shown_name(app, n, crate::i18n::current())); let resp = resp.on_hover_text(status_tip(r, mask)); + resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::ListItem, ui.is_enabled(), selected.contains(&id), name)); + if resp.secondary_clicked() && !selected.contains(&id) { + click(app, ui.ctx(), rows, id, egui::Modifiers::NONE); + selected = selected_links(app, ui.ctx()); + } + resp.context_menu(|ui| { + row_context_menu(app, ui, r, id, &cache.list); + }); if resp.double_clicked() { clicked = Some((id, egui::Modifiers::NONE, true)); } else if resp.clicked() { @@ -767,6 +775,78 @@ fn break_link(app: &mut VectorcraftApp, ids: Vec) { }); } +/// Embed images `ids` (`links.embed`). +fn embed_images(app: &mut VectorcraftApp, ids: Vec) { + let r = app.run("links.embed", json!({ "ids": ids })); + report(app, r, |v| { + let missing = v["missing"].as_array().map_or(0, Vec::len); + let n = v["embedded"].as_array().map_or(0, Vec::len); + if missing == 0 { + crate::i18n::msg_n(n as u64, "Embedded {n} image", "Embedded {n} images", &[]) + } else { + crate::i18n::msg_n( + n as u64, + "Embedded {n} image; {missing} missing: relink them first", + "Embedded {n} images; {missing} missing: relink them first", + &[("missing", &missing.to_string())], + ) + } + }); +} + +/// An item's right-click context menu in the Links panel. +fn row_context_menu(app: &mut VectorcraftApp, ui: &mut Ui, r: &Value, id: u64, list: &Value) { + let selected = selected_links(app, ui.ctx()); + let sel = selected_rows(list, &selected); + let linked = ids(&sel, |r| r["linked"] == true); + let embedded: Vec<&Value> = sel.iter().copied().filter(|r| status_is(r, "embedded")).collect(); + let modified = ids(&sel, |r| status_is(r, "modified") || (r["preview"] == true && !status_is(r, "missing"))); + let can_edit = sel.iter().any(|r| r["linked"] == true && !status_is(r, "missing")); + let in_canvas = app.session.active().is_some_and(|st| st.doc.node(NodeId(id)).is_some()) && !nested_row(r); + + if menu_item(ui, tl!("Relink…"), !sel.is_empty() && can_pick(app), false) { + crate::menus::invoke(app, "ui.relinkDialog", json!({ "ids": ids(&sel, |_| true) })); + ui.close(); + } + if menu_item(ui, tl!("Go To Link"), in_canvas, false) { + go_to(app, id); + ui.close(); + } + if menu_item(ui, tl!("Update Link"), !modified.is_empty(), false) { + let r = app.run("links.update", json!({ "ids": modified })); + report(app, r, |v| updated_status(v["updated"].as_array().map_or(0, Vec::len))); + ui.close(); + } + if menu_item(ui, tl!("Edit Original"), can_edit, false) { + let file_arg = if r["linked"] == true && !status_is(r, "missing") { json!({ "id": id }) } else { file_row(&sel) }; + crate::menus::invoke(app, "links.editOriginal", file_arg); + ui.close(); + } + if menu_item(ui, tl!("Show in Folder"), can_edit, false) { + let file_arg = if r["linked"] == true && !status_is(r, "missing") { json!({ "id": id }) } else { file_row(&sel) }; + crate::menus::invoke(app, "links.reveal", file_arg); + ui.close(); + } + ui.separator(); + if status_is(r, "embedded") { + if menu_item(ui, tl!("Unembed…"), can_unembed(app, embedded.len()), false) { + match &embedded[..] { + [r] => { + if let Some(id) = r["id"].as_u64() { + let name = r["name"].as_str().unwrap_or("Image").to_string(); + unembed(app, id, &name); + } + } + rows => unembed_several(app, rows.iter().filter_map(|r| r["id"].as_u64()).collect()), + } + ui.close(); + } + } else if menu_item(ui, tl!("Embed Image"), !linked.is_empty(), false) { + embed_images(app, linked); + ui.close(); + } +} + /// The params of Edit Original and Show in Folder for the selected rows `sel`: the first linked /// row whose file is there (rows outside the layer tree included), else none (the selection's). fn file_row(sel: &[&Value]) -> Value { @@ -893,21 +973,7 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { } ui.separator(); if menu_item(ui, tl!("Embed Image(s)"), !linked.is_empty(), false) { - let r = app.run("links.embed", json!({ "ids": linked })); - report(app, r, |v| { - let missing = v["missing"].as_array().map_or(0, Vec::len); - let n = v["embedded"].as_array().map_or(0, Vec::len); - if missing == 0 { - crate::i18n::msg_n(n as u64, "Embedded {n} image", "Embedded {n} images", &[]) - } else { - crate::i18n::msg_n( - n as u64, - "Embedded {n} image; {missing} missing: relink them first", - "Embedded {n} images; {missing} missing: relink them first", - &[("missing", &missing.to_string())], - ) - } - }); + embed_images(app, linked); } if menu_item(ui, tl!("Unembed…"), can_unembed(app, embedded.len()), false) { match &embedded[..] { diff --git a/crates/ui-egui/src/panels/preflight.rs b/crates/ui-egui/src/panels/preflight.rs index 0be4c4296b..ff8b9214d7 100644 --- a/crates/ui-egui/src/panels/preflight.rs +++ b/crates/ui-egui/src/panels/preflight.rs @@ -187,7 +187,7 @@ fn results(app: &mut VectorcraftApp, ui: &mut Ui, report: &Value) { } if let Some(ppi) = finding["effectivePpi"].as_array() { let values = ppi.iter().filter_map(Value::as_f64).map(|n| format!("{n:.0}")).collect::>(); - dim_label(ui, &format!("{}: {} ppi", tl!("Effective PPI"), values.join(" × "))); + dim_label(ui, &effective_ppi_line(&values)); } let source = finding["sourceId"].as_u64(); if code == "missingLink" @@ -220,5 +220,10 @@ fn results(app: &mut VectorcraftApp, ui: &mut Ui, report: &Value) { dim_label(ui, tl!("These checks do not certify an exported file.")); } +/// A low-resolution finding's effective resolution, one value per axis. +fn effective_ppi_line(values: &[String]) -> String { + format!("{} {} ppi", crate::i18n::colon(tl!("Effective PPI")), values.join(" × ")) +} + #[cfg(test)] mod tests; diff --git a/crates/ui-egui/src/panels/preflight/tests.rs b/crates/ui-egui/src/panels/preflight/tests.rs index 448a114bbf..0b6d2bf509 100644 --- a/crates/ui-egui/src/panels/preflight/tests.rs +++ b/crates/ui-egui/src/panels/preflight/tests.rs @@ -153,6 +153,18 @@ fn preflight_panel_rechecks_missing_files_on_its_timer_and_on_request() { std::fs::remove_file(&path).unwrap(); } +/// The Effective PPI line writes its colon as the UI language does (#7991). +#[test] +fn effective_ppi_uses_the_language_colon() { + let values = ["150".to_string(), "300".to_string()]; + let fr = crate::i18n::Lang::from_code("fr").unwrap(); + crate::i18n::set_current(fr); + let french = effective_ppi_line(&values); + crate::i18n::set_current(crate::i18n::Lang::EN); + assert_eq!(french, format!("{}\u{a0}: 150 × 300 ppi", crate::i18n::tr(fr, "Effective PPI"))); + assert_eq!(effective_ppi_line(&values), "Effective PPI: 150 × 300 ppi"); +} + /// An optional visual QA artifact, never a checked-in snapshot or an asset shipped by the app. #[test] #[ignore = "set PREFLIGHT_PREVIEW_PATH to write an offscreen GPU render for visual review"] diff --git a/crates/ui-egui/src/panels/properties.rs b/crates/ui-egui/src/panels/properties.rs index 52b74a5fb5..94b4edc638 100644 --- a/crates/ui-egui/src/panels/properties.rs +++ b/crates/ui-egui/src/panels/properties.rs @@ -767,7 +767,9 @@ fn document_sections(app: &mut VectorcraftApp, ui: &mut Ui) { if widgets::icon_button(ui, "ruler", tl!("Show Rulers (⌘R)"), v.rulers, 26.0).clicked() { app.run("view.rulers", json!({})).ok(); } - if widgets::icon_button(ui, "grid-3x3", tl!("Show Grid (⌘')"), v.grid, 26.0).clicked() { + // Trim View holds the grid and the guides off while it is on (#8363). + let shows = crate::menus::enabled(app, "view.grid"); + if widgets::icon_button_enabled(ui, "grid-3x3", tl!("Show Grid (⌘')"), v.grid, shows, 26.0).clicked() { app.run("view.grid", json!({})).ok(); } let transparency_grid = app.session.active().is_some_and(|d| d.transparency_grid); @@ -779,7 +781,8 @@ fn document_sections(app: &mut VectorcraftApp, ui: &mut Ui) { section_header(ui, tl!("Guides")); ui.horizontal(|ui| { let v = app.ui.view.clone(); - if widgets::icon_button(ui, "layout-grid", tl!("Show Guides"), v.guides, 26.0).clicked() { + let shows = crate::menus::enabled(app, "view.guides"); + if widgets::icon_button_enabled(ui, "layout-grid", tl!("Show Guides"), v.guides, shows, 26.0).clicked() { app.run("view.guides", json!({})).ok(); } if widgets::icon_button(ui, "sparkles", tl!("Smart Guides (⌘U)"), v.smart_guides, 26.0).clicked() { diff --git a/crates/ui-egui/src/panels/properties/tests.rs b/crates/ui-egui/src/panels/properties/tests.rs index 613eb73793..bc41fef557 100644 --- a/crates/ui-egui/src/panels/properties/tests.rs +++ b/crates/ui-egui/src/panels/properties/tests.rs @@ -1575,11 +1575,11 @@ fn direct_selected_corners_show_their_kind_and_radius() { // The whole path selected. app.run("select.set", json!({"ids": [star]})).unwrap(); assert!(!shows(&tall(&mut app, &ctx, vec![]), "Corner:"), "no corner selected"); - // A live rectangle's corner: its own Corner Radius row, once. + // A live rectangle's corner: its own Corner Radius row and Corner menu, once each. let r = rect(&mut app, 20.0, 20.0, 60.0, 40.0).as_u64().unwrap(); app.run("select.anchors", json!({"id": r, "anchors": [[0, 1]], "mode": "set"})).unwrap(); let texts = tall(&mut app, &ctx, vec![]); - assert!(!shows(&texts, "Corner:"), "{texts:?}"); + assert_eq!(texts.iter().filter(|(t, _)| t == "Corner:").count(), 1, "{texts:?}"); assert_eq!(texts.iter().filter(|(t, _)| t == "Corner Radius:").count(), 1, "{texts:?}"); } diff --git a/crates/ui-egui/src/panels/stroke.rs b/crates/ui-egui/src/panels/stroke.rs index 9e245fdc2c..3ba5451568 100644 --- a/crates/ui-egui/src/panels/stroke.rs +++ b/crates/ui-egui/src/panels/stroke.rs @@ -514,7 +514,7 @@ pub(crate) const PROFILE_DROPDOWN_WIDTH: f32 = 100.0; /// member's. pub(crate) fn brush_keeps_size(app: &VectorcraftApp, ctx: &egui::Context, shown: Option<&StrokeLayer>) -> Option { let st = app.session.active()?; - let bucket = app.session.tool_id() == "livePaintBucket"; + let bucket = app.session.bucket_paints(); if bucket || (st.selection.objects.is_empty() && st.selection.subjects().is_empty()) { let s = shown?; let name = s.brush.as_deref()?; diff --git a/crates/ui-egui/src/panels/tests_brush_libraries.rs b/crates/ui-egui/src/panels/tests_brush_libraries.rs index fb27a8aaa2..49b25e987b 100644 --- a/crates/ui-egui/src/panels/tests_brush_libraries.rs +++ b/crates/ui-egui/src/panels/tests_brush_libraries.rs @@ -199,6 +199,7 @@ fn the_window_menu_and_the_brushes_panel_open_brush_libraries() { json!("bristle-brushes"), json!("paint"), json!("pattern-borders"), + json!("decorative"), json!("scatter-shapes"), json!("stipple"), json!("game-trails"), @@ -207,7 +208,9 @@ fn the_window_menu_and_the_brushes_panel_open_brush_libraries() { json!("tech-circuit"), json!("engraving"), json!("arrows"), - json!("image-brush") + json!("image-brush"), + json!("artistic"), + json!("vector-packs") ] ); let dry = entries.iter().find(|e| under(e) && e.params["library"] == "dry-media").map(|e| e.label.as_str()); @@ -238,22 +241,60 @@ fn the_window_menu_and_the_brushes_panel_open_brush_libraries() { click(&mut app, &ctx, "Circuit Trace", Modifiers::NONE, 2.0); assert!(has(&app, "Circuit Trace") && !has(&app, "Bus Lines")); assert_eq!(undo_len(&app), undo + 1); + let r = app.run("window.brushLibrary", json!({"library": "Artistic Brushes"})).unwrap(); + assert_eq!((r["open"].as_str(), r["count"].as_u64()), (Some("artistic"), Some(4))); + let previous = crate::i18n::current(); + crate::i18n::set_current(crate::i18n::Lang::from_code("de").unwrap()); + assert_eq!(crate::menus::display_label(&app, "window.brushLibrary", "Artistic Brushes"), "Künstlerische Pinsel"); + crate::i18n::set_current(previous); + let undo = undo_len(&app); + click(&mut app, &ctx, "Orbit Lines", Modifiers::NONE, 3.0); + assert!(has(&app, "Orbit Lines") && !has(&app, "Facet Sweep")); + assert_eq!(undo_len(&app), undo + 1); + let r = app.run("window.brushLibrary", json!({"library": "Vector Packs"})).unwrap(); + assert_eq!((r["open"].as_str(), r["count"].as_u64()), (Some("vector-packs"), Some(4))); + let undo = undo_len(&app); + click(&mut app, &ctx, "Compass Rose", Modifiers::NONE, 4.0); + assert!(has(&app, "Compass Rose") && !has(&app, "Facet Diamond")); + assert_eq!(undo_len(&app), undo + 1); + // Without brushes there is nothing to save. + let all: Vec = vectorcraft_brush::library(&app.session.doc().unwrap().doc).into_iter().map(|b| b.name).collect(); + app.run("brush.delete", json!({ "names": all })).unwrap(); + let entries = crate::menus::menu_entries(&app); + assert!(entries.iter().any(|e| under(e) && e.command.as_deref() == Some("ui.saveBrushLibrary") && !e.enabled)); +} + +#[test] +fn pressure_decorative_paint_and_image_libraries_add_a_brush_in_one_step() { + let mut app = app(); + let ctx = context(); let r = app.run("window.brushLibrary", json!({"library": "Pressure Sensitive"})).unwrap(); assert_eq!((r["open"].as_str(), r["count"].as_u64()), (Some("pressure-sensitive"), Some(4))); let path = app.run("shape.line", json!({"x1": 10, "y1": 100, "x2": 180, "y2": 100})).unwrap()["id"].as_u64().unwrap(); let undo = undo_len(&app); - click(&mut app, &ctx, "Flex Ribbon", Modifiers::NONE, 3.0); + click(&mut app, &ctx, "Flex Ribbon", Modifiers::NONE, 4.0); assert!(has(&app, "Flex Ribbon") && !has(&app, "Pulse Stroke")); assert_eq!(undo_len(&app), undo + 1); assert_eq!( app.session.doc().unwrap().doc.node(vectorcraft_doc::NodeId(path)).unwrap().appearance.stroke().unwrap().brush.as_deref(), Some("Flex Ribbon") ); + let r = app.run("window.brushLibrary", json!({"library": "Decorative"})).unwrap(); + assert_eq!((r["open"].as_str(), r["count"].as_u64()), (Some("decorative"), Some(4))); + let path = app.run("shape.line", json!({"x1": 10, "y1": 100, "x2": 180, "y2": 100})).unwrap()["id"].as_u64().unwrap(); + let undo = undo_len(&app); + click(&mut app, &ctx, "Leaf Vine", Modifiers::NONE, 5.0); + assert!(has(&app, "Leaf Vine") && !has(&app, "Lantern String")); + assert_eq!(undo_len(&app), undo + 1); + assert_eq!( + app.session.doc().unwrap().doc.node(vectorcraft_doc::NodeId(path)).unwrap().appearance.stroke().unwrap().brush.as_deref(), + Some("Leaf Vine") + ); let r = app.run("window.brushLibrary", json!({"library": "Paint"})).unwrap(); assert_eq!((r["open"].as_str(), r["count"].as_u64()), (Some("paint"), Some(4))); let path = app.run("shape.line", json!({"x1": 10, "y1": 140, "x2": 180, "y2": 140})).unwrap()["id"].as_u64().unwrap(); let undo = undo_len(&app); - click(&mut app, &ctx, "Flat Sweep", Modifiers::NONE, 4.0); + click(&mut app, &ctx, "Flat Sweep", Modifiers::NONE, 6.0); assert!(has(&app, "Flat Sweep") && !has(&app, "Dry Drag")); assert_eq!(undo_len(&app), undo + 1); assert_eq!( @@ -263,14 +304,9 @@ fn the_window_menu_and_the_brushes_panel_open_brush_libraries() { let r = app.run("window.brushLibrary", json!({"library": "Image Brush"})).unwrap(); assert_eq!((r["open"].as_str(), r["count"].as_u64()), (Some("image-brush"), Some(4))); let undo = undo_len(&app); - click(&mut app, &ctx, "Soft Bloom", Modifiers::NONE, 5.0); + click(&mut app, &ctx, "Soft Bloom", Modifiers::NONE, 8.0); assert!(has(&app, "Soft Bloom") && !has(&app, "Color Flecks")); assert_eq!(undo_len(&app), undo + 1); - // Without brushes there is nothing to save. - let all: Vec = vectorcraft_brush::library(&app.session.doc().unwrap().doc).into_iter().map(|b| b.name).collect(); - app.run("brush.delete", json!({ "names": all })).unwrap(); - let entries = crate::menus::menu_entries(&app); - assert!(entries.iter().any(|e| under(e) && e.command.as_deref() == Some("ui.saveBrushLibrary") && !e.enabled)); } #[test] diff --git a/crates/ui-egui/src/panels/tests_color_wheel.rs b/crates/ui-egui/src/panels/tests_color_wheel.rs index 798a842e4c..49e6c6f027 100644 --- a/crates/ui-egui/src/panels/tests_color_wheel.rs +++ b/crates/ui-egui/src/panels/tests_color_wheel.rs @@ -11,7 +11,9 @@ use vectorcraft_color::cms::{self, Cms, ColorSettings, delta_e2000}; use vectorcraft_color::{Color, Paint}; use vectorcraft_engine::Session; -use super::color_wheel::{ID, display_hsb, remembered_hsb, show, stored}; +use super::color_wheel::{ + ID, Settings, Sliders, chroma_tick, display_hsb, oklch_rows, oklch_track, remembered_hsb, remembered_hsl, remembered_oklch, set, show, stored, +}; use crate::VectorcraftApp; /// An app with a selected rectangle filled with `fill`. @@ -581,3 +583,573 @@ fn the_color_pickers_field_takes_the_arrow_keys() { assert!(near(stepped, [after[0], after[1] + 0.01, after[2]], [1e-3, 1e-4, 1e-4]), "{after:?} → {stepped:?}"); assert!(h.state().ui.dialog.is_some(), "the dialog stays open"); } + +/// The panel with OKLCH Sliders shown, in a flyout tall enough for the rows. +fn oklch_harness(mut app: VectorcraftApp) -> Harness<'static, VectorcraftApp> { + app.run("ui.colorWheel", json!({"sliders": "oklch"})).unwrap(); + oklch_harness_shown(app) +} + +/// The panel in a flyout tall enough for the rows, with the app's settings as they are. +fn oklch_harness_shown(app: VectorcraftApp) -> Harness<'static, VectorcraftApp> { + let mut h = Harness::builder().with_size(vec2(260.0, 420.0)).build_ui_state( + |ui, app: &mut VectorcraftApp| { + show(app, ui); + crate::shortcuts::handle(app, ui.ctx()); + }, + app, + ); + h.run_steps(2); + h +} + +/// The slider row named `name` (its number field has the same name). +fn oklch_slider<'a>(h: &'a Harness<'static, VectorcraftApp>, name: &'a str) -> egui_kittest::Node<'a> { + h.query_all_by_label(name).find(|n| n.accesskit_node().role() == egui::accesskit::Role::Slider).expect("a slider row") +} + +/// The point at `t` (0..1) along the bar of a slider row. +fn on_rail(rail: Rect, t: f32) -> Pos2 { + Pos2::new(rail.left() + 4.0 + t * (rail.width() - 8.0), rail.top() + 7.0) +} + +fn fill_oklch(app: &VectorcraftApp) -> [f64; 3] { + vectorcraft_color::oklab::to_oklch(cms::active().display_rgb(&fill(app))) +} + +/// `ui.colorWheel {sliders: "oklch"}` shows L, C and H rows with the fill's OKLCH, and the panel +/// keeps the setting with the preferences. +#[test] +fn oklch_sliders_show_the_fills_lightness_chroma_and_hue() { + let h = oklch_harness(app(json!("#ff0000"))); + assert_eq!(h.state().ui.color_wheel.sliders, Sliders::Oklch); + let value = |name: &str| oklch_slider(&h, name).accesskit_node().numeric_value().unwrap(); + assert_eq!((value("Lightness"), value("Chroma"), value("Hue")), (63.0, 64.0, 29.0)); + let saved = serde_json::to_value(&h.state().ui).unwrap(); + assert_eq!(saved["color_wheel"]["sliders"], json!("oklch")); +} + +/// A drag on L past the chroma sRGB holds stores the largest chroma that fits at the same hue, and +/// the C row keeps the chroma asked for, so dragging L back brings it back. +#[test] +fn a_drag_on_lightness_keeps_the_chroma_asked_for() { + let mut h = oklch_harness(app(json!("#0000ff"))); + let [l0, c0, h0] = fill_oklch(h.state()); + let rail = oklch_slider(&h, "Lightness").rect(); + drag(&mut h, &[on_rail(rail, l0 as f32), on_rail(rail, 0.9)], Modifiers::NONE); + let [l1, c1, h1] = fill_oklch(h.state()); + assert!((l1 - 0.9).abs() < 0.01 && c1 < c0 - 0.1 && (h1 - h0).abs() < 1.0, "{:?} → {:?}", [l0, c0, h0], [l1, c1, h1]); + let chroma = oklch_slider(&h, "Chroma").accesskit_node().numeric_value().unwrap(); + assert_eq!(chroma, (c0 / 0.4 * 100.0).round(), "the C row keeps the requested chroma"); + drag(&mut h, &[on_rail(rail, 0.9), on_rail(rail, l0 as f32)], Modifiers::NONE); + let [l2, c2, _] = fill_oklch(h.state()); + assert!((l2 - l0).abs() < 0.01 && (c2 - c0).abs() < 0.01, "{:?} → {:?}", [l0, c0], [l2, c2]); +} + +/// A press on a row gives it the keyboard focus, and → raises it by one unit as one undo step. +/// Each row reports its range and the adjust actions to screen readers. +#[test] +fn the_oklch_rows_take_the_arrow_keys_and_screen_readers_actions() { + let mut h = oklch_harness(app(json!("#808080"))); + for (name, max) in [("Lightness", 100.0), ("Chroma", 100.0), ("Hue", 360.0)] { + let node = oklch_slider(&h, name).accesskit_node(); + assert_eq!((node.min_numeric_value(), node.max_numeric_value(), node.numeric_value_step()), (Some(0.0), Some(max), Some(1.0)), "{name}"); + assert!([Action::Increment, Action::Decrement, Action::SetValue].iter().all(|a| node.data().supports_action(*a)), "{name}"); + } + let rail = oklch_slider(&h, "Lightness").rect(); + let l = fill_oklch(h.state())[0]; + click(&mut h, on_rail(rail, l as f32), Modifiers::NONE); + let before = fill_oklch(h.state())[0]; + let undo = undo_len(h.state()); + key(&mut h, egui::Key::ArrowRight, Modifiers::NONE); + let after = fill_oklch(h.state())[0]; + assert!((after - ((before * 100.0).round() + 1.0) / 100.0).abs() < 0.003, "{before} → {after}"); + assert_eq!(undo_len(h.state()), undo + 1, "one undo step"); + let (gray, undo) = (fill(h.state()), undo_len(h.state())); + let (target_node, target_tree) = oklch_slider(&h, "Hue").accesskit_node().locate(); + let data = Some(ActionData::NumericValue(200.0)); + h.event(Event::AccessKitActionRequest(ActionRequest { target_node, target_tree, action: Action::SetValue, data })); + // The frame that takes the request draws the row before it applies it. + h.run_steps(2); + assert_eq!(oklch_slider(&h, "Hue").accesskit_node().numeric_value(), Some(200.0), "a gray keeps the hue it was given"); + assert_eq!((fill(h.state()), undo_len(h.state())), (gray, undo), "a hue on a gray changes nothing and records no undo step"); +} + +/// Each track dims the colors outside sRGB, and the C track's tick sits at the largest chroma sRGB +/// holds, along the track's 0 to 0.4. +#[test] +fn the_oklch_tracks_dim_the_colors_outside_srgb_and_the_tick_marks_the_largest_chroma() { + let (l, h) = (0.7, 150.0); + let max = vectorcraft_color::oklab::max_chroma(l, h); + for max_chroma in [Some(max), None] { + assert_eq!(oklch_track([l, max * 0.5, h], max_chroma).a(), 255, "{max_chroma:?}: inside sRGB"); + assert!(oklch_track([l, 0.4, h], max_chroma).a() < 255, "{max_chroma:?}: outside sRGB is dimmed"); + } + // Near white, an L or H track shows the color a pick there stores: the largest chroma that fits, + // not each channel clamped on its own. + let (stored, lowered) = vectorcraft_color::oklab::from_oklch(0.98, 0.2, h); + let [r, g, b] = stored.map(|v| (f64::from(v).clamp(0.0, 1.0) * 255.0).round() as u8); + assert!(lowered); + assert_eq!(oklch_track([0.98, 0.2, h], None), egui::Color32::from_rgb(r, g, b).gamma_multiply(0.3)); + // At blue's L and H the ray leaves sRGB below the largest chroma and comes back at blue: the C + // track dims that gap and shows the color a pick there stores. + let [bl, _, bh] = vectorcraft_color::oklab::to_oklch([0.0, 0.0, 1.0]); + let blue_max = vectorcraft_color::oklab::max_chroma(bl, bh); + let (stored, lowered) = vectorcraft_color::oklab::from_oklch(bl, 0.29, bh); + let [r, g, b] = stored.map(|v| (f64::from(v).clamp(0.0, 1.0) * 255.0).round() as u8); + assert!(lowered && blue_max > 0.3); + assert_eq!(oklch_track([bl, 0.29, bh], Some(blue_max)), egui::Color32::from_rgb(r, g, b).gamma_multiply(0.3)); + assert_eq!(oklch_track([bl, blue_max, bh], Some(blue_max)).a(), 255, "blue itself is inside sRGB"); + assert!((chroma_tick(max) - (max / 0.4) as f32).abs() < 1e-6 && chroma_tick(max) > 0.1 && chroma_tick(max) < 1.0); + assert_eq!((chroma_tick(0.0), chroma_tick(0.5)), (0.0, 1.0)); +} + +/// After Edit › Color Settings picks a working RGB space other than sRGB, Panel menu › OKLCH Sliders +/// is gray and `ui.colorWheel {sliders: "oklch"}` answers an error; rows already shown are gray. +#[test] +fn oklch_sliders_are_gray_after_the_working_space_changes() { + const CHILD: &str = "VECTORCRAFT_TEST_COLOR_WHEEL_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::oklch_sliders_are_gray_after_the_working_space_changes", "--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(json!("#ff0000")); + app.run("edit.colorSettings", json!({"rgb": cms::DISPLAY_P3})).unwrap(); + assert_eq!(app.run("ui.colorWheel", json!({"sliders": "oklch"})).unwrap_err(), "OKLCH needs sRGB as the working RGB space"); + assert_eq!(app.ui.color_wheel.sliders, Sliders::None); + let mut fonts = false; + let mut h = Harness::builder().with_size(vec2(260.0, 200.0)).build_ui_state( + move |ui, app: &mut VectorcraftApp| { + if !fonts { + crate::theme::install_fonts(ui.ctx()); + fonts = true; + return; + } + super::color_wheel::menu(app, ui); + }, + app, + ); + h.run_steps(3); + assert!(h.get_by_label(" OKLCH Sliders").accesskit_node().is_disabled()); + // The color settings stay with the process, so a new app works in Display P3 as well. + let mut app = self::app(json!("#ff0000")); + app.ui.color_wheel.sliders = Sliders::Oklch; + let h = oklch_harness_shown(app); + assert!(oklch_slider(&h, "Lightness").accesskit_node().is_disabled()); +} + +/// A drag on an OKLCH row during which Edit › Color Settings picks a working RGB space other than +/// sRGB keeps the color the drag previewed as one undo step and leaves no interaction open, though +/// the gray rows report no release. +#[test] +fn a_working_space_change_during_an_oklch_drag_keeps_its_color_as_one_undo_step() { + const CHILD: &str = "VECTORCRAFT_TEST_COLOR_WHEEL_P3_DRAG"; + 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::a_working_space_change_during_an_oklch_drag_keeps_its_color_as_one_undo_step", + "--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 h = oklch_harness(app(json!("#ff8000"))); + let rail = oklch_slider(&h, "Lightness").rect(); + let undo = undo_len(h.state()); + press(&mut h, on_rail(rail, 0.5), true, Modifiers::NONE); + for _ in 0..2 { + h.event(Event::PointerMoved(on_rail(rail, 0.25))); + h.run_steps(1); + } + assert!(h.state().session.in_interaction(), "the drag previews"); + let previewed = fill(h.state()); + h.state_mut().run("edit.colorSettings", json!({"rgb": cms::DISPLAY_P3})).unwrap(); + h.run_steps(2); + assert!(oklch_slider(&h, "Lightness").accesskit_node().is_disabled()); + press(&mut h, on_rail(rail, 0.25), false, Modifiers::NONE); + assert!(!h.state().session.in_interaction(), "the interaction ended"); + assert_eq!((fill(h.state()), undo_len(h.state())), (previewed, undo + 1)); +} + +/// A CMYK fill's L, C and H are those of its display color, not of its naive separation. +#[test] +fn a_cmyk_fills_oklch_is_that_of_its_display_color() { + let h = oklch_harness(app(json!({"c": 1.0, "m": 0.0, "y": 0.0, "k": 0.0}))); + let shown = vectorcraft_color::oklab::to_oklch(cms::active().display_rgb(&Color::cmyk(1.0, 0.0, 0.0, 0.0))); + let naive = vectorcraft_color::oklab::to_oklch([0.0, 1.0, 1.0]); + let lightness = oklch_slider(&h, "Lightness").accesskit_node().numeric_value().unwrap(); + assert_eq!(lightness, (shown[0] * 100.0).round()); + assert_ne!(lightness, (naive[0] * 100.0).round()); +} + +/// Panel menu › OKLCH Sliders shows the rows and, checked, hides them. +#[test] +fn the_panel_menu_shows_and_hides_the_oklch_rows() { + let mut fonts = false; + let mut h = Harness::builder().with_size(vec2(260.0, 200.0)).build_ui_state( + move |ui, app: &mut VectorcraftApp| { + // The fonts, which hold the check mark, take effect from the next frame. + if !fonts { + crate::theme::install_fonts(ui.ctx()); + fonts = true; + return; + } + super::color_wheel::menu(app, ui); + }, + app(json!("#ff0000")), + ); + h.run_steps(3); + h.get_by_label(" OKLCH Sliders").click(); + h.run_steps(2); + assert_eq!(h.state().ui.color_wheel.sliders, Sliders::Oklch); + h.get_by_label("✓ OKLCH Sliders").click(); + h.run_steps(2); + assert_eq!(h.state().ui.color_wheel.sliders, Sliders::None); +} + +/// In a working RGB space other than sRGB, `sliders: "oklch"` is an error and the rows are gray; +/// the error leaves the settings as they were. +#[test] +fn oklch_sliders_need_srgb_as_the_working_space() { + let p3 = Cms::new(&ColorSettings { rgb: cms::DISPLAY_P3.into(), ..ColorSettings::default() }).unwrap(); + let mut settings = Settings::default(); + assert_eq!(set(&mut settings, &json!({"sliders": "oklch"}), &p3).unwrap_err(), "OKLCH needs sRGB as the working RGB space"); + assert_eq!(settings.sliders, Sliders::None); + set(&mut settings, &json!({"sliders": "oklch"}), &Cms::default()).unwrap(); + assert_eq!(settings.sliders, Sliders::Oklch); + set(&mut settings, &json!({"sliders": "none"}), &p3).unwrap(); + assert_eq!(settings.sliders, Sliders::None, "the rows can be hidden in any working space"); + let mut h = Harness::builder().with_size(vec2(260.0, 200.0)).build_ui_state( + move |ui, app: &mut VectorcraftApp| { + let tgt = super::color::wheel_target(app, ui); + let color = tgt.color(); + let picked = oklch_rows(app, ui, &tgt, color, &p3); + assert!(picked.is_none(), "a gray row picks nothing: {picked:?}"); + }, + app(json!("#ff0000")), + ); + h.run_steps(2); + assert!(oklch_slider(&h, "Lightness").accesskit_node().is_disabled()); + let rail = oklch_slider(&h, "Lightness").rect(); + click(&mut h, on_rail(rail, 0.2), Modifiers::NONE); + key(&mut h, egui::Key::ArrowRight, Modifiers::NONE); + set_slider_value(&mut h, "Lightness", 20.0); +} + +/// The rows show what they asked for while the color displays as it did, and the color's own +/// OKLCH after the color settings change its display. +#[test] +fn the_remembered_oklch_follows_a_change_of_working_space() { + let srgb = Cms::default(); + let p3 = Cms::new(&ColorSettings { rgb: cms::DISPLAY_P3.into(), ..ColorSettings::default() }).unwrap(); + let c = Color::rgb(0.5, 0.3, 0.2); + let asked = [0.5, 0.3, 40.0]; + let shown = srgb.display_rgb(&c); + assert_eq!(remembered_oklch(&srgb, &c, shown, asked), asked); + assert_eq!(remembered_oklch(&p3, &c, shown, asked), vectorcraft_color::oklab::to_oklch(p3.display_rgb(&c))); +} + +/// The panel with HSL Sliders shown, in a flyout tall enough for the rows. `oklch_slider` and +/// `oklch_harness_shown` find and draw any slider row, the HSL rows included. +fn hsl_harness(mut app: VectorcraftApp) -> Harness<'static, VectorcraftApp> { + app.run("ui.colorWheel", json!({"sliders": "hsl"})).unwrap(); + oklch_harness_shown(app) +} + +fn fill_hsl(app: &VectorcraftApp) -> [f32; 3] { + vectorcraft_color::rgb_to_hsl(cms::active().display_rgb(&fill(app))) +} + +/// Sets the slider row named `name` to `v` as a screen reader does. +fn set_slider_value(h: &mut Harness<'static, VectorcraftApp>, name: &str, v: f64) { + let (target_node, target_tree) = oklch_slider(h, name).accesskit_node().locate(); + let data = Some(ActionData::NumericValue(v)); + h.event(Event::AccessKitActionRequest(ActionRequest { target_node, target_tree, action: Action::SetValue, data })); + // The frame that takes the request draws the row before it applies it. + h.run_steps(2); +} + +/// `ui.colorWheel {sliders: "hsl"}` shows H, S and L rows with the fill's HSL, CSS Color 4's +/// `hsl()` of its display sRGB, and the panel keeps the setting with the preferences. +#[test] +fn hsl_sliders_show_the_fills_hue_saturation_and_lightness() { + let h = hsl_harness(app(json!("#ff8000"))); + assert_eq!(h.state().ui.color_wheel.sliders, Sliders::Hsl); + let value = |name: &str| oklch_slider(&h, name).accesskit_node().numeric_value().unwrap(); + assert_eq!((value("HSL Hue"), value("HSL Saturation"), value("HSL Lightness")), (30.0, 100.0, 50.0)); + assert!(h.query_by_label("Chroma").is_none(), "OKLCH Sliders are hidden"); + let saved = serde_json::to_value(&h.state().ui).unwrap(); + assert_eq!(saved["color_wheel"]["sliders"], json!("hsl")); +} + +/// In Box View with the Saturation channel, screen readers tell the box strip's HSB saturation +/// from the S row's HSL saturation by their names. +#[test] +fn the_hsl_rows_names_differ_from_the_box_strips() { + let mut app = app(json!("#996633")); + app.run("ui.colorWheel", json!({"view": "box", "channel": "saturation"})).unwrap(); + let h = hsl_harness(app); + let sliders = |name: &str| h.query_all_by_label(name).filter(|n| n.accesskit_node().role() == egui::accesskit::Role::Slider).count(); + assert_eq!((sliders("Saturation"), sliders("HSL Saturation")), (1, 1)); + let strip = oklch_slider(&h, "Saturation").accesskit_node().numeric_value().unwrap(); + let row = oklch_slider(&h, "HSL Saturation").accesskit_node().numeric_value().unwrap(); + assert_ne!(strip, row, "HSB and HSL saturation differ for this color"); +} + +/// A drag on L changes the lightness and keeps the hue and the saturation. +#[test] +fn a_drag_on_hsl_lightness_keeps_the_hue_and_saturation() { + let mut h = hsl_harness(app(json!("#ff8000"))); + let rail = oklch_slider(&h, "HSL Lightness").rect(); + let undo = undo_len(h.state()); + drag(&mut h, &[on_rail(rail, 0.5), on_rail(rail, 0.25)], Modifiers::NONE); + assert!(near(fill_hsl(h.state()), [30.0, 1.0, 0.25], [1.0, 0.01, 0.01]), "{:?}", fill_hsl(h.state())); + assert_eq!(undo_len(h.state()), undo + 1, "a drag is one undo step"); +} + +/// A press on S gives it the keyboard focus, and → raises it by 1 % as one undo step. Each row +/// reports its range and the adjust actions to screen readers. +#[test] +fn the_hsl_rows_take_the_arrow_keys_and_screen_readers_actions() { + let mut h = hsl_harness(app(json!("#996633"))); + for (name, max) in [("HSL Hue", 360.0), ("HSL Saturation", 100.0), ("HSL Lightness", 100.0)] { + let node = oklch_slider(&h, name).accesskit_node(); + assert_eq!((node.min_numeric_value(), node.max_numeric_value(), node.numeric_value_step()), (Some(0.0), Some(max), Some(1.0)), "{name}"); + assert!([Action::Increment, Action::Decrement, Action::SetValue].iter().all(|a| node.data().supports_action(*a)), "{name}"); + } + let rail = oklch_slider(&h, "HSL Saturation").rect(); + let s = fill_hsl(h.state())[1]; + click(&mut h, on_rail(rail, s), Modifiers::NONE); + let before = fill_hsl(h.state()); + let undo = undo_len(h.state()); + key(&mut h, egui::Key::ArrowRight, Modifiers::NONE); + let after = fill_hsl(h.state()); + let raised = ((before[1] * 100.0).round() + 1.0) / 100.0; + assert!(near(after, [before[0], raised, before[2]], [1.0, 0.008, 0.003]), "{before:?} → {after:?}"); + assert_eq!(undo_len(h.state()), undo + 1, "one undo step"); +} + +/// A gray has no hue: a hue given to it stays on the H row while the color is unchanged, and a +/// saturation picked next uses that hue. +#[test] +fn a_gray_keeps_the_hsl_hue_it_was_given() { + let mut h = hsl_harness(app(json!("#808080"))); + let (gray, undo) = (fill(h.state()), undo_len(h.state())); + set_slider_value(&mut h, "HSL Hue", 200.0); + assert_eq!(oklch_slider(&h, "HSL Hue").accesskit_node().numeric_value(), Some(200.0), "a gray keeps the hue it was given"); + assert_eq!((fill(h.state()), undo_len(h.state())), (gray, undo), "a hue on a gray changes nothing and records no undo step"); + set_slider_value(&mut h, "HSL Saturation", 60.0); + let got = fill_hsl(h.state()); + assert!(near(got, [200.0, 0.6, 0.5], [1.0, 0.01, 0.01]), "{got:?}"); +} + +/// In a working RGB space wider than sRGB, an HSL pick goes from display sRGB into that space +/// through the color settings: the fill displays the HSL asked for, and its stored RGB numbers are +/// those of the working space, not the sRGB numbers of that HSL. +#[test] +fn an_hsl_pick_in_display_p3_goes_into_the_working_space() { + const CHILD: &str = "VECTORCRAFT_TEST_COLOR_WHEEL_HSL_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::an_hsl_pick_in_display_p3_goes_into_the_working_space", "--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(json!("#996633")); + app.run("edit.colorSettings", json!({"rgb": cms::DISPLAY_P3})).unwrap(); + let mut h = hsl_harness(app); + let [hue, sat, _] = fill_hsl(h.state()); + let undo = undo_len(h.state()); + set_slider_value(&mut h, "HSL Lightness", 60.0); + let asked = [hue, sat, 0.6]; + assert!(near(fill_hsl(h.state()), asked, [0.5, 0.005, 0.005]), "{asked:?} → {:?}", fill_hsl(h.state())); + assert_eq!(undo_len(h.state()), undo + 1, "one undo step"); + let Color::Rgb { r, g, b } = fill(h.state()) else { panic!("an RGB fill stays RGB") }; + let srgb = vectorcraft_color::hsl_to_rgb(asked); + assert!((0..3).any(|i| ([r, g, b][i] - srgb[i]).abs() > 0.01), "{:?} is stored as the sRGB numbers {srgb:?}", [r, g, b]); +} + +/// Panel menu › HSL Sliders shows the H, S and L rows in place of OKLCH Sliders and, checked, +/// hides them; it is offered in any working RGB space. +#[test] +fn the_panel_menu_shows_and_hides_the_hsl_rows() { + let mut fonts = false; + let mut app = app(json!("#ff0000")); + app.run("ui.colorWheel", json!({"sliders": "oklch"})).unwrap(); + let mut h = Harness::builder().with_size(vec2(260.0, 200.0)).build_ui_state( + move |ui, app: &mut VectorcraftApp| { + // The fonts, which hold the check mark, take effect from the next frame. + if !fonts { + crate::theme::install_fonts(ui.ctx()); + fonts = true; + return; + } + super::color_wheel::menu(app, ui); + }, + app, + ); + h.run_steps(3); + h.get_by_label(" HSL Sliders").click(); + h.run_steps(2); + assert_eq!(h.state().ui.color_wheel.sliders, Sliders::Hsl); + assert!(h.query_by_label("✓ OKLCH Sliders").is_none(), "the two slider sets show one at a time"); + h.get_by_label("✓ HSL Sliders").click(); + h.run_steps(2); + assert_eq!(h.state().ui.color_wheel.sliders, Sliders::None); + let p3 = Cms::new(&ColorSettings { rgb: cms::DISPLAY_P3.into(), ..ColorSettings::default() }).unwrap(); + let mut settings = Settings::default(); + set(&mut settings, &json!({"sliders": "hsl"}), &p3).unwrap(); + assert_eq!(settings.sliders, Sliders::Hsl, "HSL needs no particular working space"); +} + +/// The rows show what they asked for while the color displays as it did, and the color's own HSL +/// after the color settings change its display. +#[test] +fn the_remembered_hsl_follows_a_change_of_working_space() { + let srgb = Cms::default(); + let p3 = Cms::new(&ColorSettings { rgb: cms::DISPLAY_P3.into(), ..ColorSettings::default() }).unwrap(); + let c = Color::rgb(0.5, 0.3, 0.2); + let asked = [20.0, 0.43, 0.35]; + let shown = srgb.display_rgb(&c); + assert_eq!(remembered_hsl(&srgb, &c, shown, asked), asked); + assert_eq!(remembered_hsl(&p3, &c, shown, asked), vectorcraft_color::rgb_to_hsl(p3.display_rgb(&c))); +} + +/// Saved settings are read key by key: a value this version does not know (one a newer version +/// wrote) gives the default, and the other preferences still load. +#[test] +fn saved_color_wheel_settings_are_read_leniently() { + let mut saved = serde_json::to_value(crate::UiState::default()).unwrap(); + saved["color_rgb_percent"] = json!(true); + for (value, sliders) in [ + (json!({"sliders": "oklch"}), Sliders::Oklch), + (json!({"sliders": "hsl"}), Sliders::Hsl), + (json!({"sliders": "hwb", "view": "box"}), Sliders::None), + (json!(5), Sliders::None), + ] { + saved["color_wheel"] = value.clone(); + let ui: crate::UiState = serde_json::from_value(saved.clone()).unwrap(); + assert_eq!((ui.color_wheel.sliders, ui.color_rgb_percent), (sliders, true), "{value}"); + } +} + +/// `ui.colorWheel {sliders}` sets the rows and keeps the view and the channel, and an unknown +/// `sliders` value is an error that changes nothing. +#[test] +fn ui_color_wheel_sets_and_reads_the_sliders() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("ui.colorWheel", json!({"view": "box", "channel": "red"})).unwrap(); + assert_eq!(app.run("ui.colorWheel", json!({})).unwrap()["sliders"], json!("none")); + assert_eq!(app.run("ui.colorWheel", json!({"sliders": "hwb"})).unwrap_err(), "`sliders` must be none, oklch or hsl"); + let got = app.run("ui.colorWheel", json!({"sliders": "oklch"})).unwrap(); + let want = json!({"view": "box", "channel": "red", "gamut": false, "harmony": false, "harmonyRule": "complementary", "vision": false, "sliders": "oklch", "documentColors": false}); + assert_eq!(got, want); + let e = app.run("ui.colorWheel", json!({"view": "wheel", "sliders": "hwb"})).unwrap_err(); + assert_eq!(e, "`sliders` must be none, oklch or hsl"); + assert_eq!(app.ui.color_wheel.view, crate::panels::color_wheel::View::Box, "an error changes nothing"); +} + +/// A hue given to a Gray color does not change how it displays, so its paint stays a Gray color +/// and no undo step is recorded; the hue row keeps the hue. +#[test] +fn a_hue_on_a_gray_color_leaves_its_paint_gray() { + for (rows, hue) in [("hsl", "HSL Hue"), ("oklch", "Hue")] { + let mut app = app(json!({"gray": 0.5})); + app.run("ui.colorWheel", json!({"sliders": rows})).unwrap(); + let mut h = oklch_harness_shown(app); + let (gray, undo) = (fill(h.state()), undo_len(h.state())); + assert!(matches!(gray, Color::Gray { .. }), "{gray:?}"); + set_slider_value(&mut h, hue, 200.0); + assert_eq!(oklch_slider(&h, hue).accesskit_node().numeric_value(), Some(200.0), "{rows}"); + assert_eq!((fill(h.state()), undo_len(h.state())), (gray, undo), "{rows}: the Gray fill stays as it was"); + } +} + +/// For a fill outside sRGB, the HSL and OKLCH rows show the components of its display color +/// clipped to sRGB, the color the panel shows, not of the unclipped one. +#[test] +fn the_rows_show_a_color_outside_srgb_clipped_to_srgb() { + let rgb = json!([1.6, 0.2, -0.4]); + let raw = cms::active().display_rgb(&fill(&app(rgb.clone()))); + let clipped = raw.map(|v| v.clamp(0.0, 1.0)); + assert_ne!(raw, clipped, "the fill lies outside sRGB"); + let want_hsl = (f64::from(vectorcraft_color::rgb_to_hsl(clipped)[2]) * 100.0).round(); + assert_ne!(want_hsl, (f64::from(vectorcraft_color::rgb_to_hsl(raw)[2]) * 100.0).round(), "the unclipped lightness differs"); + let h = hsl_harness(app(rgb.clone())); + assert_eq!(oklch_slider(&h, "HSL Lightness").accesskit_node().numeric_value(), Some(want_hsl)); + let want_l = (vectorcraft_color::oklab::to_oklch(clipped)[0] * 100.0).round(); + assert_ne!(want_l, (vectorcraft_color::oklab::to_oklch(raw)[0] * 100.0).round(), "the unclipped OKLCH lightness differs"); + let h = oklch_harness(app(rgb)); + assert_eq!(oklch_slider(&h, "Lightness").accesskit_node().numeric_value(), Some(want_l)); +} + +/// The hue given to a gray is dropped once the panel shows another color, so the same gray applied +/// again later shows its own hue, 0°. +#[test] +fn a_remembered_hue_is_dropped_after_the_paint_changes() { + for (rows, hue) in [("hsl", "HSL Hue"), ("oklch", "Hue")] { + let mut app = app(json!("#808080")); + app.run("ui.colorWheel", json!({"sliders": rows})).unwrap(); + let mut h = oklch_harness_shown(app); + set_slider_value(&mut h, hue, 240.0); + assert_eq!(oklch_slider(&h, hue).accesskit_node().numeric_value(), Some(240.0), "{rows}"); + h.state_mut().run("paint.setFill", json!({"color": "#ff0000"})).unwrap(); + h.run_steps(2); + h.state_mut().run("paint.setFill", json!({"color": "#808080"})).unwrap(); + h.run_steps(2); + assert_eq!(oklch_slider(&h, hue).accesskit_node().numeric_value(), Some(0.0), "{rows}: the gray's own hue"); + } +} + +/// Hiding the rows, or showing the other rows, during a drag on a row keeps the color the drag +/// previewed as one undo step and leaves no interaction open. +#[test] +fn hiding_the_rows_during_a_drag_keeps_its_color_as_one_undo_step() { + for rows in ["none", "oklch"] { + let mut h = hsl_harness(app(json!("#ff8000"))); + let rail = oklch_slider(&h, "HSL Lightness").rect(); + let undo = undo_len(h.state()); + press(&mut h, on_rail(rail, 0.5), true, Modifiers::NONE); + for _ in 0..2 { + h.event(Event::PointerMoved(on_rail(rail, 0.25))); + h.run_steps(1); + } + assert!(h.state().session.in_interaction(), "{rows}: the drag previews"); + let previewed = fill(h.state()); + h.state_mut().run("ui.colorWheel", json!({"sliders": rows})).unwrap(); + h.run_steps(2); + press(&mut h, on_rail(rail, 0.25), false, Modifiers::NONE); + assert!(!h.state().session.in_interaction(), "{rows}: the interaction ended"); + assert_eq!((fill(h.state()), undo_len(h.state())), (previewed, undo + 1), "{rows}"); + } +} diff --git a/crates/ui-egui/src/panels/tests_color_wheel_box.rs b/crates/ui-egui/src/panels/tests_color_wheel_box.rs index 3b55f52ac2..c14bef3c77 100644 --- a/crates/ui-egui/src/panels/tests_color_wheel_box.rs +++ b/crates/ui-egui/src/panels/tests_color_wheel_box.rs @@ -167,7 +167,8 @@ fn the_strip_takes_the_arrow_keys_and_screen_readers_actions() { #[test] fn ui_color_wheel_sets_and_reads_the_view_and_the_channel() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); - let harmony = json!({"harmony": false, "harmonyRule": "complementary", "vision": false}); + let harmony = + json!({"sliders": "none", "gamut": false, "harmony": false, "harmonyRule": "complementary", "vision": false, "documentColors": false}); let with = |v: serde_json::Value| { let mut v = v; v.as_object_mut().unwrap().extend(harmony.as_object().unwrap().clone()); @@ -217,9 +218,9 @@ fn ui_color_wheel_rejects_other_params() { let e = app.run("ui.colorWheel", json!([1])).unwrap_err(); assert_eq!(e, "the params must be an object, not [1]"); let e = app.run("ui.colorWheel", json!({"veiw": "wheel"})).unwrap_err(); - assert_eq!(e, "unknown parameter `veiw`; the command takes: view, channel, harmony, harmonyRule, vision"); + assert_eq!(e, "unknown parameter `veiw`; the command takes: view, channel, sliders, gamut, harmony, harmonyRule, vision, documentColors"); let e = app.run("ui.colorWheel", json!({"view": "wheel", "chanel": "blue"})).unwrap_err(); - assert_eq!(e, "unknown parameter `chanel`; the command takes: view, channel, harmony, harmonyRule, vision"); + assert_eq!(e, "unknown parameter `chanel`; the command takes: view, channel, sliders, gamut, harmony, harmonyRule, vision, documentColors"); assert_eq!(app.ui.color_wheel, Settings { view: View::Box, channel: Channel::Red, ..Default::default() }, "an error changes nothing"); } @@ -277,7 +278,7 @@ fn ui_color_wheel_answers_junk_params_without_a_panic() { #[test] fn the_settings_are_kept_and_read_leniently() { let ui = crate::UiState { - color_wheel: Settings { view: View::Box, channel: Channel::Blue, vision: true, ..Default::default() }, + color_wheel: Settings { view: View::Box, channel: Channel::Blue, gamut: true, vision: true, ..Default::default() }, color_rgb_percent: true, ..Default::default() }; diff --git a/crates/ui-egui/src/panels/tests_color_wheel_document_colors.rs b/crates/ui-egui/src/panels/tests_color_wheel_document_colors.rs new file mode 100644 index 0000000000..6d63af1df9 --- /dev/null +++ b/crates/ui-egui/src/panels/tests_color_wheel_document_colors.rs @@ -0,0 +1,410 @@ +//! The Color Wheel panel's Show Document Colors row drawn headless: its colors and their order, +//! the heading that follows the selection, the colors that fit in one row, a click and an Alt+click +//! on a color, swatch links, gradient stops and freeform points, the colors kept during a drag, the panel menu, +//! `ui.colorWheel {documentColors}` and the saved setting. + +use egui::{Event, Modifiers, PointerButton, Pos2, vec2}; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::{Value, json}; +use vectorcraft_color::Paint; +use vectorcraft_engine::Session; + +use super::color_wheel::show; +use crate::VectorcraftApp; + +/// A rectangle filled with `fill` (any paint `paint.setFill` takes), without a stroke, which +/// becomes the selection. → its id. +fn rect(app: &mut VectorcraftApp, x: f64, fill: Value) -> Value { + let id = app.run("shape.rectangle", json!({"x": x, "y": 10, "width": 30, "height": 30})).unwrap()["id"].clone(); + app.run("paint.setFill", fill).unwrap(); + app.run("paint.setStroke", json!({"none": true, "focus": false})).unwrap(); + id +} + +/// A document with three red rectangles and one blue one (selected), with Show Document Colors on. +/// → the app, the ids of the red rectangles and the id of the blue one. +fn app() -> (VectorcraftApp, Vec, Value) { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + let reds = (0..3).map(|i| rect(&mut app, 10.0 + 40.0 * i as f64, json!({"color": "#ff0000"}))).collect(); + let blue = rect(&mut app, 130.0, json!({"color": "#0000ff"})); + app.run("ui.colorWheel", json!({"documentColors": true})).unwrap(); + (app, reds, blue) +} + +fn harness(app: VectorcraftApp) -> Harness<'static, VectorcraftApp> { + let mut h = Harness::builder().with_size(vec2(260.0, 360.0)).build_ui_state(|ui, app: &mut VectorcraftApp| show(app, ui), app); + h.run_steps(2); + h +} + +fn label(hex: &str, n: u64) -> String { + format!("{hex}\n{}", if n == 1 { "Used 1 time".to_string() } else { format!("Used {n} times") }) +} + +fn has(h: &Harness<'static, VectorcraftApp>, label: &str) -> bool { + h.query_by_label(label).is_some() +} + +fn press(h: &mut Harness<'static, VectorcraftApp>, pos: Pos2, pressed: bool, modifiers: Modifiers) { + h.event(Event::ModifiersChanged(modifiers)); + h.event(Event::PointerMoved(pos)); + h.event(Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers }); + h.run_steps(1); +} + +fn click(h: &mut Harness<'static, VectorcraftApp>, pos: Pos2, modifiers: Modifiers) { + press(h, pos, true, modifiers); + press(h, pos, false, modifiers); + h.event(Event::ModifiersChanged(Modifiers::NONE)); + h.run_steps(1); +} + +/// The hex value of the one color object `id` uses (its fill: it has no stroke). +fn fill_of(app: &mut VectorcraftApp, id: &Value) -> String { + let r = app.session.execute("recolor.colors", &json!({"ids": [id]})).unwrap(); + assert_eq!(r["colors"].as_array().map(Vec::len), Some(1), "{r}"); + r["colors"][0]["hex"].as_str().unwrap().to_string() +} + +/// With nothing selected, the row is headed Document Colors and lists the art's colors, the red +/// that three rectangles use before the blue that one uses. +#[test] +fn show_document_colors_lists_the_art_colors_most_used_first() { + let (mut app, _, _) = app(); + app.run("select.none", json!({})).unwrap(); + let h = harness(app); + assert!(has(&h, "Document Colors")); + let red = h.get_by_label(&label("#ff0000", 3)).rect(); + let blue = h.get_by_label(&label("#0000ff", 1)).rect(); + assert!(red.left() < blue.left(), "red {red:?} comes before blue {blue:?}"); +} + +/// With something selected the row is headed Selection Colors and lists the selection's colors. +#[test] +fn the_heading_and_the_colors_follow_the_selection() { + let (app, _, _) = app(); + let mut h = harness(app); + assert!(has(&h, "Selection Colors")); + assert!(has(&h, &label("#0000ff", 1))); + assert!(!has(&h, &label("#ff0000", 3))); + h.state_mut().run("select.none", json!({})).unwrap(); + h.run_steps(2); + assert!(has(&h, "Document Colors") && !has(&h, "Selection Colors")); + assert!(has(&h, &label("#ff0000", 3))); +} + +/// The row shows the most used colors that fit in one row and leaves out the rest. +#[test] +fn the_row_shows_only_the_colors_that_fit() { + let (mut app, _, _) = app(); + for i in 0..30 { + rect(&mut app, 170.0 + i as f64, json!({"color": format!("#00{:02x}00", 40 + 6 * i)})); + } + app.run("select.none", json!({})).unwrap(); + let h = harness(app); + let red = h.get_by_label(&label("#ff0000", 3)).rect(); + let shown: Vec<_> = (0..30).filter_map(|i| h.query_by_label(&label(&format!("#00{:02x}00", 40 + 6 * i), 1)).map(|n| n.rect())).collect(); + assert!(!shown.is_empty() && shown.len() < 30, "{} of the 30 greens show", shown.len()); + assert!(shown.iter().all(|r| (r.top() - red.top()).abs() < 0.5 && r.right() <= 260.0), "one row inside the panel: {shown:?}"); +} + +/// A row wide enough for more than 128 chips shows as many colors as fit. +#[test] +fn a_wide_row_shows_more_than_128_colors() { + let (mut app, _, _) = app(); + let hex = |i: usize| format!("#{:02x}{:02x}80", i % 256, i / 256 + 1); + for i in 0..160 { + rect(&mut app, 170.0, json!({"color": hex(i)})); + } + app.run("select.none", json!({})).unwrap(); + let mut h = Harness::builder().with_size(vec2(3400.0, 360.0)).build_ui_state(|ui, app: &mut VectorcraftApp| show(app, ui), app); + h.run_steps(2); + let shown = (0..160).filter(|i| has(&h, &label(&hex(*i), 1))).count(); + assert!(shown > 128, "{shown} of the 160 colors show"); +} + +/// A click on a color fills the selection with it, as one undo step. +#[test] +fn a_click_on_a_color_sets_the_fill() { + let (mut app, reds, blue) = app(); + app.run("select.set", json!({"ids": [reds[0], blue]})).unwrap(); + let undo = app.session.doc().unwrap().history.undo.len(); + let mut h = harness(app); + let at = h.get_by_label(&label("#0000ff", 1)).rect().center(); + click(&mut h, at, Modifiers::NONE); + let app = h.state_mut(); + assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1); + assert_eq!(fill_of(app, &reds[0]), "#0000ff"); + assert_eq!(fill_of(app, &blue), "#0000ff"); + assert_eq!(fill_of(app, &reds[1]), "#ff0000"); +} + +/// Alt+click applies the color to the inactive proxy (the stroke) and leaves the fill in front. +#[test] +fn alt_click_on_a_color_sets_the_stroke() { + let (mut app, reds, blue) = app(); + app.run("select.set", json!({"ids": [reds[0], blue]})).unwrap(); + let mut h = harness(app); + let at = h.get_by_label(&label("#ff0000", 1)).rect().center(); + click(&mut h, at, Modifiers::ALT); + let app = h.state_mut(); + assert!(app.session.fill_active, "the fill stays in front"); + let st = app.session.doc().unwrap(); + let paints = |id: &Value| { + let n = st.doc.node(vectorcraft_doc::NodeId(id.as_u64().unwrap())).unwrap(); + (n.appearance.fill_paint().color().map(|c| c.to_hex()), n.appearance.stroke_paint().color().map(|c| c.to_hex())) + }; + assert_eq!(paints(&blue), (Some("#0000ff".into()), Some("#ff0000".into()))); +} + +/// A color linked to a spot swatch stays linked at its tint when a click applies it. +#[test] +fn a_click_keeps_a_swatch_link_and_its_tint() { + let (mut app, _, blue) = app(); + app.run("swatch.new", json!({"name": "Ink", "color": {"c": 0, "m": 100, "y": 60, "k": 0}, "spot": true})).unwrap(); + let ink = rect(&mut app, 170.0, json!({"swatch": "Ink", "tint": 40})); + app.run("select.set", json!({"ids": [ink, blue]})).unwrap(); + let hex = app.session.execute("color.used", &json!({})).unwrap()["colors"] + .as_array() + .unwrap() + .iter() + .find(|c| c["swatch"] == "Ink") + .expect("the tint is listed")["hex"] + .as_str() + .unwrap() + .to_string(); + let mut h = harness(app); + let at = h.get_by_label(&label(&hex, 1)).rect().center(); + click(&mut h, at, Modifiers::NONE); + let st = h.state().session.doc().unwrap(); + let fill = st.doc.node(vectorcraft_doc::NodeId(blue.as_u64().unwrap())).unwrap().appearance.fill_paint().clone(); + let Paint::Solid { swatch, tint, .. } = fill else { panic!("a solid fill, not {fill:?}") }; + assert_eq!(swatch.as_deref(), Some("Ink")); + assert!((tint - 0.4).abs() < 1e-3, "tint {tint}"); +} + +/// A click recolors the selected gradient stop, linking it to a color's swatch at its tint. +#[test] +fn a_click_recolors_the_selected_gradient_stop() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + app.run("swatch.new", json!({"name": "Ink", "color": {"c": 0, "m": 100, "y": 60, "k": 0}, "spot": true})).unwrap(); + let stops = json!([{"offset": 0, "color": "#000000", "swatch": "Ink", "tint": 40}, {"offset": 1, "color": "#0000ff"}]); + rect(&mut app, 10.0, json!({"gradient": {"stops": stops, "start": [10, 25], "end": [40, 25]}})); + app.select_tool("gradient"); + app.run("gradient.selectStop", json!({"index": 1})).unwrap(); + app.run("ui.colorWheel", json!({"documentColors": true})).unwrap(); + let hex = app.session.execute("color.used", &json!({})).unwrap()["colors"] + .as_array() + .unwrap() + .iter() + .find(|c| c["swatch"] == "Ink") + .expect("the stop's color is listed")["hex"] + .as_str() + .unwrap() + .to_string(); + let mut h = harness(app); + let at = h.get_by_label(&label(&hex, 1)).rect().center(); + click(&mut h, at, Modifiers::NONE); + let Paint::Gradient(g) = crate::panels::current_paints(h.state()).0 else { panic!("still a gradient") }; + let stop = &g.gradient.stops[1]; + assert_eq!((stop.color.to_hex(), stop.swatch.as_deref()), (hex, Some("Ink"))); + assert!((stop.tint - 0.4).abs() < 1e-3, "tint {}", stop.tint); +} + +/// A click on a color linked to a swatch gives a selected freeform point the color alone and keeps +/// the freeform fill. +#[test] +fn a_click_gives_a_freeform_point_the_color_alone() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + app.run("swatch.new", json!({"name": "Ink", "color": {"c": 0, "m": 100, "y": 60, "k": 0}, "spot": true})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 100, "height": 100})).unwrap(); + app.run("paint.editGradient", json!({"kind": "freeform"})).unwrap(); + app.run("paint.setStroke", json!({"swatch": "Ink", "tint": 40, "focus": false})).unwrap(); + app.select_tool("gradient"); + app.run("paint.freeform.selectPoint", json!({"index": 1})).unwrap(); + app.run("ui.colorWheel", json!({"documentColors": true})).unwrap(); + let hex = app.session.execute("color.used", &json!({})).unwrap()["colors"] + .as_array() + .unwrap() + .iter() + .find(|c| c["swatch"] == "Ink") + .expect("the stroke's color is listed")["hex"] + .as_str() + .unwrap() + .to_string(); + let mut h = harness(app); + let at = h.get_by_label(&label(&hex, 1)).rect().center(); + click(&mut h, at, Modifiers::NONE); + let Paint::Gradient(g) = crate::panels::current_paints(h.state()).0 else { panic!("still a gradient") }; + let points = g.freeform.expect("still freeform").points; + assert_eq!(points[1].color.to_hex(), hex); +} + +/// While a drag on the wheel recolors the selection, the row keeps the colors from before the +/// drag; once it ends, it lists the new color. +#[test] +fn a_drag_on_the_wheel_does_not_read_the_colors_again_until_it_ends() { + let (app, _, blue) = app(); + let revision = app.session.active().unwrap().revision; + let mut h = harness(app); + let ring = h.get_by_label("Hue ring").rect(); + // The left of the ring (cyan), then its bottom, in the middle of the band. + let r = ring.width() / 2.0 - 11.0; + let (a, b) = (ring.center() - vec2(r, 0.0), ring.center() + vec2(0.0, r)); + press(&mut h, a, true, Modifiers::NONE); + for p in [a, b, b] { + h.event(Event::PointerMoved(p)); + h.run_steps(1); + } + assert!(h.state().session.in_interaction(), "the drag is in progress"); + assert_ne!(h.state().session.active().unwrap().revision, revision, "the drag changed the document"); + assert!(has(&h, &label("#0000ff", 1)), "the row keeps the colors from before the drag"); + press(&mut h, b, false, Modifiers::NONE); + h.run_steps(2); + let now = fill_of(h.state_mut(), &blue); + assert_ne!(now, "#0000ff"); + assert!(!has(&h, &label("#0000ff", 1))); + assert!(has(&h, &label(&now, 1)), "the row lists {now} after the drag"); +} + +/// In art with more than 5,000 color uses, the row reads the colors again after an edit at most +/// once every half second of frames, and a change of selection reads them at once. +#[test] +fn in_large_art_an_edit_reads_the_colors_again_after_half_a_second() { + let (mut app, reds, _) = app(); + app.run("select.set", json!({"ids": [reds[0]]})).unwrap(); + for _ in 0..11 { + app.run("select.all", json!({})).unwrap(); + app.run("edit.duplicate", json!({})).unwrap(); + } + app.run("select.none", json!({})).unwrap(); + let uses = app.session.execute("color.used", &json!({})).unwrap()["uses"].as_u64().unwrap(); + assert!(uses > 5_000, "{uses} uses"); + let reds_used = app.session.execute("color.used", &json!({})).unwrap()["colors"][0]["count"].as_u64().unwrap(); + let mut h = Harness::builder().with_size(vec2(260.0, 360.0)).with_step_dt(0.1).build_ui_state(|ui, app: &mut VectorcraftApp| show(app, ui), app); + h.run_steps(6); + assert!(has(&h, &label("#ff0000", reds_used))); + // Half a second after the last read, an edit is read at once. + h.state_mut().run("paint.setFill", json!({"ids": [reds[0]], "color": "#00ff00"})).unwrap(); + h.run_steps(1); + assert!(has(&h, &label("#ff0000", reds_used - 1)) && has(&h, &label("#00ff00", 1)), "the first edit is read at once"); + // The next edit within half a second waits. + h.state_mut().run("paint.setFill", json!({"ids": [reds[1]], "color": "#00ff00"})).unwrap(); + h.run_steps(1); + assert!(has(&h, &label("#00ff00", 1)), "the row waits after the second edit"); + h.run_steps(5); + assert!(has(&h, &label("#ff0000", reds_used - 2)) && has(&h, &label("#00ff00", 2)), "the row reads the colors again"); + h.state_mut().run("paint.setFill", json!({"ids": [reds[2]], "color": "#00ff00"})).unwrap(); + h.state_mut().run("select.set", json!({"ids": [reds[2]]})).unwrap(); + h.run_steps(1); + assert!(has(&h, "Selection Colors") && has(&h, &label("#00ff00", 1)), "a new selection reads the colors at once"); + assert!(!has(&h, &label("#00ff00", 3))); +} + +/// A row widened past the 128 colors last read keeps them while an interaction is in progress, and +/// in art with more than 5,000 color uses until half a second after the last read. +#[test] +fn a_widened_row_waits_for_the_interaction_and_the_half_second() { + let (mut app, reds, _) = app(); + let hex = |i: usize| format!("#{:02x}{:02x}80", i % 256, i / 256 + 1); + for i in 0..160 { + rect(&mut app, 170.0, json!({"color": hex(i)})); + } + for _ in 0..5 { + app.run("select.all", json!({})).unwrap(); + app.run("edit.duplicate", json!({})).unwrap(); + } + app.run("select.none", json!({})).unwrap(); + let uses = app.session.execute("color.used", &json!({})).unwrap()["uses"].as_u64().unwrap(); + assert!(uses > 5_000, "{uses} uses"); + let (narrow, wide) = (vec2(260.0, 360.0), vec2(3400.0, 360.0)); + let mut h = Harness::builder().with_size(narrow).with_step_dt(0.1).build_ui_state(|ui, app: &mut VectorcraftApp| show(app, ui), app); + h.run_steps(6); + let shown = |h: &Harness<'static, VectorcraftApp>| (0..160).filter(|i| has(h, &label(&hex(*i), 32))).count(); + // During an interaction the wide row keeps the 128 colors read for the narrow one. + h.state_mut().session.begin_interaction("test").unwrap(); + h.set_size(wide); + h.run_steps(6); + assert!(shown(&h) <= 128, "{} colors show during the interaction", shown(&h)); + h.state_mut().session.cancel_interaction().unwrap(); + h.run_steps(6); + assert!(shown(&h) > 128, "{} colors show after the interaction", shown(&h)); + // An edit read in the narrow row, then a wide row within half a second, waits for the half second. + h.set_size(narrow); + h.run_steps(1); + h.state_mut().run("paint.setFill", json!({"ids": [reds[0]], "color": "#00ff00"})).unwrap(); + h.run_steps(1); + assert!(has(&h, &label("#ff0000", 95)), "the edit is read at once"); + h.set_size(wide); + h.run_steps(1); + assert!(shown(&h) <= 128, "{} colors show within half a second", shown(&h)); + h.run_steps(5); + assert!(shown(&h) > 128, "{} colors show after half a second", shown(&h)); +} + +/// Without the setting the row is not drawn, and the panel menu's Show Document Colors turns it on. +#[test] +fn the_panel_menu_turns_the_row_on_and_off() { + let off = || { + let (mut a, _, _) = app(); + a.run("ui.colorWheel", json!({"documentColors": false})).unwrap(); + a + }; + let mut h = harness(off()); + assert!(!has(&h, "Selection Colors")); + // The menu in a context of its own, as the other panel menu tests draw it. + let mut app = off(); + let ctx = egui::Context::default(); + let raw = |events| egui::RawInput { events, screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(240.0, 320.0))), ..Default::default() }; + let click_item = |app: &mut VectorcraftApp| { + let mut out = ctx.run_ui(raw(vec![]), |ui| super::color_wheel::menu(app, ui)); + out.textures_delta.clear(); + let item = out + .shapes + .iter() + .find_map(|c| match &c.shape { + egui::Shape::Text(t) if t.galley.text().ends_with("Show Document Colors") => Some(t.visual_bounding_rect().center()), + _ => None, + }) + .expect("the menu shows Show Document Colors"); + let button = |pressed| Event::PointerButton { pos: item, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }; + ctx.run_ui(raw(vec![Event::PointerMoved(item), button(true), button(false)]), |ui| super::color_wheel::menu(app, ui)).textures_delta.clear(); + }; + click_item(&mut app); + assert!(app.ui.color_wheel.document_colors); + click_item(&mut app); + assert!(!app.ui.color_wheel.document_colors); + h.state_mut().run("ui.colorWheel", json!({"documentColors": true})).unwrap(); + h.run_steps(2); + assert!(has(&h, "Selection Colors")); +} + +/// `ui.colorWheel {documentColors}` sets the row's setting, keeps the others, and refuses a value +/// that is not a bool, changing nothing. +#[test] +fn ui_color_wheel_sets_document_colors() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + assert_eq!(app.run("ui.colorWheel", json!({})).unwrap()["documentColors"], json!(false)); + app.run("ui.colorWheel", json!({"view": "box"})).unwrap(); + let r = app.run("ui.colorWheel", json!({"documentColors": true})).unwrap(); + assert_eq!((r["documentColors"].clone(), r["view"].clone()), (json!(true), json!("box"))); + assert_eq!(app.run("ui.colorWheel", json!({"documentColors": "no"})).unwrap_err(), "`documentColors` must be true or false"); + assert!(app.ui.color_wheel.document_colors); + assert_eq!(app.run("ui.colorWheel", json!({"documentColors": null})).unwrap()["documentColors"], json!(true)); +} + +/// The saved setting reads leniently: a value this build does not know reads as off, and the other +/// settings and preferences are kept. +#[test] +fn the_saved_setting_reads_leniently() { + let read = |v: Value| serde_json::from_value::(v).expect("the preferences read"); + let s = read(json!({"color_wheel": {"documentColors": true, "view": "box"}, "color_rgb_percent": true})); + assert!(s.color_wheel.document_colors && s.color_rgb_percent); + let s = read(json!({"color_wheel": {"documentColors": "yes", "view": "box"}, "color_rgb_percent": true})); + assert!(!s.color_wheel.document_colors && s.color_rgb_percent); + assert_eq!(s.color_wheel.view, super::color_wheel::View::Box); +} diff --git a/crates/ui-egui/src/panels/tests_color_wheel_gamut.rs b/crates/ui-egui/src/panels/tests_color_wheel_gamut.rs new file mode 100644 index 0000000000..da47fa684e --- /dev/null +++ b/crates/ui-egui/src/panels/tests_color_wheel_gamut.rs @@ -0,0 +1,265 @@ +//! The Color Wheel panel's Show Out-of-Gamut Colors: the grid of out-of-gamut cells, its cache, the +//! wheel's square and the box sharing it, `ui.colorWheel {gamut}`, the panel menu and the saved +//! setting. + +use egui::vec2; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::json; +use vectorcraft_color::cms::{self, Cms, ColorSettings}; +use vectorcraft_color::{Color, hsb_to_rgb}; +use vectorcraft_engine::Session; + +use super::color_wheel::{GAMUT, GAMUT_CELLS, GamutGrid, GamutKey, Settings, View, box_pick, cached_grid, gamut_grid, show}; +use crate::VectorcraftApp; +use crate::dialogs::color_picker::Channel; + +/// Whether cell `col` of row `row` (from the top-left) of `grid` is out of gamut. +fn marked(grid: &GamutGrid, col: usize, row: usize) -> bool { + (grid[row] >> col) & 1 == 1 +} + +/// An app with a selected rectangle filled with `fill`, its Color Wheel panel on `view` with Show +/// Out-of-Gamut Colors set to `gamut`. +fn app(fill: &str, view: &str, gamut: bool) -> 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": fill})).unwrap(); + app.run("ui.colorWheel", json!({"view": view, "channel": "hue", "gamut": gamut})).unwrap(); + app +} + +fn harness(app: VectorcraftApp) -> Harness<'static, VectorcraftApp> { + let mut h = Harness::builder().with_size(vec2(260.0, 320.0)).build_ui_state(|ui, app: &mut VectorcraftApp| show(app, ui), app); + h.run_steps(2); + h +} + +/// The grid the panel drew last, with its key. +fn drawn(h: &Harness<'static, VectorcraftApp>) -> Option<(GamutKey, GamutGrid)> { + super::pstate::>(&h.ctx, GAMUT) +} + +/// At hue 240° the field's top-right cell is nearly pure blue, which the CMYK space cannot print, +/// and its bottom-left cell is nearly black, which it can. Each cell is the color a pick at its +/// center stores, tested as the out-of-gamut warning tests it. +#[test] +fn the_hue_grid_marks_blue_and_leaves_black() { + let cms = Cms::default(); + let grid = gamut_grid(&cms, Channel::Hue, 240.0 / 360.0); + let last = GAMUT_CELLS - 1; + assert!(marked(&grid, last, 0), "{grid:04x?}"); + assert!(!marked(&grid, 0, last), "{grid:04x?}"); + for row in 0..GAMUT_CELLS { + for col in 0..GAMUT_CELLS { + let n = GAMUT_CELLS as f32; + let hsb = box_pick(Channel::Hue, 240.0 / 360.0, (col as f32 + 0.5) / n, (row as f32 + 0.5) / n, [0.0; 3]); + let [r, g, b] = cms.srgb_to_rgb(hsb_to_rgb(hsb)); + assert_eq!(marked(&grid, col, row), cms.out_of_gamut(&Color::rgb(r, g, b)), "cell {col}, {row}"); + } + } +} + +/// In the Blue box at full blue, the field's bottom-left cell (no red, no green) is nearly pure +/// blue. +#[test] +fn an_rgb_box_marks_its_own_cells() { + let grid = gamut_grid(&Cms::default(), Channel::Blue, 1.0); + assert!(marked(&grid, 0, GAMUT_CELLS - 1), "{grid:04x?}"); +} + +/// With uncalibrated CMYK as the CMYK space every color counts as printable, as the out-of-gamut +/// warning has it, so no cell is marked. +#[test] +fn uncalibrated_cmyk_marks_nothing() { + let cms = Cms::new(&ColorSettings { cmyk: cms::DEVICE_CMYK.into(), ..ColorSettings::default() }).unwrap(); + assert_eq!(gamut_grid(&cms, Channel::Hue, 240.0 / 360.0), [0; GAMUT_CELLS]); +} + +/// The cache computes a grid once per key: the same channel, value, color settings and profile +/// generation reuse it, and a change of any of them computes it again. +#[test] +fn the_cache_computes_once_per_key() { + let mut slot = None; + let mut runs = 0; + let settings = ColorSettings::default(); + let mut get = |slot: &mut Option<(GamutKey, GamutGrid)>, key: GamutKey| { + cached_grid(slot, key, || { + runs += 1; + [runs; GAMUT_CELLS] + }) + }; + let key = (Channel::Hue, 0.5f32.to_bits(), settings.clone(), 0); + assert_eq!(get(&mut slot, key.clone()), [1; GAMUT_CELLS]); + assert_eq!(get(&mut slot, key.clone()), [1; GAMUT_CELLS], "the same key is not computed again"); + assert_eq!(get(&mut slot, (Channel::Hue, 0.25f32.to_bits(), settings.clone(), 0)), [2; GAMUT_CELLS]); + assert_eq!(get(&mut slot, (Channel::Red, 0.25f32.to_bits(), settings.clone(), 0)), [3; GAMUT_CELLS]); + let device = ColorSettings { cmyk: cms::DEVICE_CMYK.into(), ..settings }; + assert_eq!(get(&mut slot, (Channel::Red, 0.25f32.to_bits(), device.clone(), 0)), [4; GAMUT_CELLS]); + assert_eq!(get(&mut slot, (Channel::Red, 0.25f32.to_bits(), device, 1)), [5; GAMUT_CELLS], "a profile loaded again"); +} + +/// A profile loaded again under the same name can change which colors are printable while the +/// color settings stay the same, so the panel tests the colors again after a profile is +/// registered. +#[test] +fn the_grid_is_computed_again_after_a_profile_is_loaded() { + let mut h = harness(app("#3366cc", "box", true)); + let Some((before, _)) = drawn(&h) else { panic!("the box drew no grid") }; + /// Unregisters the profile when dropped, also after a failed assertion. + struct Unregister(&'static str); + impl Drop for Unregister { + fn drop(&mut self) { + cms::unregister_icc(self.0); + } + } + let name = "Color Wheel Gamut Reload CMYK"; + let bytes = cms::icc_bytes(cms::GENERIC_CMYK).unwrap(); + cms::register_icc(&bytes, Some(name.into())).unwrap(); + let _unregister = Unregister(name); + h.run_steps(2); + let Some((after, _)) = drawn(&h) else { panic!("the box drew no grid") }; + assert_eq!((after.0, after.1, &after.2), (before.0, before.1, &before.2)); + assert!(after.3 > before.3, "the key follows the loaded profiles: {} then {}", before.3, after.3); +} + +/// The wheel's square is the hue box at the ring's hue: both draw the same grid, under one key, so +/// a switch between them does not test the colors again. +#[test] +fn the_wheel_and_the_hue_box_shade_the_same_cells() { + let mut h = harness(app("#3366cc", "wheel", true)); + let cms = cms::active(); + let Some((key, grid)) = drawn(&h) else { panic!("the wheel drew no grid") }; + let z = f32::from_bits(key.1); + assert_eq!((key.0, &key.2), (Channel::Hue, cms.settings())); + assert!((z * 360.0 - 220.0).abs() < 0.5, "the ring's hue: {}", z * 360.0); + assert_eq!(grid, gamut_grid(&cms, Channel::Hue, z)); + h.state_mut().run("ui.colorWheel", json!({"view": "box"})).unwrap(); + h.run_steps(2); + // Other tests in this process may register profiles between the frames, which changes the + // key's profile generation; the channel, value, settings and grid stay the same. + let Some((boxed, boxed_grid)) = drawn(&h) else { panic!("the box drew no grid") }; + assert_eq!((boxed.0, boxed.1, &boxed.2, boxed_grid), (key.0, key.1, &key.2, grid)); +} + +/// With Show Out-of-Gamut Colors off, the panel tests no colors. +#[test] +fn with_the_setting_off_no_grid_is_computed() { + let h = harness(app("#3366cc", "box", false)); + assert_eq!(drawn(&h), None); +} + +/// `ui.colorWheel {gamut}` sets the setting and keeps the others; a key set to null keeps its value +/// while the other keys apply; a value that is not true or false is an error that changes nothing, +/// translated where messages are. +#[test] +fn ui_color_wheel_sets_gamut() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let with = |v: serde_json::Value| { + let mut v = v; + let rest = json!({"sliders": "none", "harmony": false, "harmonyRule": "complementary", "vision": false, "documentColors": false}); + v.as_object_mut().unwrap().extend(rest.as_object().unwrap().clone()); + v + }; + app.run("ui.colorWheel", json!({"view": "box"})).unwrap(); + assert_eq!(app.run("ui.colorWheel", json!({"gamut": true})).unwrap(), with(json!({"view": "box", "channel": "hue", "gamut": true}))); + let e = app.run("ui.colorWheel", json!({"view": "wheel", "gamut": "yes"})).unwrap_err(); + assert_eq!(e, "`gamut` must be true or false"); + assert_eq!(app.ui.color_wheel, Settings { view: View::Box, gamut: true, ..Default::default() }, "an error changes nothing"); + assert_eq!(app.run("ui.colorWheel", json!({"gamut": null})).unwrap()["gamut"], json!(true), "null keeps the value"); + app.run("ui.colorWheel", json!({"channel": "red"})).unwrap(); + let got = app.run("ui.colorWheel", json!({"view": "wheel", "channel": null, "gamut": null})).unwrap(); + assert_eq!(got, with(json!({"view": "wheel", "channel": "red", "gamut": true})), "null keeps a value while the other keys apply"); + let got = app.run("ui.colorWheel", json!({"view": null, "gamut": false})).unwrap(); + assert_eq!(got, with(json!({"view": "wheel", "channel": "red", "gamut": false})), "a null view keeps the view while gamut applies"); + for code in ["de", "fr", "ja", "zh-hans"] { + let lang = crate::i18n::Lang::from_code(code).expect("registered"); + let shown = crate::i18n::message(lang, &e); + assert_ne!(shown, e, "{code}"); + assert!(shown.contains("`gamut`"), "{code}: {shown}"); + } +} + +/// The setting survives a JSON round trip of the preferences, and a saved value that is not true +/// or false reads as off without losing the other settings. +#[test] +fn the_gamut_setting_is_kept_and_read_leniently() { + let ui = crate::UiState { color_wheel: Settings { view: View::Box, gamut: true, ..Default::default() }, ..Default::default() }; + let saved = serde_json::to_value(&ui).unwrap(); + assert_eq!(saved["color_wheel"]["gamut"], json!(true)); + let back: crate::UiState = serde_json::from_value(saved.clone()).unwrap(); + assert_eq!(back.color_wheel, ui.color_wheel); + let mut odd = saved; + odd["color_wheel"] = json!({"view": "box", "channel": "red", "gamut": "yes"}); + let back: crate::UiState = serde_json::from_value(odd).unwrap(); + assert_eq!(back.color_wheel, Settings { view: View::Box, channel: Channel::Red, gamut: false, ..Default::default() }); +} + +/// The panel menu's Show Out-of-Gamut Colors is checked while the setting is on, and switches it. +#[test] +fn the_panel_menu_switches_the_shading() { + let app = app("#ff0000", "wheel", false); + let mut fonts = false; + let mut h = Harness::builder().with_size(vec2(260.0, 360.0)).build_ui_state( + move |ui, app: &mut VectorcraftApp| { + // The fonts, which draw the check mark, take effect from the next frame. + if !fonts { + crate::theme::install_fonts(ui.ctx()); + fonts = true; + return; + } + assert!(super::panel_menu_items(app, ui, super::color_wheel::ID)); + }, + app, + ); + h.run_steps(3); + h.get_by_label(" Show Out-of-Gamut Colors").click(); + h.run_steps(2); + assert!(h.state().ui.color_wheel.gamut); + assert!(h.query_by_label("✓ Show Out-of-Gamut Colors").is_some()); + h.get_by_label("✓ Show Out-of-Gamut Colors").click(); + h.run_steps(2); + assert!(!h.state().ui.color_wheel.gamut); +} + +/// The edge runs between the marked cells and the others, inside the grid only, and bits past the +/// grid's width are not cells. +#[test] +fn the_edge_runs_between_marked_and_unmarked_cells() { + assert_eq!(crate::widgets::shade_edges(&[0b01, 0b00]), vec![[(1, 0), (1, 1)], [(0, 1), (1, 1)]]); + assert_eq!(crate::widgets::shade_edges(&[0b11, 0b11]), Vec::<[(usize, usize); 2]>::new(), "all marked"); + assert_eq!(crate::widgets::shade_edges(&[0b100]), Vec::<[(usize, usize); 2]>::new(), "bit 2 is past a 1 × 1 grid"); + assert_eq!(crate::widgets::shade_edges(&[]), Vec::<[(usize, usize); 2]>::new()); +} + +/// The gray covers each marked cell and no other, and each edge is drawn dark, then light on top. +#[test] +fn the_gray_covers_the_marked_cells_only() { + use egui::{Pos2, Rect, Shape}; + let ctx = egui::Context::default(); + let rect = Rect::from_min_size(Pos2::new(10.0, 20.0), vec2(16.0, 16.0)); + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| crate::widgets::shade_cells(ui.painter(), rect, &[0b01, 0b10])); + out.textures_delta.clear(); + let grays: Vec = out + .shapes + .iter() + .filter_map(|c| match &c.shape { + Shape::Rect(r) if r.fill == crate::widgets::SHADE => Some(r.rect), + _ => None, + }) + .collect(); + let cell = |col: f32, row: f32| Rect::from_min_size(Pos2::new(10.0 + col * 8.0, 20.0 + row * 8.0), vec2(8.0, 8.0)); + assert_eq!(grays, vec![cell(0.0, 0.0), cell(1.0, 1.0)]); + let lines: Vec<(f32, egui::Color32)> = out + .shapes + .iter() + .filter_map(|c| match &c.shape { + Shape::LineSegment { stroke, .. } => Some((stroke.width, stroke.color)), + _ => None, + }) + .collect(); + let dark = vec![(2.0, egui::Color32::BLACK); 4]; + let light = vec![(1.0, egui::Color32::WHITE); 4]; + assert_eq!(lines, [dark, light].concat(), "four edges, dark under light"); +} diff --git a/crates/ui-egui/src/panels/tests_color_wheel_vision.rs b/crates/ui-egui/src/panels/tests_color_wheel_vision.rs index 7c07b71f90..e929d15086 100644 --- a/crates/ui-egui/src/panels/tests_color_wheel_vision.rs +++ b/crates/ui-egui/src/panels/tests_color_wheel_vision.rs @@ -225,8 +225,7 @@ fn the_panel_menu_turns_the_row_on_and_off() { #[test] fn ui_color_wheel_sets_and_reads_the_settings() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); - let settings = - |view: &str, vision: bool| json!({"view": view, "channel": "hue", "harmony": false, "harmonyRule": "complementary", "vision": vision}); + let settings = |view: &str, vision: bool| json!({"view": view, "channel": "hue", "gamut": false, "harmony": false, "harmonyRule": "complementary", "vision": vision, "sliders": "none", "documentColors": false}); assert_eq!(app.run("ui.colorWheel", json!({})).unwrap(), settings("wheel", false)); assert_eq!(app.run("ui.colorWheel", json!({"vision": true})).unwrap(), settings("wheel", true)); assert_eq!(crate::control::inspect(&app, &egui::Context::default())["ui"]["color_wheel"]["vision"], true); @@ -237,7 +236,7 @@ fn ui_color_wheel_sets_and_reads_the_settings() { assert_eq!(app.run("ui.colorWheel", json!(5)).unwrap_err(), "the params must be an object, not 5"); assert_eq!( app.run("ui.colorWheel", json!({"visoin": false})).unwrap_err(), - "unknown parameter `visoin`; the command takes: view, channel, harmony, harmonyRule, vision" + "unknown parameter `visoin`; the command takes: view, channel, sliders, gamut, harmony, harmonyRule, vision, documentColors" ); assert!(app.ui.color_wheel.vision); assert_eq!(app.run("ui.colorWheel", json!({"vision": null})).unwrap()["vision"], true); diff --git a/crates/ui-egui/src/panels/tests_links.rs b/crates/ui-egui/src/panels/tests_links.rs index 12a0c293b1..85a26e557a 100644 --- a/crates/ui-egui/src/panels/tests_links.rs +++ b/crates/ui-egui/src/panels/tests_links.rs @@ -458,6 +458,13 @@ fn a_nested_rows_tooltip_names_what_holds_it() { // A row in the layers says only its file. let row = json!({"id": 9, "name": "a.png", "status": "ok", "path": "/x/a.png"}); assert_eq!(super::links::status_tip(&row, None), "/x/a.png"); + // The labels take the UI language's colon (#7991). + let fr = crate::i18n::Lang::from_code("fr").unwrap(); + crate::i18n::set_current(fr); + let french = tip(json!({"kind": "symbol", "name": "Mark", "maskOf": 7}), None); + crate::i18n::set_current(crate::i18n::Lang::EN); + let (symbols, mask) = (crate::i18n::tr(fr, "Symbols"), crate::i18n::tr(fr, "Opacity Mask")); + assert_eq!(french, format!("/x/a.png\n{symbols}\u{a0}: Mark\n{mask}\u{a0}: 7")); } /// The tooltip of an image in the opacity mask of an object inside a symbol names that object, @@ -736,3 +743,93 @@ fn the_links_menu_items_run_commands() { assert!(ids("Edit").contains("links.editOriginal")); assert!(ids("Window").contains(super::links::ID)); } + +#[test] +fn right_click_context_menu_in_links_panel() { + use egui::vec2; + use egui_kittest::Harness; + use egui_kittest::kittest::{NodeT, Queryable}; + + let dir = Folder::new("context-menu"); + let (mut app, linked, embedded) = app(&dir); + + let revealed: Rc>> = Rc::default(); + let rev = revealed.clone(); + app.services.reveal = Some(Box::new(move |p: &str| { + rev.borrow_mut().push(p.to_string()); + Ok(()) + })); + + // Initially embedded is selected, linked is unselected + assert_eq!(selected(&app), vec![embedded]); + + let mut h = Harness::builder().with_size(vec2(280.0, 500.0)).with_accessibility_check(false).build_ui_state( + |ui, app: &mut VectorcraftApp| { + super::links::show(app, ui); + }, + app, + ); + h.run_steps(2); + + let right_click = |h: &mut Harness<'static, VectorcraftApp>, label: &str| { + let node = h.get_all_by_label(label).find(|n| n.accesskit_node().role() == egui::accesskit::Role::ListItem).unwrap(); + let pos = node.rect().center(); + h.event(egui::Event::PointerMoved(pos)); + h.event(egui::Event::PointerButton { pos, button: egui::PointerButton::Secondary, pressed: true, modifiers: Default::default() }); + h.event(egui::Event::PointerButton { pos, button: egui::PointerButton::Secondary, pressed: false, modifiers: Default::default() }); + h.run_steps(2); + }; + + // 1. Right-click unselected "linked.png": selects it and opens context menu + right_click(&mut h, "linked.png"); + assert_eq!(selected(h.state()), vec![linked], "right-clicking unselected row selects that row first"); + + let relink = h.get_by_label(" Relink…"); + let go_to = h.get_by_label(" Go To Link"); + let update = h.get_by_label(" Update Link"); + let edit_orig = h.get_by_label(" Edit Original"); + let show_folder = h.get_by_label(" Show in Folder"); + let embed_img = h.get_by_label(" Embed Image"); + + // "Relink…" is disabled because app has no pick_open service by default + assert!(relink.accesskit_node().is_disabled()); + // "Go To Link" is enabled because linked node is in canvas document + assert!(!go_to.accesskit_node().is_disabled()); + // "Update Link" is disabled because linked file is not modified + assert!(update.accesskit_node().is_disabled()); + // "Edit Original" and "Show in Folder" are enabled because linked file exists + assert!(!edit_orig.accesskit_node().is_disabled()); + assert!(!show_folder.accesskit_node().is_disabled()); + // "Embed Image" is enabled because it is a linked image + assert!(!embed_img.accesskit_node().is_disabled()); + + // 2. Click "Show in Folder" dispatches links.reveal + show_folder.click(); + h.run_steps(2); + assert_eq!(revealed.borrow().len(), 1); + assert!(revealed.borrow()[0].ends_with("linked.png")); + + // 3. Multi-selection: select both linked and embedded + h.state_mut().run("select.set", json!({"ids": [linked, embedded]})).unwrap(); + assert_eq!(selected(h.state()), vec![linked, embedded]); + + // Right-click "linked.png" while already selected in multi-selection: preserves selection + right_click(&mut h, "linked.png"); + assert_eq!(selected(h.state()), vec![linked, embedded], "right-clicking selected row preserves multi-selection"); + + // 4. Click "Go To Link" focuses the art on canvas via go_to + let go_to_btn = h.get_by_label(" Go To Link"); + assert!(!go_to_btn.accesskit_node().is_disabled()); + go_to_btn.click(); + h.run_steps(2); + assert_eq!(selected(h.state()), vec![linked]); + assert!(h.state().view().unwrap().fitted); + + // 5. Right-click embedded image: displays "Unembed…" while "Edit Original" and "Show in Folder" are disabled + right_click(&mut h, "embedded.png"); + assert_eq!(selected(h.state()), vec![embedded]); + let unembed_btn = h.get_by_label(" Unembed…"); + assert!(!unembed_btn.accesskit_node().is_disabled()); + assert!(h.get_by_label(" Edit Original").accesskit_node().is_disabled()); + assert!(h.get_by_label(" Show in Folder").accesskit_node().is_disabled()); +} diff --git a/crates/ui-egui/src/panels/tests_three_d.rs b/crates/ui-egui/src/panels/tests_three_d.rs index 8b526b28c6..18f75c2898 100644 --- a/crates/ui-egui/src/panels/tests_three_d.rs +++ b/crates/ui-egui/src/panels/tests_three_d.rs @@ -253,6 +253,128 @@ fn a_change_reaches_each_selected_3d_effect_and_no_other_effect() { assert_eq!(fx(c)[0].params, c_shadow); } +/// A custom bevel picked in the panel sends its name and points with `bevel`, to the effects that +/// take a bevel only, and another custom bevel replaces them. +#[test] +fn a_custom_bevel_sends_its_name_and_points() { + let mut app = app(); + let a = app.session.active().unwrap().selection.objects[0].0; + set_type(&mut app, "extrude").unwrap(); + let b = app.run("shape.rectangle", json!({"x": 250, "y": 100, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap(); + app.run("effect.apply", json!({"effect": "threeD.inflate", "item": null})).unwrap(); + app.run("select.set", json!({"ids": [a, b]})).unwrap(); + let ctx = egui::Context::default(); + let pick = |name: &str, points: Value| { + Map::from_iter([ + ("bevel".to_string(), json!("custom")), + (vectorcraft_effects::BEVEL_NAME.to_string(), json!(name)), + (vectorcraft_effects::BEVEL_PROFILE.to_string(), points), + ]) + }; + let notch = json!([[0.0, 0.0], [0.2, 0.6], [0.7, 0.4], [1.0, 1.0]]); + send(&mut app, &ctx, pick("Notch", notch.clone()), false); + let fx = |app: &VectorcraftApp, id: u64| { + app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().appearance.effects[0].params.clone() + }; + let p = fx(&app, a); + assert_eq!( + (&p["bevel"], &p[vectorcraft_effects::BEVEL_NAME], &p[vectorcraft_effects::BEVEL_PROFILE]), + (&json!("custom"), &json!("Notch"), ¬ch) + ); + assert!(fx(&app, b).get(vectorcraft_effects::BEVEL_PROFILE).is_none()); + let steps = json!([[0.0, 0.0], [0.0, 0.5], [0.5, 0.5], [0.5, 1.0], [1.0, 1.0]]); + send(&mut app, &ctx, pick("Steps", steps.clone()), false); + let p = fx(&app, a); + assert_eq!((&p[vectorcraft_effects::BEVEL_NAME], &p[vectorcraft_effects::BEVEL_PROFILE]), (&json!("Steps"), &steps)); +} + +/// With one Extrude & Bevel on a custom bevel and one without, picking that custom bevel sends its +/// name and points too, though the form already held them, so both effects take it. +#[test] +fn a_custom_bevel_picked_for_a_mixed_selection_reaches_every_effect() { + let mut app = app(); + let notch = json!([[0.0, 0.0], [0.2, 0.6], [0.7, 0.4], [1.0, 1.0]]); + let custom = json!({"bevel": "custom", "bevelName": "Notch", "bevelProfile": notch}); + app.run("effect.apply", json!({"effect": "threeD.extrude", "item": null, "params": custom})).unwrap(); + let a = app.session.active().unwrap().selection.objects[0].0; + let b = app.run("shape.rectangle", json!({"x": 250, "y": 100, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap(); + app.run("effect.apply", json!({"effect": "threeD.extrude", "item": null})).unwrap(); + app.run("select.set", json!({"ids": [a, b]})).unwrap(); + let mut fields = target(&app).map(|t| vectorcraft_effects::merged_params(&t.effect, &t.params)).unwrap().as_object().cloned().unwrap(); + super::mark_mixed(&app, &mut fields); + assert_eq!((&fields["bevel"], &fields[vectorcraft_effects::BEVEL_NAME]), (&Value::Null, &json!("Notch"))); + let before = Value::Object(fields.clone()); + fields.insert("bevel".into(), json!("custom")); + let changed = changed_settings(&before, &Value::Object(fields)); + assert_eq!(Value::Object(changed.clone()), json!({"bevel": "custom", "bevelName": "Notch", "bevelProfile": notch})); + send(&mut app, &egui::Context::default(), changed, false); + let st = app.session.active().unwrap(); + for id in [a, b] { + let p = &st.doc.node(vectorcraft_doc::NodeId(id)).unwrap().appearance.effects[0].params; + assert_eq!((&p["bevel"], &p[vectorcraft_effects::BEVEL_PROFILE]), (&json!("custom"), ¬ch), "{id}"); + } +} + +/// Two custom bevels the bevels file does not list: the mixed selection unsets the shown points, +/// and Bevel Shape still lists the first effect's own bevel, which then reaches both effects. +#[test] +fn a_mixed_selection_still_lists_the_first_effects_own_custom_bevel() { + use crate::dialogs::revolve::{OWN_BEVEL, bevel_options}; + let mut app = app(); + let notch = json!([[0.0, 0.0], [0.2, 0.6], [0.7, 0.4], [1.0, 1.0]]); + let steps = json!([[0.0, 0.0], [0.0, 0.5], [0.5, 0.5], [0.5, 1.0], [1.0, 1.0]]); + let custom = |name: &str, points: &Value| json!({"bevel": "custom", "bevelName": name, "bevelProfile": points}); + app.run("effect.apply", json!({"effect": "threeD.extrude", "item": null, "params": custom("Notch", ¬ch)})).unwrap(); + let a = app.session.active().unwrap().selection.objects[0].0; + let b = app.run("shape.rectangle", json!({"x": 250, "y": 100, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap(); + app.run("effect.apply", json!({"effect": "threeD.extrude", "item": null, "params": custom("Steps", &steps)})).unwrap(); + app.run("select.set", json!({"ids": [a, b]})).unwrap(); + let mut fields = target(&app).map(|t| vectorcraft_effects::merged_params(&t.effect, &t.params)).unwrap().as_object().cloned().unwrap(); + let own = super::own_bevel(&fields).unwrap(); + super::mark_mixed(&app, &mut fields); + assert_eq!(fields[vectorcraft_effects::BEVEL_PROFILE], Value::Null); + fields.insert(OWN_BEVEL.into(), own); + let (options, builtin) = bevel_options(&app, &fields, "threeD.extrude"); + assert_eq!(options.len(), builtin + 1); + let (label, value, picked) = options[builtin].clone(); + assert_eq!((label.as_str(), value), ("Notch", json!("custom"))); + let (name, points) = picked.unwrap(); + assert_eq!(points, notch); + // Picking it sends the whole bevel to both effects. + fields.remove(OWN_BEVEL); + let before = Value::Object(fields.clone()); + fields.insert(vectorcraft_effects::BEVEL_NAME.into(), json!(name)); + fields.insert(vectorcraft_effects::BEVEL_PROFILE.into(), points); + send(&mut app, &egui::Context::default(), changed_settings(&before, &Value::Object(fields)), false); + let st = app.session.active().unwrap(); + for id in [a, b] { + let p = &st.doc.node(vectorcraft_doc::NodeId(id)).unwrap().appearance.effects[0].params; + assert_eq!((&p[vectorcraft_effects::BEVEL_NAME], &p[vectorcraft_effects::BEVEL_PROFILE]), (&json!("Notch"), ¬ch), "{id}"); + } +} + +/// An effect's own custom bevel named like a bevel of the bevels file with other points is listed +/// under its own label, so Bevel Shape does not show two entries of one name. +#[test] +fn an_own_custom_bevel_named_like_a_file_bevel_gets_its_own_label() { + use crate::dialogs::revolve::bevel_options; + let dir = std::env::temp_dir().join(format!("vectorcraft-ui-bevels-own-label-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let mut app = app(); + app.session.attach_bevels_file(dir.join(vectorcraft_engine::cmd::bevels::FILE_NAME).to_string_lossy().to_string()); + app.run("threeD.bevels.edit", json!({})).unwrap(); + let file = app.session.bevels.get("Example Bevel").unwrap().profile_json(); + let other = json!([[0.0, 0.0], [0.5, 0.5], [1.0, 1.0]]); + assert_ne!(file, other); + let fields = json!({"bevel": "custom", "bevelName": "Example Bevel", "bevelProfile": other}).as_object().cloned().unwrap(); + let (options, builtin) = bevel_options(&app, &fields, "threeD.extrude"); + let _ = std::fs::remove_dir_all(&dir); + let labels: Vec<&str> = options[builtin..].iter().map(|(l, _, _)| l.as_str()).collect(); + assert_eq!(labels, ["Example Bevel", "Example Bevel (document)"]); + assert_eq!(options[builtin + 1].2, Some(("Example Bevel".to_string(), other))); +} + #[test] fn the_panel_finds_a_3d_effect_on_a_fill() { let mut app = app(); diff --git a/crates/ui-egui/src/panels/three_d.rs b/crates/ui-egui/src/panels/three_d.rs index c1cdbd71b1..d8ecd19bc5 100644 --- a/crates/ui-egui/src/panels/three_d.rs +++ b/crates/ui-egui/src/panels/three_d.rs @@ -13,10 +13,11 @@ use std::sync::Arc; use egui::Ui; use serde_json::{Map, Value, json}; use vectorcraft_doc::{Effect, Node, NodeId, NodeKind}; -use vectorcraft_effects::{CLASSIC_EXTRUDE, CLASSIC_REVOLVE, EXTRUDE, INFLATE, THREE_D_TYPES, is_three_d}; +use vectorcraft_effects::{BEVEL_NAME, BEVEL_PROFILE, CLASSIC_EXTRUDE, CLASSIC_REVOLVE, EXTRUDE, INFLATE, THREE_D_TYPES, is_three_d}; use super::{live_run, pstate, set_pstate}; use crate::VectorcraftApp; +use crate::dialogs::revolve::OWN_BEVEL; use crate::dialogs::three_d_materials as materials; use crate::state::Dialog; use crate::theme::Tokens; @@ -157,9 +158,11 @@ pub(crate) fn send(app: &mut VectorcraftApp, ctx: &egui::Context, changed: Map = pending .iter() - .filter(|(k, _)| takes.get(k.as_str()).is_some() && (k.as_str() != "lights" || *same_lights)) + .filter(|(k, _)| (takes.get(k.as_str()).is_some() || custom_bevel(k)) && (k.as_str() != "lights" || *same_lights)) .map(|(k, v)| (k.clone(), v.clone())) .collect(); (!params.is_empty()) @@ -242,13 +245,19 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } // The applied effect's settings in the dialog's form, with the controls' own state. let mut fields = vectorcraft_effects::merged_params(&t.effect, &t.params).as_object().cloned().unwrap_or_default(); + let own_bevel = own_bevel(&fields); mark_mixed(app, &mut fields); fields.extend(pstate::>(&ctx, UI_STATE)); fields.insert("__effect".into(), json!(t.effect)); fields.insert("__panel".into(), json!(true)); + if let Some(own) = own_bevel { + fields.insert(OWN_BEVEL.into(), own); + } let mut d = Dialog { kind: ID.into(), fields }; let before = crate::dialogs::form::params(&d); crate::dialogs::revolve::controls(app, ui, &mut d); + d.fields.remove(OWN_BEVEL); + let edit_bevels = d.fields.remove("__editBevels").is_some(); let action = d.fields.remove(materials::ACTION).and_then(|v| materials::Action::from_value(&v)); let state: Map = d .fields @@ -261,6 +270,14 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let changed = changed_settings(&before, &after); let dragging = ctx.input(|i| i.pointer.any_down()); send(app, &ctx, changed, dragging); + // Bevel Shape's Edit Bevels…: the bevels file opens as a document of its own. + if edit_bevels { + finish(app, &ctx); + if let Err(e) = app.run("threeD.bevels.edit", json!({})) { + app.ui.status = e; + } + return; + } if quick_actions_shown(&d) { ui.add_space(10.0); let t = Tokens::get(ui.ctx()); @@ -606,10 +623,30 @@ pub(crate) fn mark_mixed(app: &VectorcraftApp, fields: &mut Map) } } +/// The custom bevel of an effect's settings `fields`, `[name, points]`, when its `bevel` is +/// `"custom"` with points (the Bevel Shape menu lists it while a mixed selection unsets them). +pub(crate) fn own_bevel(fields: &Map) -> Option { + let points = fields.get(BEVEL_PROFILE).filter(|v| !v.is_null())?; + let name = fields.get(BEVEL_NAME).and_then(Value::as_str).unwrap_or_default(); + (fields.get("bevel").and_then(Value::as_str) == Some("custom")).then(|| json!([name, points])) +} + /// The settings whose values differ between `before` and `after`, with their values in `after`. +/// A change to a custom bevel (`bevel` `"custom"`, its name or its points) sends all three, so an +/// effect of a mixed selection that had none takes the whole bevel. pub(crate) fn changed_settings(before: &Value, after: &Value) -> Map { let Some(after) = after.as_object() else { return Map::new() }; - after.iter().filter(|(k, v)| before.get(k.as_str()) != Some(*v)).map(|(k, v)| (k.clone(), v.clone())).collect() + let mut changed: Map = + after.iter().filter(|(k, v)| before.get(k.as_str()) != Some(*v)).map(|(k, v)| (k.clone(), v.clone())).collect(); + let custom = ["bevel", BEVEL_NAME, BEVEL_PROFILE]; + if after.get("bevel").and_then(Value::as_str) == Some("custom") && custom.iter().any(|k| changed.contains_key(*k)) { + for k in custom { + if let Some(v) = after.get(k) { + changed.insert(k.into(), v.clone()); + } + } + } + changed } #[cfg(test)] diff --git a/crates/ui-egui/src/panels/transform/tests.rs b/crates/ui-egui/src/panels/transform/tests.rs index dbb92b3cd4..75ae9f2594 100644 --- a/crates/ui-egui/src/panels/transform/tests.rs +++ b/crates/ui-egui/src/panels/transform/tests.rs @@ -136,6 +136,101 @@ fn a_polygon_shows_its_polygon_properties() { assert!(live(&app).polygon_sides_equal()); } +/// A live rectangle's Rectangle Properties show one Corner menu for all four corners while Corner +/// Radius is linked, blank when the corners' kinds differ, and one per corner when it is unlinked, +/// in the Transform panel and the Properties panel's Transform section. +#[test] +fn a_rectangle_shows_linked_and_unlinked_corner_types() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + app.run("shape.rectangle", json!({"x": 50, "y": 50, "width": 120, "height": 80, "radius": 10})).unwrap(); + let count = |shown: &[String], t: &str| shown.iter().filter(|s| *s == t).count(); + let draws = [show as fn(&mut VectorcraftApp, &mut Ui), crate::panels::properties::transform_section]; + set_pref(&mut app, "singleCornerRadius", true); + for draw in draws { + let shown = texts(&mut app, draw); + assert_eq!((count(&shown, "Corner:"), count(&shown, "Round")), (1, 1), "{shown:?}"); + } + // Kinds that differ leave the linked menu blank. + app.run("object.setLiveShape", json!({"kind": "chamfer", "corners": [2]})).unwrap(); + for draw in draws { + let shown = texts(&mut app, draw); + assert_eq!((count(&shown, "Corner:"), count(&shown, "Round"), count(&shown, "Chamfer")), (1, 0, 0), "{shown:?}"); + } + set_pref(&mut app, "singleCornerRadius", false); + for draw in draws { + let shown = texts(&mut app, draw); + for t in ["Top Left:", "Top Right:", "Bottom Right:", "Bottom Left:"] { + assert_eq!(count(&shown, t), 1, "{t} in {shown:?}"); + } + assert_eq!((count(&shown, "Round"), count(&shown, "Chamfer")), (3, 1), "{shown:?}"); + } +} + +/// A corner kind set with no live rectangle selected leaves the selected polygon, the document and +/// its undo history as they are. +#[test] +fn a_rectangle_corner_kind_without_a_selected_rectangle_changes_nothing() { + use vectorcraft_geom::shapes::CornerKind::Chamfer; + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + app.run("shape.polygon", json!({"cx": 150, "cy": 150, "radius": 40, "sides": 6})).unwrap(); + let st = app.session.active().unwrap(); + let (before, steps) = (st.doc.clone(), st.history.undo.len()); + crate::panels::set_rectangle_kinds(&mut app, Chamfer, None); + crate::panels::set_rectangle_kinds(&mut app, Chamfer, Some(2)); + let st = app.session.active().unwrap(); + assert!(st.doc == before, "the document changed"); + assert_eq!(st.history.undo.len(), steps); +} + +/// A corner kind picked while a Shape Builder merge is computed on another thread applies the +/// merge first, and sets the kind on the live rectangles selected after it. +#[test] +fn a_rectangle_corner_kind_applies_a_merge_on_another_thread_first() { + use vectorcraft_geom::shapes::CornerKind::Chamfer; + use vectorcraft_tools::{Mods, PointerEvent, PointerKind}; + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 800, "height": 200})).unwrap(); + for k in 0..40 { + app.run("shape.rectangle", json!({"x": k * 10, "y": 0, "width": 20, "height": 20})).unwrap(); + } + app.run("select.all", json!({})).unwrap(); + app.run("tool.select", json!({"tool": "shapeBuilder"})).unwrap(); + let view = app.view_info(); + let at = |kind| PointerEvent { + kind, + pos: vectorcraft_geom::Point::new(15.0, 10.0), + mods: Mods::default(), + pressure: 1.0, + backquote: false, + pen: None, + }; + crate::canvas::dispatch(&mut app, &at(PointerKind::Move), view); + app.session.tool_poll(view, true).unwrap(); + crate::canvas::dispatch(&mut app, &at(PointerKind::Down), view); + crate::canvas::dispatch(&mut app, &at(PointerKind::Up), view); + assert!(app.session.tool_editing()); + crate::panels::set_rectangle_kinds(&mut app, Chamfer, None); + assert!(!app.session.tool_editing()); + let st = app.session.active().unwrap(); + let labels: Vec<_> = st.history.undo.iter().rev().take(2).map(|e| e.label.as_str()).collect(); + assert_eq!(labels, ["Live Shape", "Shape Builder"]); + let kinds: Vec<_> = st + .selection + .objects + .iter() + .filter_map(|id| match &st.doc.node(*id)?.kind { + NodeKind::Path { live: Some(l), .. } => match &**l { + LiveShape::Rectangle { kinds, .. } => Some(*kinds), + _ => None, + }, + _ => None, + }) + .collect(); + assert!(!kinds.is_empty() && kinds.iter().all(|k| *k == [Chamfer; 4]), "{kinds:?}"); +} + /// #3451: a live ellipse shows pie start/end angles and Invert Pie in the Transform panel and /// the Properties panel's Transform section; typed angles update the shape. #[test] diff --git a/crates/ui-egui/src/place.rs b/crates/ui-egui/src/place.rs index a644c91ce9..a36d85f8a2 100644 --- a/crates/ui-egui/src/place.rs +++ b/crates/ui-egui/src/place.rs @@ -262,6 +262,9 @@ fn place_file_in(app: &mut VectorcraftApp, p: &Value, read: Read) -> Result { let r = crate::placing::start(app, &p, dropped); @@ -553,12 +556,17 @@ pub(crate) fn place_from_cursor(app: &mut VectorcraftApp, p: &Value) { }); // Placing shows its own errors in the status bar. let _ = place_file(app, &p, Read::ForUser { dropped: false }); - } else if crate::placing::available(app) { - if let Err(e) = crate::placing::start(app, p, false) { - app.status(e); - } } else { - let _ = engine(app, "file.place", p); + // An embedded PDF takes the `pdfTextAs` preference, as one placed from the Place dialog. + let mut p = p.clone(); + crate::dialogs::import_pdf::place_with_preferred_text_as(app, &mut p); + if crate::placing::available(app) { + if let Err(e) = crate::placing::start(app, &p, false) { + app.status(e); + } + } else { + let _ = engine(app, "file.place", &p); + } } }); } diff --git a/crates/ui-egui/src/prefs_dialog/descriptions.rs b/crates/ui-egui/src/prefs_dialog/descriptions.rs index d7227d7c83..ec8aea7063 100644 --- a/crates/ui-egui/src/prefs_dialog/descriptions.rs +++ b/crates/ui-egui/src/prefs_dialog/descriptions.rs @@ -237,7 +237,7 @@ pub(crate) const DESCRIPTIONS: &[(&str, &str)] = &[ // Plug-ins & Scratch Disks ( "pluginsFolder", - "On the desktop, the .wasm plug-ins in this folder load at startup and when you click OK with a new folder here, except in Safe Mode; the web version does not load them.", + "On the desktop, this folder's .wasm plug-ins load at startup and when OK sets a new folder, except in Safe Mode; one that asks for permissions loads only after you grant them. The web version loads none.", ), ( "pluginInstructionBudget", @@ -263,10 +263,13 @@ pub(crate) const DESCRIPTIONS: &[(&str, &str)] = &[ "From now on, documents you open or create open as tabs; off, each opens in a floating window. Documents already open stay where they are.", ), ("largeTabs", "Makes the document tabs taller and their names larger."), - ("systemTitleBar", "From the next start, the system draws the window's title bar where VectorCraft would otherwise draw its own."), + ( + "systemTitleBar", + "From the next start, the system draws the window's title bar where VectorCraft would otherwise draw its own; on Linux and the BSDs, the VECTORCRAFT_TITLEBAR variable takes precedence.", + ), ( "appTitleBar", - "From the next start, VectorCraft draws the window's title bar even where the desktop would draw it, unless System Title Bar is on.", + "From the next start, VectorCraft draws the window's title bar even where the desktop would draw it, unless System Title Bar is on or the VECTORCRAFT_TITLEBAR variable chooses it.", ), ("uiScaling", "Makes the interface larger or smaller; art on the canvas keeps its size at the same zoom."), ("scaleCursorWithUi", "The tool pointers VectorCraft draws grow and shrink with UI Scaling; off, they keep their size."), @@ -279,7 +282,7 @@ pub(crate) const DESCRIPTIONS: &[(&str, &str)] = &[ ), ( "gpuPreference", - "From the next start, the desktop version draws with this kind of graphics processor; Automatic prefers the one that drives the display. The web version does not use it.", + "From the next start, the desktop version shows the canvas through this kind of graphics processor; the artwork is drawn on the CPU either way. Automatic prefers the integrated one on Windows and macOS. The web version does not use it.", ), ( "lowLatencyDrawing", @@ -337,6 +340,10 @@ pub(crate) const DESCRIPTIONS: &[(&str, &str)] = &[ "updateLinks", "When a linked file changes, Automatically reads it again, Ask When Modified asks you first, and Manually leaves it and shows a note in the status bar.", ), + ( + "pdfTextAs", + "The text of a PDF you open or embed comes in as editable type, or as outlines that look the same on a computer without its fonts.", + ), ( "templatesFolder", "On the desktop, the folder New from Template… and Save as Template… start in; leave it blank for VectorCraft Templates in your documents folder.", diff --git a/crates/ui-egui/src/prefs_dialog/tests.rs b/crates/ui-egui/src/prefs_dialog/tests.rs index 0b05159a72..c79ca22470 100644 --- a/crates/ui-egui/src/prefs_dialog/tests.rs +++ b/crates/ui-egui/src/prefs_dialog/tests.rs @@ -1856,25 +1856,41 @@ fn a_text_shows_only_while_its_center_is_inside_its_clip() { /// with their rectangles, and the description of the accessibility node with the keyboard focus, if /// it has one. fn description_frame(a: &mut VectorcraftApp, ctx: &egui::Context, events: Vec) -> (Vec<(String, egui::Rect)>, Option) { + frame_texts(a, ctx, events, |clip, r| shows_in_clip(r, clip)) +} + +/// [`description_frame`], keeping only the texts whose whole rectangle is inside their clip +/// rectangle, so that the pointer can reach the center of each one. +fn whole_texts_frame(a: &mut VectorcraftApp, ctx: &egui::Context, events: Vec) -> Vec<(String, egui::Rect)> { + frame_texts(a, ctx, events, |clip, r| clip.contains_rect(r)).0 +} + +/// [`description_frame`] with the texts that `keep(clip rectangle, text rectangle)` accepts. +fn frame_texts( + a: &mut VectorcraftApp, + ctx: &egui::Context, + events: Vec, + keep: fn(egui::Rect, egui::Rect) -> bool, +) -> (Vec<(String, egui::Rect)>, Option) { let time = ctx.input(|i| i.time) + 0.25; let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 900.0))); let raw = egui::RawInput { screen_rect, events, time: Some(time), ..Default::default() }; let mut out = ctx.run_ui(raw, |ui| show(a, ui.ctx())); out.textures_delta.clear(); - fn walk(s: &egui::Shape, clip: egui::Rect, v: &mut Vec<(String, egui::Rect)>) { + fn walk(s: &egui::Shape, clip: egui::Rect, keep: fn(egui::Rect, egui::Rect) -> bool, v: &mut Vec<(String, egui::Rect)>) { match s { egui::Shape::Text(t) => { let r = egui::Rect::from_min_size(t.pos, t.galley.size()); - if shows_in_clip(r, clip) { + if keep(clip, r) { v.push((t.galley.text().to_string(), r)); } } - egui::Shape::Vec(s) => s.iter().for_each(|s| walk(s, clip, v)), + egui::Shape::Vec(s) => s.iter().for_each(|s| walk(s, clip, keep, v)), _ => {} } } let mut texts = vec![]; - out.shapes.iter().for_each(|c| walk(&c.shape, c.clip_rect, &mut texts)); + out.shapes.iter().for_each(|c| walk(&c.shape, c.clip_rect, keep, &mut texts)); let focused = out.platform_output.accesskit_update.and_then(|u| { let focus = u.focus; u.nodes.into_iter().find(|(id, _)| *id == focus).and_then(|(_, n)| n.description().map(str::to_string)) @@ -2014,6 +2030,37 @@ fn description_line_rects(ctx: &egui::Context) -> DescriptionRects { DescriptionRects { column, line } } +/// Scrolls the field list with the wheel until the last text `label` in `texts` lies wholly inside +/// the list, above the spacing and the gap over the description line, and stays put there (the +/// wheel scrolls smoothly over several frames) → the texts of the last frame. +fn scroll_into_view(a: &mut VectorcraftApp, ctx: &egui::Context, mut texts: Vec<(String, egui::Rect)>, label: &str) -> Vec<(String, egui::Rect)> { + let wheel = egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: egui::vec2(0.0, -40.0), + phase: egui::TouchPhase::Move, + modifiers: Default::default(), + source: egui::MouseWheelSource::Unknown, + }; + let at = |texts: &[(String, egui::Rect)]| texts.iter().rev().find(|(t, _)| t == label).map(|(_, r)| *r); + let inside = |r: Option| { + let DescriptionRects { column, line } = description_line_rects(ctx); + let bottom = line.min.y - DESCRIPTION_GAP - ctx.global_style().spacing.item_spacing.y; + let list = egui::Rect::from_min_max(column.min, egui::pos2(column.max.x, bottom)); + r.is_some_and(|r| list.contains_rect(r)) + }; + for _ in 0..80 { + let shown = inside(at(&texts)); + let next = description_frame(a, ctx, if shown { vec![] } else { vec![wheel.clone()] }).0; + let still = shown && at(&next) == at(&texts); + texts = next; + if still { + break; + } + } + assert!(inside(at(&texts)), "`{label}` lies wholly inside the field list: {texts:?}"); + texts +} + /// A row with no sentence leaves the description line empty, also after another category's row /// was described, and the dialog keeps its size. #[test] @@ -2416,6 +2463,38 @@ fn keyboard_focus_on_a_slices_row_shows_its_description() { assert!(described.iter().any(|d| d == numbers), "the focused control carries the sentence: {described:?}"); } +/// Whether `sentence` is one of `texts` and is drawn on the description line of the frame that +/// painted them. +fn painted_on_line(ctx: &egui::Context, texts: &[(String, egui::Rect)], sentence: &str) -> bool { + let line = description_line_rects(ctx).line; + texts.iter().any(|(t, r)| t == sentence && r.intersects(line)) +} + +/// Tab from the search field, which must have the keyboard, until each of `sentences` has shown on +/// the description line. Other controls may come between them, but a sentence that shows before the +/// ones ahead of it in `sentences` fails the test. → For each sentence, the description of the focused +/// accessibility node and the focused widget when it first showed. +fn tab_to_each(a: &mut VectorcraftApp, ctx: &egui::Context, sentences: &[&str]) -> Vec<(Option, Option)> { + assert!(ctx.memory(|m| m.has_focus(search_edit_id())), "the search field has the keyboard before the first Tab"); + let mut first = vec![]; + for _ in 0..40 { + if first.len() == sentences.len() { + break; + } + let (texts, described) = description_frame(a, ctx, key_press(egui::Key::Tab, egui::Modifiers::NONE)); + if let Some(i) = sentences.iter().position(|s| painted_on_line(ctx, &texts, s)) { + assert!(i <= first.len(), "Tab reaches {:?} before {:?}", sentences[i], sentences[first.len()]); + if i == first.len() { + first.push((described, ctx.memory(|m| m.focused()))); + } + } + } + if let Some(missing) = sentences.get(first.len()) { + panic!("Tab does not reach the row of {missing:?}"); + } + first +} + /// The pointer over Hyphenation's Default Language row and over its Exceptions row shows each /// row's sentence. #[test] @@ -2433,10 +2512,10 @@ fn hovering_a_hyphenation_row_shows_its_description() { let exceptions = descriptions::description("hyphenationExceptions").expect("Exceptions has a sentence"); description_frame(&mut a, &ctx, vec![egui::Event::PointerMoved(row(&texts, "Default Language:"))]); let (after, _) = description_frame(&mut a, &ctx, vec![]); - assert!(painted(&after, language) && !painted(&after, exceptions), "the Default Language row's sentence shows: {after:?}"); + assert!(painted_on_line(&ctx, &after, language) && !painted(&after, exceptions), "the Default Language row's sentence shows: {after:?}"); description_frame(&mut a, &ctx, vec![egui::Event::PointerMoved(row(&texts, "Exceptions"))]); let (after, _) = description_frame(&mut a, &ctx, vec![]); - assert!(painted(&after, exceptions) && !painted(&after, language), "the Exceptions row's sentence shows: {after:?}"); + assert!(painted_on_line(&ctx, &after, exceptions) && !painted(&after, language), "the Exceptions row's sentence shows: {after:?}"); } /// Tab from the search field reaches Hyphenation's Default Language menu and then its Exceptions @@ -2469,7 +2548,7 @@ fn hovering_a_plugins_and_scratch_disks_row_shows_its_description() { }; let rows = [ ("Additional Plug-ins Folder:", "pluginsFolder"), - ("Plug-in Instruction Budget", "pluginInstructionBudget"), + ("Plug-in Instruction", "pluginInstructionBudget"), ("Primary:", "scratchPrimary"), ("Secondary:", "scratchSecondary"), ]; @@ -2478,7 +2557,37 @@ fn hovering_a_plugins_and_scratch_disks_row_shows_its_description() { description_frame(&mut a, &ctx, vec![egui::Event::PointerMoved(row(&texts, label))]); let (after, _) = description_frame(&mut a, &ctx, vec![]); for (j, sentence) in sentences.iter().enumerate() { - assert_eq!(painted(&after, sentence), i == j, "pointer over `{label}`, sentence {j}: {after:?}"); + let shown = if i == j { painted_on_line(&ctx, &after, sentence) } else { painted(&after, sentence) }; + assert_eq!(shown, i == j, "pointer over `{label}`, sentence {j}: {after:?}"); + } + } +} + +/// Tab from the search field reaches the Additional Plug-ins Folder field, then Primary, then +/// Secondary: the line shows each one's sentence in turn, and a screen reader gets it as the focused +/// field's description. With a folder picker, Choose… shares the folder's row, and the folder's +/// text field still has the keyboard when its sentence first shows. +#[test] +fn keyboard_focus_on_a_plugins_and_scratch_disks_row_shows_its_description() { + let keys = ["pluginsFolder", "scratchPrimary", "scratchSecondary"]; + let sentences: Vec<_> = keys.iter().map(|key| descriptions::description(key).unwrap_or_else(|| panic!("`{key}` has a sentence"))).collect(); + for picker in [false, true] { + let mut a = app(); + if picker { + a.services.pick_folder = Some(Box::new(|| None)); + } + open(&mut a, Some("Plug-ins & Scratch Disks")); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + crate::theme::install_fonts(&ctx); + description_frame(&mut a, &ctx, vec![]); + let (texts, _) = description_frame(&mut a, &ctx, vec![]); + assert_eq!(texts.iter().any(|(t, _)| t == "Choose…"), picker, "Choose… shows only with a folder picker: {texts:?}"); + let visits = tab_to_each(&mut a, &ctx, &sentences); + for ((described, focused), (key, sentence)) in visits.iter().zip(keys.iter().zip(&sentences)) { + let field = focused.is_some_and(|id| egui::text_edit::TextEditState::load(&ctx, id).is_some()); + assert!(field, "the `{key}` text field has the keyboard (picker {picker})"); + assert!(described.iter().any(|d| d == sentence), "the focused `{key}` field carries the sentence (picker {picker}): {described:?}"); } } } @@ -2487,7 +2596,7 @@ fn hovering_a_plugins_and_scratch_disks_row_shows_its_description() { /// Budget menu, then Primary, then Secondary: the line shows each one's sentence in turn, and a /// screen reader gets it as the focused control's description. #[test] -fn keyboard_focus_on_a_plugins_and_scratch_disks_row_shows_its_description() { +fn keyboard_focus_on_the_plugin_instruction_budget_menu_shows_its_description() { let mut a = app(); open(&mut a, Some("Plug-ins & Scratch Disks")); let ctx = egui::Context::default(); @@ -2517,7 +2626,8 @@ fn hovering_a_user_interface_row_shows_its_description() { let ctx = egui::Context::default(); crate::theme::install_fonts(&ctx); description_frame(&mut a, &ctx, vec![]); - let (texts, _) = description_frame(&mut a, &ctx, vec![]); + // Only rows the list shows whole: the pointer goes to the center of a row it can reach. + let texts = whole_texts_frame(&mut a, &ctx, vec![]); let row = |texts: &[(String, egui::Rect)], label: &str| { texts.iter().find(|(t, _)| t == label).map(|(_, r)| r.center()).unwrap_or_else(|| panic!("no `{label}` in {texts:?}")) }; @@ -2536,30 +2646,9 @@ fn hovering_a_user_interface_row_shows_its_description() { ]; let sentences: Vec<_> = rows.iter().map(|(_, key)| descriptions::description(key).unwrap_or_else(|| panic!("`{key}` has a sentence"))).collect(); // The Language row is under the bottom of the list: the wheel scrolls it into view. - let wheel = egui::Event::MouseWheel { - unit: egui::MouseWheelUnit::Point, - delta: egui::vec2(0.0, -40.0), - phase: egui::TouchPhase::Move, - modifiers: Default::default(), - source: egui::MouseWheelSource::Unknown, - }; let mut texts = texts; for (i, (label, _)) in rows.iter().enumerate() { - for _ in 0..20 { - if texts.iter().any(|(t, _)| t == label) { - break; - } - texts = description_frame(&mut a, &ctx, vec![wheel.clone()]).0; - } - // The wheel scrolls smoothly over several frames: wait until the row stays put. - for _ in 0..60 { - let next = description_frame(&mut a, &ctx, vec![]).0; - let still = row(&next, label) == row(&texts, label); - texts = next; - if still { - break; - } - } + texts = scroll_into_view(&mut a, &ctx, texts, label); description_frame(&mut a, &ctx, vec![egui::Event::PointerMoved(row(&texts, label))]); let (after, _) = description_frame(&mut a, &ctx, vec![]); for (j, sentence) in sentences.iter().enumerate() { @@ -2626,30 +2715,9 @@ fn hovering_a_performance_row_shows_its_description() { } let sentences: Vec<_> = rows.iter().map(|(_, key)| descriptions::description(key).unwrap_or_else(|| panic!("`{key}` has a sentence"))).collect(); // The last rows can be under the bottom of the list: the wheel scrolls them into view. - let wheel = egui::Event::MouseWheel { - unit: egui::MouseWheelUnit::Point, - delta: egui::vec2(0.0, -40.0), - phase: egui::TouchPhase::Move, - modifiers: Default::default(), - source: egui::MouseWheelSource::Unknown, - }; let mut texts = texts; for (i, (label, _)) in rows.iter().enumerate() { - for _ in 0..20 { - if texts.iter().any(|(t, _)| t == label) { - break; - } - texts = description_frame(&mut a, &ctx, vec![wheel.clone()]).0; - } - // The wheel scrolls smoothly over several frames: wait until the row stays put. - for _ in 0..60 { - let next = description_frame(&mut a, &ctx, vec![]).0; - let still = row(&next, label) == row(&texts, label); - texts = next; - if still { - break; - } - } + texts = scroll_into_view(&mut a, &ctx, texts, label); description_frame(&mut a, &ctx, vec![egui::Event::PointerMoved(row(&texts, label))]); let (after, _) = description_frame(&mut a, &ctx, vec![]); for (j, sentence) in sentences.iter().enumerate() { @@ -2680,7 +2748,7 @@ fn keyboard_focus_on_a_performance_row_shows_its_description() { assert_tab_order(&mut a, &ctx, &keys); } -/// The pointer over each of the 14 File Handling rows, from Enable Background Save to Use +/// The pointer over each of the 15 File Handling rows, from Enable Background Save to Use /// Compression, shows that row's sentence and no other row's. #[test] fn hovering_a_file_handling_row_shows_its_description() { @@ -2704,6 +2772,7 @@ fn hovering_a_file_handling_row_shows_its_description() { ("Use Low Resolution Proxy for Linked EPS", "lowResProxyEps"), ("Display Bitmaps as Anti-aliased Images in Pixel Preview", "antiAliasedBitmaps"), ("Update Links:", "updateLinks"), + ("PDF Text:", "pdfTextAs"), ("Templates Folder:", "templatesFolder"), ("Use System Defaults for Edit Original", "editOriginalSystemDefaults"), ("Mark Older Files as [Converted] When Opened", "appendConverted"), @@ -2711,30 +2780,9 @@ fn hovering_a_file_handling_row_shows_its_description() { ]; let sentences: Vec<_> = rows.iter().map(|(_, key)| descriptions::description(key).unwrap_or_else(|| panic!("`{key}` has a sentence"))).collect(); // The last rows can be under the bottom of the list: the wheel scrolls them into view. - let wheel = egui::Event::MouseWheel { - unit: egui::MouseWheelUnit::Point, - delta: egui::vec2(0.0, -40.0), - phase: egui::TouchPhase::Move, - modifiers: Default::default(), - source: egui::MouseWheelSource::Unknown, - }; let mut texts = texts; for (i, (label, _)) in rows.iter().enumerate() { - for _ in 0..20 { - if texts.iter().any(|(t, _)| t == label) { - break; - } - texts = description_frame(&mut a, &ctx, vec![wheel.clone()]).0; - } - // The wheel scrolls smoothly over several frames: wait until the row stays put. - for _ in 0..60 { - let next = description_frame(&mut a, &ctx, vec![]).0; - let still = row(&next, label) == row(&texts, label); - texts = next; - if still { - break; - } - } + texts = scroll_into_view(&mut a, &ctx, texts, label); description_frame(&mut a, &ctx, vec![egui::Event::PointerMoved(row(&texts, label))]); let (after, _) = description_frame(&mut a, &ctx, vec![]); for (j, sentence) in sentences.iter().enumerate() { diff --git a/crates/ui-egui/src/shortcut_editor.rs b/crates/ui-egui/src/shortcut_editor.rs index f45a02e75e..a9d7b022a7 100644 --- a/crates/ui-egui/src/shortcut_editor.rs +++ b/crates/ui-egui/src/shortcut_editor.rs @@ -937,17 +937,27 @@ pub(crate) fn menu_target(id: &str) -> Option<(String, Value)> { /// status line ([`dimmed`]), as for Remove Background… with no image selected. pub(crate) fn menu_target_now(app: &VectorcraftApp, id: &str) -> Option> { let target = menu_target(id)?; - Some(if menus::enabled(app, id) { Ok(target) } else { dimmed(app, id) }) + Some(match dimmed(app, id, id) { + None => Ok(target), + Some(why) => Err(why), + }) } -/// What [`menu_target_now`] gives for command `id` while its menu bar item is dimmed: the status -/// line, with the engine's reason when it gives one. The app's own rules ([`menus::enabled`]) dim -/// UI commands, and some commands the engine would run, without giving a reason. -pub(crate) fn dimmed(app: &VectorcraftApp, id: &str) -> Result<(String, Value), String> { - let Some(why) = vectorcraft_engine::find_command(id).and_then(|c| (c.enabled)(&app.session).err()) else { - return Err(format!("command `{id}` is not available right now")); +/// What [`menu_target_now`] gives for command `id` while its menu bar item is dimmed, or `None` +/// while the item is not dimmed: the status line, which calls the command `name` (its id on the +/// status line), with the engine's reason when it gives one. The app's own rules +/// ([`menus::enabled`]) dim UI commands, and some commands the engine would run, without giving a +/// reason. The engine's check runs at most once. +pub(crate) fn dimmed(app: &VectorcraftApp, id: &str, name: &str) -> Option { + let why = match menus::why_off(app, id)? { + Some(why) => Some(why), + // Dimmed before the engine was asked (no Appearance subject, an input method composing). + None => vectorcraft_engine::find_command(id).and_then(|c| (c.enabled)(&app.session).err()), }; - Err(vectorcraft_engine::EngineError::Disabled(id.to_string(), why).to_string()) + Some(match why { + Some(why) => vectorcraft_engine::EngineError::Disabled(name.to_string(), why).to_string(), + None => format!("command `{name}` is not available right now"), + }) } /// Is `key` a command with no default shortcut that a key press can't run: no item of the menu @@ -992,9 +1002,10 @@ fn listed_on_its_own(c: &vectorcraft_engine::CommandSpec) -> bool { /// Is UI command `id` (default key `sc`, params doc `params`) listed in Edit › Keyboard Shortcuts /// whether or not an item of the menu bar runs it? It is when it has a default key or a params doc /// of `{}` or `{path…}`. Rename has no default key, and a key press names the selection: it needs -/// no `id`. +/// no `id`. Color Picker… has no default key either, and a key press opens it for the proxy in +/// front. fn ui_listed_on_its_own(id: &str, sc: &str, params: &str) -> bool { - !sc.is_empty() || params.starts_with("{}") || params.starts_with("{path") || id == "ui.rename" + !sc.is_empty() || params.starts_with("{}") || params.starts_with("{path") || id == "ui.rename" || id == "ui.colorPicker" } /// Does a menu bar item run the command with no params, so that it does what its label says and opens @@ -3365,13 +3376,19 @@ mod tests { use vectorcraft_testkit::fixtures::Fixture; let none = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); assert!(!menus::enabled(&none, "edit.findReplace")); - assert_eq!(dimmed(&none, "edit.findReplace"), Err("command `edit.findReplace` is not available right now: no document open".into())); + let why = "command `edit.findReplace` is not available right now: no document open"; + assert_eq!(dimmed(&none, "edit.findReplace", "edit.findReplace").as_deref(), Some(why)); + // A name to show takes the id's place. + let shown = "command `Edit › Find and Replace…` is not available right now: no document open"; + assert_eq!(dimmed(&none, "edit.findReplace", "Edit › Find and Replace…").as_deref(), Some(shown)); let empty = VectorcraftApp::new(Fixture::Empty.session(), crate::Services::default()); for id in ["appearance.addFill", "ui.cropImage"] { assert!(!menus::enabled(&empty, id), "{id}"); assert!(vectorcraft_engine::find_command(id).is_none_or(|c| (c.enabled)(&empty.session).is_ok()), "{id}: the engine gives no reason"); - assert_eq!(dimmed(&empty, id), Err(format!("command `{id}` is not available right now"))); + assert_eq!(dimmed(&empty, id, id), Some(format!("command `{id}` is not available right now"))); } + assert!(menus::enabled(&empty, "edit.findReplace")); + assert_eq!(dimmed(&empty, "edit.findReplace", "edit.findReplace"), None, "not dimmed"); } /// Every command the editor lists, run as a key press runs it on a document with one or with diff --git a/crates/ui-egui/src/shortcuts.rs b/crates/ui-egui/src/shortcuts.rs index d4cde5a873..462adb62d2 100644 --- a/crates/ui-egui/src/shortcuts.rs +++ b/crates/ui-egui/src/shortcuts.rs @@ -970,6 +970,12 @@ fn busy_tool_keys(app: &mut VectorcraftApp, ctx: &egui::Context, view: ViewInfo) for d in digits { let _ = app.session.tool_key(ToolKey::Digit(d), Mods::default(), view); } + // `[` and `]` while the Quick Pen tool draws a piece: the arc being dragged takes the new size. + // The Blob Brush, Eraser and Symbolism tools do not get them during a press, so their size and + // intensity stay as they were when the press began. + if app.session.tool_id() == vectorcraft_tools::quickpen::ID { + tool_brackets(app, ctx, view); + } // Tab, when the tool takes it (the Smart Pen Tool placing an anchor). if app.session.tool_claims_key(ToolKey::Tab, view) && ctx.input_mut(|i| i.consume_key(Modifiers::NONE, Key::Tab)) { let _ = app.session.tool_key(ToolKey::Tab, Mods::default(), view); @@ -1073,9 +1079,14 @@ fn claimed_tool_keys(app: &mut VectorcraftApp, ctx: &egui::Context, view: ViewIn } } } - // `[` and `]` the active tool takes (the Blob Brush's and the Eraser's size, the Symbolism - // tools' diameter, with Shift their intensity). Read as typed, so - // layouts where a bracket takes Option or AltGr count too; `{` and `}` are Shift's. + tool_brackets(app, ctx, view) +} + +/// `[` and `]` the active tool takes (the Blob Brush's and the Eraser's size, the Symbolism tools' +/// diameter, with Shift their intensity). Read as typed, so layouts where a bracket takes Option or +/// AltGr count too; `{` and `}` are Shift's. Did the tool take one? +fn tool_brackets(app: &mut VectorcraftApp, ctx: &egui::Context, view: ViewInfo) -> bool { + let m = ctx.input(|i| i.modifiers); if !(m.command || m.ctrl) { let typed: Vec<(String, ToolKey, bool)> = ctx.input(|i| { i.events diff --git a/crates/ui-egui/src/shortcuts/tests.rs b/crates/ui-egui/src/shortcuts/tests.rs index f29308c4b5..063d63bb14 100644 --- a/crates/ui-egui/src/shortcuts/tests.rs +++ b/crates/ui-egui/src/shortcuts/tests.rs @@ -489,8 +489,8 @@ fn a_shortcut_runs_what_its_menu_item_runs() { /// add-on, Set Corners…, Divide into Dashes, Tangent Circle…, Find Nearest Swatch, the swatch legend, the type /// tools, the select add-on and Select by Link Status…), three "…" items whose menu entry gives /// params, Smart Punctuation…, Edit Custom Dictionary…, Composite Fonts…, Recolor Artwork…, the Edit menu's preset -/// dialogs and Apply SVG Filter…. -const MENU_DIALOG_COMMANDS: [&str; 40] = [ +/// dialogs (Transparency Flattener, Print, PDF, Tracing and Perspective Grid Presets…) and Apply SVG Filter…. +const MENU_DIALOG_COMMANDS: [&str; 41] = [ "object.path.smooth", "object.path.simplify", "object.path.offsetPath", @@ -529,6 +529,7 @@ const MENU_DIALOG_COMMANDS: [&str; 40] = [ "ui.flattenerPresetsDialog", "ui.printPresetsDialog", "ui.pdfPresetsDialog", + "ui.tracingPresetsDialog", "ui.perspectivePresetsDialog", "ui.svgFilterDialog", ]; @@ -1638,6 +1639,45 @@ fn polygonal_lasso_takes_backspace_delete_enter_and_escape_while_a_loop_is_open( assert_eq!(sel.anchors.get(&id).map(|a| a.len()), Some(1), "only the corner inside the loop"); } +/// Color Picker… (`ui.colorPicker`) has no default key. Keyboard Shortcuts lists it, and a key +/// assigned there opens the picker for the proxy in front: with no document open, with nothing +/// selected and with an object selected, and for the stroke while the Stroke proxy is in front, +/// with or without a document open. +#[test] +fn a_key_assigned_to_the_color_picker_opens_it_for_the_proxy_in_front() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + crate::shortcut_editor::sync(&app.ui); + assert_eq!(crate::shortcut_editor::default_command_shortcut("ui.colorPicker"), None); + let listed = app.run("shortcuts.list", json!({"query": "ui.colorPicker"})).unwrap(); + let rows: Vec<_> = listed.as_array().expect("rows").iter().map(|r| r["label"].clone()).collect(); + assert_eq!(rows, [json!("Color Picker…")], "Keyboard Shortcuts lists it"); + app.run("shortcuts.set", json!({"id": "ui.colorPicker", "shortcut": "Cmd+Alt+Shift+F12"})).unwrap(); + crate::shortcut_editor::sync(&app.ui); + let key = || press(Key::F12, Modifiers::COMMAND | Modifiers::ALT | Modifiers::SHIFT); + let opened = |app: &mut VectorcraftApp| { + let stroke = app.ui.dialog.as_ref().filter(|d| d.kind == "colorPicker").map(|d| d.bool("stroke")); + app.ui.dialog = None; + stroke + }; + frame(&mut app, key()); + assert_eq!(opened(&mut app), Some(false), "no document: the fill"); + app.run("paint.toggleActive", json!({"fill": false})).unwrap(); + frame(&mut app, key()); + assert_eq!(opened(&mut app), Some(true), "no document, the Stroke proxy in front: the stroke"); + app.run("paint.toggleActive", json!({"fill": true})).unwrap(); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + frame(&mut app, key()); + assert_eq!(opened(&mut app), Some(false), "nothing selected: the fill"); + let id = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap()["id"].clone(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + frame(&mut app, key()); + assert_eq!(opened(&mut app), Some(false), "an object selected: the fill"); + app.run("paint.toggleActive", json!({})).unwrap(); + frame(&mut app, key()); + assert_eq!(opened(&mut app), Some(true), "the Stroke proxy in front: the stroke"); + crate::shortcut_editor::sync(&crate::state::UiState::default()); +} + /// Binds Show Grid to `chord`, or with `None` leaves every command its default shortcut. fn bind_grid(app: &mut VectorcraftApp, chord: Option<&str>) { app.ui.shortcut_overrides.clear(); @@ -2080,13 +2120,16 @@ fn the_command_search_that_opens_while_enter_is_down_waits_for_a_new_press() { // The empty search lists the recent picks, so the last pick is the highlighted result. app.ui.recent_commands = vec!["paint.swap".into()]; app.ui.palette_open = true; + let before = undo_len(&app); for repeat in 0..4 { held.press(&mut app); assert!(app.ui.palette_open, "repeat {repeat}: it stays open"); + assert_eq!(undo_len(&app), before, "repeat {repeat}: nothing ran"); } held.release(&mut app); held.press(&mut app); assert!(!app.ui.palette_open, "a new press runs the highlighted result"); + assert_eq!(undo_len(&app), before + 1, "Swap Fill and Stroke ran on the rectangle: {}", app.ui.status); } /// Enter on a command search result whose menu item opens a dialog (Create Gradient Mesh…) opens @@ -2237,6 +2280,39 @@ fn brackets_size_the_blob_brush_and_the_eraser() { assert_eq!(app.session.paint.stroke_width, 3.0); } +/// A typed `[` or `]` reaches the Quick Pen tool while a press drags a sharp-corner arc: the arc +/// being dragged takes the new size. +#[test] +fn brackets_size_the_quick_pen_arc_being_dragged() { + use vectorcraft_tools::{PointerEvent, PointerKind}; + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + app.select_tool(vectorcraft_tools::quickpen::ID); + app.session.set_tool_option_cmd(&json!({"tool": "quickPen", "key": "action", "value": "sharpArc"})).unwrap(); + let v = vectorcraft_engine::ViewInfo { smart_guides: false, ..Default::default() }; + app.session.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 300.0), v).unwrap(); + app.session.pointer(&PointerEvent::new(PointerKind::Up, 100.0, 300.0), v).unwrap(); + app.session.pointer(&PointerEvent::new(PointerKind::Down, 280.0, 300.0), v).unwrap(); + app.session.pointer(&PointerEvent::new(PointerKind::Drag, 300.0, 300.0), v).unwrap(); + assert!(app.session.tool_busy()); + let points = |app: &VectorcraftApp| { + let mut v = vec![]; + app.session.doc().unwrap().doc.walk(|n| { + if let Some(pd) = n.path_data() { + v.extend(pd.subpaths.iter().flat_map(|sp| sp.anchors.iter().map(|a| a.p))); + } + }); + v + }; + let before = points(&app); + assert_eq!(before.len(), 3, "the arc being dragged is drawn"); + frame(&mut app, vec![egui::Event::Text("[".into())]); + assert_eq!(app.session.tool_options()["turn"], 165.0); + let after = points(&app); + assert_eq!(after.len(), 3); + assert_ne!(after[1], before[1], "the arc being dragged is drawn again with the new size"); +} + fn remembered_paint_app() -> VectorcraftApp { let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); app.session.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 7886d92a9e..f8bce4e088 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -349,6 +349,19 @@ impl Default for ViewFlags { } } +impl ViewFlags { + /// Whether the ruler guides and guide paths draw: View › Show Guides, unless Trim View hides + /// them while it is on (#8363). `guides` keeps the choice, so they come back as they were. + pub fn guides_shown(&self) -> bool { + self.guides && !self.trim_view + } + + /// Whether the grid draws: View › Show Grid, unless Trim View hides it while it is on (#8363). + pub fn grid_shown(&self) -> bool { + self.grid && !self.trim_view + } +} + /// An open modal dialog. `fields` are string-valued so agents can set them uniformly. #[derive(Clone, Debug, Serialize, Deserialize)] pub struct Dialog { @@ -502,6 +515,18 @@ pub struct UiState { /// starts under the selection at every launch. #[serde(skip)] pub task_bar_place: TaskBarPlace, + /// The Contextual Task Bar's actions (`canvas::TASK_BAR_ACTIONS`) that More Options › Bar + /// Actions has off (`window.taskBar.actions`); none: the bar shows every action it offers. + #[serde(deserialize_with = "crate::canvas::read_hidden_task_bar_actions")] + pub task_bar_hidden_actions: std::collections::BTreeSet, + /// Window › Quick Pen Toolbar: the Quick Pen tool shows its toolbar on the canvas. Hide Toolbar + /// turns it off until the tool is selected again. Not saved. + #[serde(skip, default = "yes")] + pub quick_pen_bar: bool, + /// Where the Quick Pen toolbar was dragged or pinned. Not saved: the toolbar starts beside the + /// drawing at every launch. + #[serde(skip)] + pub quick_pen_bar_place: QuickPenBarPlace, /// The Pathfinder panel's Shape Mode buttons make a compound shape on a click, and give the /// permanent Pathfinder result on Alt-click (off, the default: the other way round). #[serde(default)] @@ -647,6 +672,11 @@ pub struct UiState { pub status_notes: Option<(String, Vec)>, pub palette_open: bool, pub palette_query: String, + /// Set when the palette's shortcut, its command or the search icon opens or closes the palette, + /// so that the palette starts at its first row the next time it is drawn, even when it closed + /// and opened again before then. Not saved. + #[serde(skip)] + pub palette_toggled: bool, /// Screen mode: 0 normal, 1 full screen with menu, 2 full screen, 3 presentation. Not saved: /// the app always starts in Normal Screen Mode, with its menus and panels (#472: a saved /// Presentation Mode came back on restart with no way out). @@ -758,6 +788,10 @@ pub struct UiState { /// Help › Search Commands' Recent Commands list: the ids of the last picks, most recent first. #[serde(default)] pub recent_commands: Vec, + /// How many times each command was picked in Help › Search Commands, which ranks the commands + /// picked most often first among results that match as well. + #[serde(default, deserialize_with = "crate::palette::deserialize_command_uses")] + pub command_uses: crate::palette::CommandUses, /// Families starred in the font menus (the ★ filter shows only these). #[serde(default)] pub favorite_fonts: Vec, @@ -821,7 +855,8 @@ pub struct UiState { /// of an RGB field, `ui.colorPanel`, [`crate::panels::color::deserialize_rgb_percent`]). #[serde(default, deserialize_with = "crate::panels::color::deserialize_rgb_percent")] pub color_rgb_percent: bool, - /// Color Wheel panel: the wheel or the box, the box's channel, and the color vision row + /// Color Wheel panel: the wheel or the box, the box's channel, the slider rows, the + /// out-of-gamut shading and the color vision row /// (`ui.colorWheel`, [`crate::panels::color_wheel::deserialize_settings`]). #[serde(default, deserialize_with = "crate::panels::color_wheel::deserialize_settings")] pub color_wheel: crate::panels::color_wheel::Settings, @@ -1124,6 +1159,25 @@ pub struct ToolbarEdits { pub advanced: Option>, } +/// Where the Quick Pen toolbar sits once its handle has moved it (`window.quickPenToolbar.pin`, +/// `window.quickPenToolbar.reset`). +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct QuickPenBarPlace { + /// More Options › Pin Toolbar Position: the toolbar stays where it is on the canvas instead of + /// following the drawing. + pub pinned: bool, + /// Where a pinned toolbar's top-left corner sits from the canvas's top-left (none when it was + /// pinned before it ever showed, until it is drawn). Unpinning leaves it for the next frame to + /// turn into `offset`. + pub pin_at: Option, + /// Where the toolbar was last drawn, from the canvas's top-left: where pinning holds it. + pub shown_at: Option, + /// How far an unpinned toolbar was dragged from its place, the document (`DocState::uid`) it + /// was moved in, and whether it was beside a path being drawn then (false: resting with no path + /// being drawn). It applies only in that document and that kind of place. + pub offset: Option<(u64, bool, egui::Vec2)>, +} + /// Where the Contextual Task Bar sits once its handle has moved it (`window.taskBar.pin`, /// `window.taskBar.reset`). #[derive(Clone, Copy, Debug, Default, PartialEq)] @@ -1270,6 +1324,9 @@ impl Default for UiState { toolbar_advanced: false, task_bar: true, task_bar_place: TaskBarPlace::default(), + task_bar_hidden_actions: Default::default(), + quick_pen_bar: true, + quick_pen_bar_place: QuickPenBarPlace::default(), shape_modes_compound: false, context_locked: None, context_intertwine: None, @@ -1314,6 +1371,7 @@ impl Default for UiState { status_notes: None, palette_open: false, palette_query: String::new(), + palette_toggled: false, screen_mode: 0, tiled: false, tile_layout: crate::canvas::TileLayout::Grid, @@ -1343,6 +1401,7 @@ impl Default for UiState { recent_files: vec![], recent_fonts: vec![], recent_commands: vec![], + command_uses: Default::default(), favorite_fonts: vec![], engine_prefs: Value::Null, original_editor: Default::default(), diff --git a/crates/ui-egui/src/tests.rs b/crates/ui-egui/src/tests.rs index b37ed0d10c..e0619ddaf7 100644 --- a/crates/ui-egui/src/tests.rs +++ b/crates/ui-egui/src/tests.rs @@ -30,6 +30,7 @@ mod plugins; mod printps; mod printtiling; mod puppetwarp; +mod quickpenbar; mod recolor; mod recovery; pub(super) mod removeanchors; diff --git a/crates/ui-egui/src/tests/quickpenbar.rs b/crates/ui-egui/src/tests/quickpenbar.rs new file mode 100644 index 0000000000..d78423eb6b --- /dev/null +++ b/crates/ui-egui/src/tests/quickpenbar.rs @@ -0,0 +1,348 @@ +//! The Quick Pen toolbar: it shows while the Quick Pen tool is active, its buttons set the tool's +//! action and flip the last sharp-corner arc, it follows the drawing beside the path's last point, +//! and its More Options menu's commands hide it, pin it and reset its place. + +use egui::{Event, PointerButton, Pos2, Rect, vec2}; +use serde_json::json; +use vectorcraft_doc::NodeKind; +use vectorcraft_geom::{Point, SubPath}; +use vectorcraft_tools::{Mods, PointerEvent, PointerKind, ToolKey}; + +use crate::{VectorcraftApp, canvas}; + +fn app() -> VectorcraftApp { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.select_tool("quickPen"); + app +} + +fn context() -> egui::Context { + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + crate::theme::install_fonts(&ctx); + ctx +} + +/// One frame of the canvas; returns the buttons it drew, by name, from the accessibility tree. +fn frame(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec) -> Vec<(String, Rect, bool)> { + frame_in(app, ctx, events, vec2(1000.0, 700.0)) +} + +/// [`frame`] in a window of `size`. +fn frame_in(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec, size: egui::Vec2) -> Vec<(String, Rect, bool)> { + let screen = Rect::from_min_size(Pos2::ZERO, size); + let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), events, ..Default::default() }, |ui| canvas::show(app, ui)); + out.textures_delta.clear(); + let Some(update) = out.platform_output.accesskit_update.as_ref() else { return vec![] }; + update + .nodes + .iter() + .filter(|(_, n)| n.role() == egui::accesskit::Role::Button) + .filter_map(|(_, n)| { + let b = n.bounds()?; + let r = Rect::from_min_max(Pos2::new(b.x0 as f32, b.y0 as f32), Pos2::new(b.x1 as f32, b.y1 as f32)); + Some((n.label()?.to_string(), r, !n.is_disabled())) + }) + .collect() +} + +/// Two frames, for the toolbar's area to settle; returns the second frame's buttons. +fn settle(app: &mut VectorcraftApp, ctx: &egui::Context) -> Vec<(String, Rect, bool)> { + frame(app, ctx, vec![]); + frame(app, ctx, vec![]) +} + +fn bar(ctx: &egui::Context) -> Option { + canvas::quick_pen_bar_rect(ctx) +} + +/// Click the toolbar's button named `name`, which must be enabled. +fn click_button(app: &mut VectorcraftApp, ctx: &egui::Context, name: &str) { + let named = settle(app, ctx); + let (_, r, on) = named.iter().find(|(n, _, _)| n == name).unwrap_or_else(|| panic!("no button named {name:?} in {named:?}")); + assert!(*on, "{name} is enabled"); + let p = r.center(); + let press = |pressed| Event::PointerButton { pos: p, button: PointerButton::Primary, pressed, modifiers: Default::default() }; + frame(app, ctx, vec![Event::PointerMoved(p)]); + frame(app, ctx, vec![press(true)]); + frame(app, ctx, vec![press(false)]); + frame(app, ctx, vec![]); +} + +/// A click of the tool at `x`, `y` in the document. +fn click_doc(app: &mut VectorcraftApp, x: f64, y: f64) { + let v = app.view_info(); + for kind in [PointerKind::Down, PointerKind::Up] { + app.session.pointer(&PointerEvent::new(kind, x, y), v).unwrap(); + } +} + +fn paths(app: &VectorcraftApp) -> Vec { + let mut v = vec![]; + app.session.active().unwrap().doc.walk(|n| { + if let NodeKind::Path { path, .. } = &n.kind { + v.extend(path.subpaths.iter().cloned()); + } + }); + v +} + +fn screen(app: &VectorcraftApp, x: f64, y: f64) -> Pos2 { + app.canvas_xf().unwrap().to_screen(Point::new(x, y)) +} + +fn near(p: Pos2, q: Pos2) { + assert!((p - q).length() < 1.5, "{p:?} is not at {q:?}"); +} + +/// The toolbar shows only with the Quick Pen tool, at the bottom center of the canvas while no path +/// is being drawn; its action buttons set the tool's action without drawing on the canvas under +/// them; Hide Toolbar and Window › Quick Pen Toolbar hide and show it. +#[test] +fn the_toolbar_shows_with_the_tool_and_its_buttons_set_the_action() { + let mut app = app(); + let ctx = context(); + let named = settle(&mut app, &ctx); + let r = bar(&ctx).expect("the toolbar shows with the Quick Pen tool"); + for name in ["Straight Line", "Continuous Arc", "Sharp Corner Arc", "Flip Arc", "More Options"] { + assert!(named.iter().any(|(n, _, _)| n == name), "{name} in {named:?}"); + } + assert!(!named.iter().any(|(n, _, on)| n == "Flip Arc" && *on), "Flip Arc waits for an arc"); + let canvas = app.canvas_xf().unwrap().rect; + assert!((r.center().x - canvas.center().x).abs() < 1.5 && (r.bottom() - (canvas.bottom() - 8.0)).abs() < 1.5, "{r:?} in {canvas:?}"); + + click_button(&mut app, &ctx, "Sharp Corner Arc"); + assert_eq!(app.session.tool_options()["action"], "sharpArc"); + click_button(&mut app, &ctx, "Continuous Arc"); + assert_eq!(app.session.tool_options()["action"], "continuousArc"); + click_button(&mut app, &ctx, "Straight Line"); + assert_eq!(app.session.tool_options()["action"], "line"); + assert!(paths(&app).is_empty(), "a click on the toolbar draws nothing"); + + assert_eq!(app.run("window.quickPenToolbar", json!({})).unwrap(), json!(false)); + assert_eq!(crate::menus::checked(&app, "window.quickPenToolbar", &json!({})), Some(false)); + settle(&mut app, &ctx); + assert!(bar(&ctx).is_none(), "hidden"); + assert_eq!(app.run("window.quickPenToolbar", json!({})).unwrap(), json!(true)); + settle(&mut app, &ctx); + assert!(bar(&ctx).is_some(), "shown again"); + + app.select_tool("pen"); + settle(&mut app, &ctx); + assert!(bar(&ctx).is_none(), "only with the Quick Pen tool"); + + // Hidden, it shows again when the tool is selected again. + app.select_tool("quickPen"); + settle(&mut app, &ctx); + assert_eq!(app.run("window.quickPenToolbar", json!({})).unwrap(), json!(false)); + settle(&mut app, &ctx); + assert!(bar(&ctx).is_none(), "hidden"); + app.select_tool("pen"); + app.select_tool("quickPen"); + settle(&mut app, &ctx); + assert!(bar(&ctx).is_some(), "selecting the tool shows it"); + assert_eq!(crate::menus::checked(&app, "window.quickPenToolbar", &json!({})), Some(true)); + // Selecting it again while it is active shows it too. + app.run("window.quickPenToolbar", json!({})).unwrap(); + settle(&mut app, &ctx); + assert!(bar(&ctx).is_none(), "hidden"); + app.run("tool.select", json!({"tool": "quickPen"})).unwrap(); + settle(&mut app, &ctx); + assert!(bar(&ctx).is_some(), "selected again"); +} + +/// The toolbar hides while a press drags on the canvas, and shows again once it is let go. +#[test] +fn the_toolbar_hides_while_a_press_drags_on_the_canvas() { + let mut app = app(); + let ctx = context(); + // The first click places the path's start; the press that follows drags out a piece. + click_doc(&mut app, 60.0, 60.0); + settle(&mut app, &ctx); + assert!(bar(&ctx).is_some()); + let (a, b) = (screen(&app, 100.0, 100.0), screen(&app, 200.0, 140.0)); + let press = |pos, pressed| Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Default::default() }; + frame(&mut app, &ctx, vec![Event::PointerMoved(a), press(a, true)]); + frame(&mut app, &ctx, vec![Event::PointerMoved(a + (b - a) / 2.0)]); + frame(&mut app, &ctx, vec![Event::PointerMoved(b)]); + assert!(app.session.tool_busy(), "the press reached the tool"); + assert!(bar(&ctx).is_none(), "hidden mid-drag"); + frame(&mut app, &ctx, vec![press(b, false)]); + settle(&mut app, &ctx); + assert!(bar(&ctx).is_some(), "shown after the drag"); +} + +/// A middle-button drag on the canvas (a pan), which the tool takes no press from, hides the toolbar +/// too, and it shows again when the button is let go. +#[test] +fn the_toolbar_hides_while_the_canvas_pans() { + let mut app = app(); + let ctx = context(); + settle(&mut app, &ctx); + assert!(bar(&ctx).is_some()); + let (a, b) = (screen(&app, 100.0, 100.0), screen(&app, 200.0, 140.0)); + let press = |pos, pressed| Event::PointerButton { pos, button: PointerButton::Middle, pressed, modifiers: Default::default() }; + frame(&mut app, &ctx, vec![Event::PointerMoved(a), press(a, true)]); + frame(&mut app, &ctx, vec![Event::PointerMoved(a + (b - a) / 2.0)]); + frame(&mut app, &ctx, vec![Event::PointerMoved(b)]); + assert!(!app.session.tool_busy(), "the tool has no press under way"); + assert!(bar(&ctx).is_none(), "hidden mid-pan"); + frame(&mut app, &ctx, vec![press(b, false)]); + settle(&mut app, &ctx); + assert!(bar(&ctx).is_some(), "shown after the pan"); +} + +/// On a canvas narrower than the toolbar, its controls wrap onto more rows, so every button lies +/// on the canvas. +#[test] +fn the_toolbar_wraps_on_a_narrow_canvas() { + let mut app = app(); + let ctx = context(); + let size = vec2(130.0, 500.0); + frame_in(&mut app, &ctx, vec![], size); + let named = frame_in(&mut app, &ctx, vec![], size); + let canvas = app.canvas_xf().unwrap().rect; + assert!(canvas.width() < 150.0, "{canvas:?}"); + for name in ["Straight Line", "Continuous Arc", "Sharp Corner Arc", "Flip Arc", "More Options"] { + let (_, r, _) = named.iter().find(|(n, _, _)| n == name).unwrap_or_else(|| panic!("{name} in {named:?}")); + assert!(canvas.contains_rect(*r), "{name} at {r:?} is off the canvas {canvas:?}"); + } +} + +/// Flip Arc's command sends C only to the Quick Pen tool: with the Arc tool, which takes C while it +/// drags, it returns false and changes nothing. +#[test] +fn flip_arc_does_nothing_with_another_tool() { + let mut app = app(); + app.select_tool("arc"); + let v = app.view_info(); + app.session.pointer(&PointerEvent::new(PointerKind::Down, 50.0, 50.0), v).unwrap(); + app.session.pointer(&PointerEvent::new(PointerKind::Drag, 150.0, 120.0), v).unwrap(); + assert!(app.session.tool_claims_key(ToolKey::Letter('c'), v), "the Arc tool takes C mid-drag"); + let closed = app.session.tool_options()["closed"].clone(); + assert_eq!(app.run("tool.quickPen.flipArc", json!({})).unwrap(), json!(false)); + assert_eq!(app.session.tool_options()["closed"], closed, "the arc's C was not sent"); +} + +/// While a path is drawn, the toolbar sits 24 points off its last point, on the side the path +/// heads toward; Flip Arc flips the last sharp-corner arc as one undo step and is off after a line; +/// Escape sends the toolbar back to the bottom of the canvas. +#[test] +fn the_toolbar_follows_the_drawing_and_flips_the_last_arc() { + let mut app = app(); + let ctx = context(); + settle(&mut app, &ctx); + let resting = bar(&ctx).unwrap(); + app.run("tool.setOption", json!({"key": "action", "value": "sharpArc"})).unwrap(); + assert_eq!(app.run("tool.quickPen.flipArc", json!({})).unwrap(), json!(false), "no path being drawn"); + click_doc(&mut app, 100.0, 150.0); + click_doc(&mut app, 200.0, 150.0); + // A half circle above the chord, which arrives at (200, 150) heading down: right and below. + let mid = |app: &VectorcraftApp| paths(app)[0].anchors[1].p; + assert!(mid(&app).y < 150.0); + settle(&mut app, &ctx); + near(bar(&ctx).unwrap().min, screen(&app, 200.0, 150.0) + vec2(24.0, 24.0)); + + let undo = app.session.active().unwrap().history.undo.len(); + click_button(&mut app, &ctx, "Flip Arc"); + assert!(mid(&app).y > 150.0, "flipped below the chord"); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1); + + // A line drawn to the left: the toolbar goes to the left of its end, still below it. + app.run("tool.setOption", json!({"key": "action", "value": "line"})).unwrap(); + click_doc(&mut app, 120.0, 150.0); + let named = settle(&mut app, &ctx); + let r = bar(&ctx).unwrap(); + let end = screen(&app, 120.0, 150.0); + near(pos2_of(r.right(), r.top()), end + vec2(-24.0, 24.0)); + assert!(!named.iter().any(|(n, _, on)| n == "Flip Arc" && *on), "Flip Arc is off after a line"); + assert_eq!(app.run("tool.quickPen.flipArc", json!({})).unwrap(), json!(false)); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 2, "the line, and no flip"); + + let v = app.view_info(); + app.session.tool_key(ToolKey::Escape, Mods::default(), v).unwrap(); + settle(&mut app, &ctx); + near(bar(&ctx).unwrap().min, resting.min); +} + +fn pos2_of(x: f32, y: f32) -> Pos2 { + Pos2::new(x, y) +} + +/// The toolbar stays shown while its handle is dragged farther than the toolbar's height, when the +/// press is no longer on it. +#[test] +fn the_toolbar_stays_while_its_handle_drags_far() { + let mut app = app(); + let ctx = context(); + settle(&mut app, &ctx); + let button = |pos, pressed| Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Default::default() }; + let grip = pos2_of(bar(&ctx).unwrap().left() + 10.0, bar(&ctx).unwrap().center().y); + frame(&mut app, &ctx, vec![Event::PointerMoved(grip)]); + frame(&mut app, &ctx, vec![button(grip, true)]); + for k in 1..=6 { + frame(&mut app, &ctx, vec![Event::PointerMoved(grip + vec2(-20.0, -30.0) * k as f32)]); + assert!(bar(&ctx).is_some(), "shown at step {k}"); + } + frame(&mut app, &ctx, vec![button(grip + vec2(-120.0, -180.0), false)]); + settle(&mut app, &ctx); + assert!(bar(&ctx).is_some()); +} + +/// The handle drags the toolbar, which keeps that offset as it follows the drawing, but not in its +/// resting place with no path being drawn; pinned, it stays put; Reset Toolbar Position puts it +/// back beside the drawing, unpinned. +#[test] +fn the_toolbar_drags_pins_and_resets() { + let mut app = app(); + let ctx = context(); + click_doc(&mut app, 100.0, 100.0); + click_doc(&mut app, 150.0, 100.0); + settle(&mut app, &ctx); + let beside = |app: &VectorcraftApp, x: f64, y: f64| screen(app, x, y) + vec2(24.0, 24.0); + near(bar(&ctx).unwrap().min, beside(&app, 150.0, 100.0)); + let button = |pos, pressed| Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Default::default() }; + let grip = pos2_of(bar(&ctx).unwrap().left() + 10.0, bar(&ctx).unwrap().center().y); + let by = vec2(30.0, 40.0); + frame(&mut app, &ctx, vec![Event::PointerMoved(grip)]); + frame(&mut app, &ctx, vec![button(grip, true)]); + frame(&mut app, &ctx, vec![Event::PointerMoved(grip + by)]); + frame(&mut app, &ctx, vec![button(grip + by, false)]); + settle(&mut app, &ctx); + near(bar(&ctx).unwrap().min, beside(&app, 150.0, 100.0) + by); + assert_eq!(paths(&app)[0].anchors.len(), 2, "dragging the handle draws nothing"); + + click_doc(&mut app, 200.0, 100.0); + settle(&mut app, &ctx); + near(bar(&ctx).unwrap().min, beside(&app, 200.0, 100.0) + by); + + // A drag made beside the drawing does not move the resting toolbar. + let resting = { + let canvas = app.canvas_xf().unwrap().rect.shrink(8.0); + let r = bar(&ctx).unwrap(); + Pos2::new(canvas.center().x - r.width() / 2.0, canvas.bottom() - r.height()) + }; + let v = app.view_info(); + app.session.tool_key(ToolKey::Escape, Mods::default(), v).unwrap(); + settle(&mut app, &ctx); + near(bar(&ctx).unwrap().min, resting); + // A new path, away from the first one's ends. + click_doc(&mut app, 100.0, 200.0); + click_doc(&mut app, 200.0, 200.0); + settle(&mut app, &ctx); + near(bar(&ctx).unwrap().min, beside(&app, 200.0, 200.0) + by); + + assert_eq!(app.run("window.quickPenToolbar.pin", json!({})).unwrap(), json!(true)); + assert_eq!(crate::menus::checked(&app, "window.quickPenToolbar.pin", &json!({})), Some(true)); + let pinned = bar(&ctx).unwrap().min; + click_doc(&mut app, 250.0, 200.0); + settle(&mut app, &ctx); + near(bar(&ctx).unwrap().min, pinned); + assert!(app.run("window.quickPenToolbar.pin", json!({"pinned": "yes"})).is_err()); + + app.run("window.quickPenToolbar.reset", json!({})).unwrap(); + assert!(!app.ui.quick_pen_bar_place.pinned); + settle(&mut app, &ctx); + near(bar(&ctx).unwrap().min, beside(&app, 250.0, 200.0)); +} diff --git a/crates/ui-egui/src/tests/taskbar.rs b/crates/ui-egui/src/tests/taskbar.rs index bc4734db5a..6caf92cc81 100644 --- a/crates/ui-egui/src/tests/taskbar.rs +++ b/crates/ui-egui/src/tests/taskbar.rs @@ -744,6 +744,148 @@ fn the_shape_properties_popup_keeps_its_corner_dropdown() { assert!(!kinds.is_empty() && kinds.iter().all(|k| *k == vectorcraft_geom::shapes::CornerKind::Chamfer), "{kinds:?}"); } +/// A rectangle's Corner menu in the popup sets the kind of all four corners in one undo step while +/// Corner Radius is linked; picking the kind they already have adds no step. Unlinked, each +/// corner's menu sets that corner alone. +#[test] +fn the_shape_properties_popup_changes_a_rectangle_corner_type() { + use vectorcraft_geom::shapes::CornerKind::{Chamfer, Round}; + let mut app = app(); + app.run("tool.select", json!({"tool": "selection"})).unwrap(); + app.run("prefs.set", json!({"key": "singleCornerRadius", "value": true})).unwrap(); + let rect = id(app.run("shape.rectangle", json!({"x": 40, "y": 40, "width": 80, "height": 60, "radius": 10})).unwrap()); + select(&mut app, &[rect]); + let kinds = |app: &VectorcraftApp| match live(app, rect) { + vectorcraft_doc::LiveShape::Rectangle { kinds, radii, .. } => (kinds, radii), + l => panic!("{l:?}"), + }; + let steps = |app: &VectorcraftApp| app.session.active().unwrap().history.undo.len(); + let (ctx, texts) = click_lock_slot(&mut app); + let click = |app: &mut VectorcraftApp, p: Pos2| { + let press = |pressed| Event::PointerButton { pos: p, button: PointerButton::Primary, pressed, modifiers: Default::default() }; + frame(app, &ctx, vec![Event::PointerMoved(p), press(true), press(false)]); + frame(app, &ctx, vec![]) + }; + // The open list's entry for `name`, drawn after the closed menu that may show the same name. + let entry = |texts: &[(String, Rect)], name: &str| texts.iter().rev().find(|(t, _)| t == name).map(|(_, r)| r.center()).unwrap(); + let before = steps(&app); + let texts = click(&mut app, at(&texts, "Round")); + let texts = click(&mut app, entry(&texts, "Chamfer")); + assert_eq!(kinds(&app), ([Chamfer; 4], [10.0; 4]), "all four corners, radii kept"); + assert_eq!(steps(&app), before + 1, "one undo step"); + let texts = click(&mut app, at(&texts, "Chamfer")); + // The list is open: its Chamfer row shows as well as the closed menu's, and the pick closes it. + assert_eq!(texts.iter().filter(|(t, _)| t == "Chamfer").count(), 2, "{texts:?}"); + assert!(texts.iter().any(|(t, _)| t == "Inverted Round"), "{texts:?}"); + let texts = click(&mut app, entry(&texts, "Chamfer")); + assert!(!texts.iter().any(|(t, _)| t == "Inverted Round"), "the pick closes the list: {texts:?}"); + assert_eq!(steps(&app), before + 1, "the same kind adds no undo step"); + + app.run("prefs.set", json!({"key": "singleCornerRadius", "value": false})).unwrap(); + let texts = frame(&mut app, &ctx, vec![]); + assert_eq!(texts.iter().filter(|(t, _)| t == "Chamfer").count(), 4, "{texts:?}"); + // The first menu is the top left corner's. + let texts = click(&mut app, at(&texts, "Chamfer")); + click(&mut app, entry(&texts, "Round")); + assert_eq!(kinds(&app), ([Round, Chamfer, Chamfer, Chamfer], [10.0; 4])); + assert_eq!(steps(&app), before + 2); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(kinds(&app).0, [Chamfer; 4]); +} + +/// One Transform panel frame `width` points wide: the texts drawn, with their rectangles. +fn panel_frame(app: &mut VectorcraftApp, ctx: &egui::Context, width: f32, events: Vec) -> Vec<(String, Rect)> { + let screen = Rect::from_min_size(Pos2::ZERO, vec2(width, 700.0)); + let input = egui::RawInput { screen_rect: Some(screen), events, ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| crate::panels::transform::show(app, ui)); + out.textures_delta.clear(); + shapes_text(&out.shapes.iter().map(|c| c.shape.clone()).collect::>()) +} + +/// With several rectangles selected, the linked Corner menu sets the kind on every corner of each +/// of them, also when the rectangle the panel shows already has it, and leaves a selected polygon +/// as it is. +#[test] +fn the_linked_corner_menu_sets_every_selected_rectangle() { + use vectorcraft_geom::shapes::CornerKind::{Chamfer, Round}; + let mut app = app(); + app.run("prefs.set", json!({"key": "singleCornerRadius", "value": true})).unwrap(); + let a = id(app.run("shape.rectangle", json!({"x": 20, "y": 20, "width": 80, "height": 60, "radius": 8})).unwrap()); + let b = id(app.run("shape.rectangle", json!({"x": 200, "y": 20, "width": 80, "height": 60, "radius": 8})).unwrap()); + let polygon = id(app.run("shape.polygon", json!({"cx": 200, "cy": 200, "radius": 40, "sides": 6})).unwrap()); + app.run("object.setLiveShape", json!({"ids": [a], "kind": "chamfer"})).unwrap(); + select(&mut app, &[a, b, polygon]); + let kinds = |app: &VectorcraftApp, id: u64| match live(app, id) { + vectorcraft_doc::LiveShape::Rectangle { kinds, .. } => kinds, + l => panic!("{l:?}"), + }; + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let click = |app: &mut VectorcraftApp, p: Pos2| { + let press = |pressed| Event::PointerButton { pos: p, button: PointerButton::Primary, pressed, modifiers: Default::default() }; + panel_frame(app, &ctx, 300.0, vec![Event::PointerMoved(p), press(true), press(false)]); + panel_frame(app, &ctx, 300.0, vec![]) + }; + panel_frame(&mut app, &ctx, 300.0, vec![]); + let texts = panel_frame(&mut app, &ctx, 300.0, vec![]); + let steps = app.session.active().unwrap().history.undo.len(); + let texts = click(&mut app, at(&texts, "Chamfer")); + let entry = texts.iter().rev().find(|(t, _)| t == "Chamfer").map(|(_, r)| r.center()).unwrap(); + click(&mut app, entry); + assert_eq!((kinds(&app, a), kinds(&app, b)), ([Chamfer; 4], [Chamfer; 4])); + let vectorcraft_doc::LiveShape::Polygon { kinds: sides, .. } = live(&app, polygon) else { panic!("not a polygon") }; + assert!(sides.iter().all(|k| *k == Round), "the polygon keeps its corners: {sides:?}"); + assert_eq!(app.session.active().unwrap().history.undo.len(), steps + 1, "one undo step"); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(kinds(&app, b), [Round; 4]); +} + +/// Unlinked, a corner's radius field rounds that corner of each selected rectangle and leaves a +/// selected polygon as it is. +#[test] +fn an_unlinked_corner_radius_leaves_other_selected_shapes() { + let mut app = app(); + app.run("prefs.set", json!({"key": "singleCornerRadius", "value": false})).unwrap(); + let rect = id(app.run("shape.rectangle", json!({"x": 20, "y": 20, "width": 80, "height": 60, "radius": 7})).unwrap()); + let polygon = id(app.run("shape.polygon", json!({"cx": 200, "cy": 200, "radius": 40, "sides": 6})).unwrap()); + select(&mut app, &[rect, polygon]); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + panel_frame(&mut app, &ctx, 300.0, vec![]); + let texts = panel_frame(&mut app, &ctx, 300.0, vec![]); + // The top left corner's field is the first that shows the radius. + let p = at(&texts, "7 pt"); + let press = |pressed| Event::PointerButton { pos: p, button: PointerButton::Primary, pressed, modifiers: Default::default() }; + panel_frame(&mut app, &ctx, 300.0, vec![Event::PointerMoved(p), press(true), press(false)]); + panel_frame(&mut app, &ctx, 300.0, vec![]); + panel_frame(&mut app, &ctx, 300.0, vec![Event::Text("15".into())]); + let enter = Event::Key { key: egui::Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }; + panel_frame(&mut app, &ctx, 300.0, vec![enter]); + panel_frame(&mut app, &ctx, 300.0, vec![]); + let vectorcraft_doc::LiveShape::Rectangle { radii, .. } = live(&app, rect) else { panic!("not a rectangle") }; + assert_eq!(radii, [15.0, 7.0, 7.0, 7.0]); + let vectorcraft_doc::LiveShape::Polygon { radii, .. } = live(&app, polygon) else { panic!("not a polygon") }; + assert!(radii.iter().all(|r| *r == 0.0), "the polygon keeps its corners: {radii:?}"); +} + +/// Unlinked, the four corner rows keep their Corner menus inside a panel at its narrowest. +#[test] +fn the_unlinked_corner_menus_fit_a_narrow_panel() { + let mut app = app(); + app.run("prefs.set", json!({"key": "singleCornerRadius", "value": false})).unwrap(); + let rect = id(app.run("shape.rectangle", json!({"x": 20, "y": 20, "width": 80, "height": 60, "radius": 8})).unwrap()); + app.run("object.setLiveShape", json!({"ids": [rect], "kind": "invertedRound"})).unwrap(); + select(&mut app, &[rect]); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let width = 220.0; + panel_frame(&mut app, &ctx, width, vec![]); + let texts = panel_frame(&mut app, &ctx, width, vec![]); + let menus: Vec<_> = texts.iter().filter(|(t, _)| t.starts_with("Inverted")).collect(); + assert_eq!(menus.len(), 4, "{texts:?}"); + assert!(menus.iter().all(|(_, r)| r.right() <= width), "{menus:?}"); +} + /// Every other selection keeps Lock: a plain closed path, a star (a plain path), a path with live /// corners, a group and several objects. The Direct Selection tool keeps it for a basic shape. #[test] @@ -1573,3 +1715,469 @@ fn the_task_bar_follows_edits_and_undo() { assert!(has(&texts, "10 pt") && !has(&texts, "20 pt"), "{texts:?}"); assert!(!locked(&app, rect), "the button doesn't lock the shape"); } + +/// Turns the bar's action or chip `action` on or off (`window.taskBar.actions`). +fn show_action(app: &mut VectorcraftApp, action: &str, visible: bool) { + let r = app.run("window.taskBar.actions", json!({"action": action, "visible": visible})).unwrap(); + assert_eq!(r, json!({"action": action, "visible": visible})); +} + +/// An action turned off in Bar Actions leaves the bar for every selection that offers it, and its +/// Object menu command stays enabled. Toggled, it comes back. +#[test] +fn an_action_turned_off_leaves_the_bar_and_stays_in_its_menu() { + let mut app = app(); + app.run("tool.select", json!({"tool": "selection"})).unwrap(); + let line = id(app.run("shape.line", json!({"x1": 50, "y1": 50, "x2": 200, "y2": 120})).unwrap()); + select(&mut app, &[line]); + let (_, texts) = bar(&mut app); + assert!(has(&texts, "Offset Path") && has(&texts, "Join"), "{texts:?}"); + show_action(&mut app, "offsetPath", false); + assert_eq!(crate::menus::checked(&app, "window.taskBar.actions", &json!({"action": "offsetPath"})), Some(false)); + assert_eq!(crate::menus::checked(&app, "window.taskBar.actions", &json!({"action": "join"})), Some(true)); + let (_, texts) = bar(&mut app); + assert!(!has(&texts, "Offset Path"), "{texts:?}"); + assert!(has(&texts, "Join") && has(&texts, "Simplify") && has(&texts, "Edit Path"), "the other actions stay: {texts:?}"); + assert!(crate::menus::enabled(&app, "object.path.offsetPath"), "Object › Path › Offset Path… still runs"); + + // Another selection that offers the same action leaves it out too: a rectangle. + let rect = id(app.run("shape.rectangle", json!({"x": 220, "y": 40, "width": 80, "height": 60})).unwrap()); + select(&mut app, &[rect]); + let (_, texts) = bar(&mut app); + assert!(!has(&texts, "Offset Path") && has(&texts, "Edit Path"), "{texts:?}"); + + // Toggled (no `visible`), it shows again. + assert_eq!(app.run("window.taskBar.actions", json!({"action": "offsetPath"})).unwrap(), json!({"action": "offsetPath", "visible": true})); + let (_, texts) = bar(&mut app); + assert!(has(&texts, "Offset Path"), "{texts:?}"); + // A `visible` of null counts as omitted and toggles too. + let r = app.run("window.taskBar.actions", json!({"action": "offsetPath", "visible": null})).unwrap(); + assert_eq!(r, json!({"action": "offsetPath", "visible": false})); +} + +/// The Fill, Stroke, Recolor Artwork, Lock and Shape Properties chips each turn off on their own: +/// Lock off leaves a basic shape's Shape Properties, and Shape Properties off leaves Lock. +#[test] +fn a_chip_turned_off_leaves_the_bar() { + let mut app = app(); + app.run("tool.select", json!({"tool": "selection"})).unwrap(); + let rect = id(app.run("shape.rectangle", json!({"x": 40, "y": 40, "width": 80, "height": 60})).unwrap()); + let line = id(app.run("shape.line", json!({"x1": 50, "y1": 150, "x2": 200, "y2": 220})).unwrap()); + select(&mut app, &[rect]); + let names = |app: &mut VectorcraftApp| buttons(app).1.into_iter().map(|(n, _)| n).collect::>(); + let shown = names(&mut app); + for name in ["Fill", "Stroke", "Shape Properties"] { + assert!(shown.iter().any(|n| n == name), "{name}: {shown:?}"); + } + show_action(&mut app, "fill", false); + show_action(&mut app, "lock", false); + let shown = names(&mut app); + assert!(!shown.iter().any(|n| n == "Fill"), "{shown:?}"); + assert!(shown.iter().any(|n| n == "Stroke") && shown.iter().any(|n| n == "Shape Properties"), "{shown:?}"); + select(&mut app, &[line]); + let shown = names(&mut app); + assert!(!shown.iter().any(|n| n.starts_with("Lock")), "Lock is off: {shown:?}"); + show_action(&mut app, "lock", true); + show_action(&mut app, "shapeProperties", false); + let shown = names(&mut app); + assert!(shown.iter().any(|n| n.starts_with("Lock")), "Lock is on again: {shown:?}"); + select(&mut app, &[rect]); + let shown = names(&mut app); + assert!(!shown.iter().any(|n| n == "Shape Properties"), "{shown:?}"); +} + +/// Reset Bar Actions shows every action and chip again and returns the ids it showed. +#[test] +fn reset_bar_actions_shows_every_action_again() { + let mut app = app(); + app.run("tool.select", json!({"tool": "selection"})).unwrap(); + let line = id(app.run("shape.line", json!({"x1": 50, "y1": 50, "x2": 200, "y2": 120})).unwrap()); + select(&mut app, &[line]); + show_action(&mut app, "simplify", false); + show_action(&mut app, "duplicate", false); + show_action(&mut app, "stroke", false); + let (_, texts) = bar(&mut app); + assert!(!has(&texts, "Simplify") && !has(&texts, "Duplicate"), "{texts:?}"); + assert_eq!(app.run("window.taskBar.resetActions", json!({})).unwrap(), json!(["duplicate", "simplify", "stroke"])); + assert!(app.ui.task_bar_hidden_actions.is_empty()); + let (_, texts) = bar(&mut app); + assert!(has(&texts, "Simplify") && has(&texts, "Duplicate"), "{texts:?}"); + assert_eq!(app.run("window.taskBar.resetActions", json!({})).unwrap(), json!([]), "nothing left to show"); +} + +/// Each of the bar's actions and chips has its own id, and no two actions run the same command +/// with the same tool. +#[test] +fn bar_action_ids_are_distinct() { + let ids: Vec<&str> = canvas::TASK_BAR_ACTIONS.iter().map(|a| a.0).chain(canvas::TASK_BAR_CHIPS).collect(); + let set: std::collections::BTreeSet<&str> = ids.iter().copied().collect(); + assert_eq!(set.len(), ids.len(), "{ids:?}"); + let runs: std::collections::BTreeSet<(&str, Option<&str>)> = canvas::TASK_BAR_ACTIONS.iter().map(|a| (a.1, a.2)).collect(); + assert_eq!(runs.len(), canvas::TASK_BAR_ACTIONS.len()); +} + +/// An action the bar does not have, a missing one, or a `visible` that is not true, false or null is +/// an error and changes nothing. +#[test] +fn bar_actions_refuse_bad_params() { + let mut app = app(); + show_action(&mut app, "group", false); + for p in [json!({"action": "teleport"}), json!({}), json!({"action": 3}), json!({"action": "unite", "visible": "yes"})] { + assert!(app.run("window.taskBar.actions", p.clone()).is_err(), "{p}"); + } + let err = app.run("window.taskBar.actions", json!({"action": "teleport"})).unwrap_err(); + assert!(err.contains("imageTrace") && err.contains("shapeProperties"), "{err}"); + assert_eq!(app.ui.task_bar_hidden_actions.iter().map(String::as_str).collect::>(), ["group"]); + assert_eq!(crate::menus::checked(&app, "window.taskBar.actions", &json!({"action": "teleport"})), Some(false)); +} + +/// The actions that are off are kept with the preferences. Ids the bar does not have are dropped, +/// a value that is not a list turns none off, and older preferences without it show every action. +#[test] +fn bar_actions_are_kept_with_the_preferences() { + let mut app = app(); + show_action(&mut app, "unite", false); + show_action(&mut app, "recolor", false); + let mut prefs = serde_json::to_value(&app.ui).unwrap(); + let back: crate::state::UiState = serde_json::from_value(prefs.clone()).unwrap(); + let ids = |ui: &crate::state::UiState| ui.task_bar_hidden_actions.iter().cloned().collect::>(); + assert_eq!(ids(&back), ["recolor", "unite"]); + prefs["task_bar_hidden_actions"] = json!(["unite", "teleport", 7, "fill"]); + assert_eq!(ids(&serde_json::from_value(prefs.clone()).unwrap()), ["fill", "unite"], "ids the bar does not have are dropped"); + prefs["task_bar_hidden_actions"] = json!("unite"); + assert!(ids(&serde_json::from_value(prefs.clone()).unwrap()).is_empty(), "a value that is not a list turns none off"); + prefs.as_object_mut().unwrap().remove("task_bar_hidden_actions"); + assert!(ids(&serde_json::from_value(prefs).unwrap()).is_empty(), "older preferences show every action"); + app.run("window.taskBar.resetActions", json!({})).unwrap(); + assert_eq!(serde_json::to_value(&app.ui).unwrap()["task_bar_hidden_actions"], json!([]), "none off"); +} + +/// More Options › Bar Actions lists the actions and chips the bar offers for the selection, each +/// checked while it shows; a click turns one off, it is listed unchecked after that, and a click on +/// Reset Bar Actions shows it again. +#[test] +fn more_options_bar_actions_turns_an_action_off_and_on() { + let mut app = app(); + app.run("tool.select", json!({"tool": "selection"})).unwrap(); + let line = id(app.run("shape.line", json!({"x1": 50, "y1": 50, "x2": 200, "y2": 120})).unwrap()); + select(&mut app, &[line]); + let more = buttons(&mut app).1.into_iter().find(|(n, _)| n == "More Options").expect("More Options").1.center(); + let (ctx, _) = bar(&mut app); + let click_at = |app: &mut VectorcraftApp, p: Pos2| { + let press = |pressed| Event::PointerButton { pos: p, button: PointerButton::Primary, pressed, modifiers: Default::default() }; + frame(app, &ctx, vec![Event::PointerMoved(p)]); + frame(app, &ctx, vec![press(true)]); + frame(app, &ctx, vec![press(false)]); + frame(app, &ctx, vec![]) + }; + let texts = click_at(&mut app, more); + let item = at(&texts, " Bar Actions"); + frame(&mut app, &ctx, vec![Event::PointerMoved(item)]); + let texts = frame(&mut app, &ctx, vec![]); + for name in ["✓ Join", "✓ Edit Path", "✓ Offset Path", "✓ Simplify", "✓ Duplicate", "✓ Fill", "✓ Stroke", "✓ Lock"] { + assert!(has(&texts, name), "{name}: {texts:?}"); + } + assert!(has(&texts, " Reset Bar Actions"), "{texts:?}"); + let offset = at(&texts, "✓ Offset Path"); + // Along the submenu's row first, so the pointer stays over the menu on its way. + frame(&mut app, &ctx, vec![Event::PointerMoved(Pos2::new(offset.x, item.y))]); + click_at(&mut app, offset); + assert!(app.ui.task_bar_hidden_actions.contains("offsetPath"), "{:?}", app.ui.task_bar_hidden_actions); + let (_, texts) = bar(&mut app); + assert!(!has(&texts, "Offset Path") && has(&texts, "Simplify"), "{texts:?}"); + + // Opened again, Bar Actions lists it unchecked; Reset Bar Actions turns it on. + let more = buttons(&mut app).1.into_iter().find(|(n, _)| n == "More Options").expect("More Options").1.center(); + let (ctx, _) = bar(&mut app); + let click_at = |app: &mut VectorcraftApp, p: Pos2| { + let press = |pressed| Event::PointerButton { pos: p, button: PointerButton::Primary, pressed, modifiers: Default::default() }; + frame(app, &ctx, vec![Event::PointerMoved(p)]); + frame(app, &ctx, vec![press(true)]); + frame(app, &ctx, vec![press(false)]); + frame(app, &ctx, vec![]) + }; + let texts = click_at(&mut app, more); + let item = at(&texts, " Bar Actions"); + let reset = at(&texts, " Reset Bar Actions"); + frame(&mut app, &ctx, vec![Event::PointerMoved(item)]); + let texts = frame(&mut app, &ctx, vec![]); + assert!(has(&texts, " Offset Path") && has(&texts, "✓ Simplify"), "{texts:?}"); + // Back along the menu's column to Reset Bar Actions, closing the submenu on the way. + frame(&mut app, &ctx, vec![Event::PointerMoved(Pos2::new(item.x, reset.y))]); + click_at(&mut app, reset); + assert!(app.ui.task_bar_hidden_actions.is_empty(), "{:?}", app.ui.task_bar_hidden_actions); + let (_, texts) = bar(&mut app); + assert!(has(&texts, "Offset Path"), "{texts:?}"); +} + +/// On a canvas too short for every action, More Options lists the ones that don't fit; an action +/// turned off in Bar Actions is listed neither there nor on the bar, and the others still are. +#[test] +fn an_action_turned_off_is_not_listed_in_more_options() { + let mut app = app(); + app.run("tool.select", json!({"tool": "selection"})).unwrap(); + let a = id(app.run("shape.rectangle", json!({"x": 40, "y": 40, "width": 120, "height": 100})).unwrap()); + let b = id(app.run("shape.ellipse", json!({"x": 70, "y": 60, "width": 50, "height": 50})).unwrap()); + select(&mut app, &[a, b]); + let size = vec2(160.0, 150.0); + // More Options' list, opened on a new context, and what the bar itself shows. + let listed = |app: &mut VectorcraftApp| { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let (on_bar, r, _) = bar_texts_on_screen(app, &ctx, size, 3); + let more = r.min + vec2(9.0 + 4.0 + 6.0 + 15.0, 7.0 + 15.0); + let press = |pressed| Event::PointerButton { pos: more, button: PointerButton::Primary, pressed, modifiers: Default::default() }; + let screen = Rect::from_min_size(Pos2::ZERO, size); + let mut texts = vec![]; + for events in [vec![Event::PointerMoved(more)], vec![press(true)], vec![press(false)], vec![]] { + let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), events, ..Default::default() }, |ui| canvas::show(app, ui)); + out.textures_delta.clear(); + texts = shapes_text(&out.shapes.iter().map(|c| c.shape.clone()).collect::>()); + } + assert!(texts.iter().any(|(t, _)| t.trim() == "Hide Bar"), "More Options opens: {texts:?}"); + let names = |t: &[(String, Rect)]| t.iter().map(|(t, _)| t.trim().to_string()).collect::>(); + (names(&on_bar), names(&texts)) + }; + let (on_bar, menu) = listed(&mut app); + for label in ["Unite", "Duplicate"] { + assert!(!on_bar.iter().any(|t| t == label) && menu.iter().any(|t| t == label), "{label} in More Options: {menu:?}"); + } + show_action(&mut app, "unite", false); + let (on_bar, menu) = listed(&mut app); + assert!(!on_bar.iter().any(|t| t == "Unite") && !menu.iter().any(|t| t == "Unite"), "{on_bar:?} {menu:?}"); + assert!(on_bar.iter().chain(&menu).any(|t| t == "Duplicate"), "Duplicate is still offered: {on_bar:?} {menu:?}"); +} + +/// Every action and chip the bar offers, for every kind of selection and tool, has an id in Bar +/// Actions, and with all of them turned off the bar shows none of them but still shows, with More +/// Options. That covers Connect and Join (both `join`), the actions matched by the tool they switch +/// to (`editPath`, `drawPencil`, `smoothToolOptions`), the Smooth tool's Fidelity, Dynamic Text, +/// an Image Trace object's Expand, the Type tool's Fill with type selected and while it edits +/// type, and the Artboard tool's actions. +#[test] +fn every_action_the_bar_offers_can_be_turned_off() { + let dir = crate::tests_folder::Folder::new("ui-taskbar-actions"); + let line = |app: &mut VectorcraftApp| { + id(app.run("path.create", json!({"anchors": [{"x": 50, "y": 200}, {"x": 150, "y": 80}, {"x": 250, "y": 200}]})).unwrap()) + }; + let two = |app: &mut VectorcraftApp| { + let a = id(app.run("shape.rectangle", json!({"x": 40, "y": 40, "width": 120, "height": 100})).unwrap()); + let b = id(app.run("shape.ellipse", json!({"x": 70, "y": 60, "width": 50, "height": 50})).unwrap()); + select(app, &[a, b]); + }; + type Setup<'a> = Box; + let cases: Vec<(&str, Setup, &[&str])> = vec![ + ( + "an open path", + Box::new(|app| { + let l = line(app); + select(app, &[l]); + }), + &["join", "editPath", "offsetPath", "simplify", "duplicate"], + ), + ( + "a path the Direct Selection tool selects whole", + Box::new(|app| { + let l = line(app); + select(app, &[l]); + app.run("tool.select", json!({"tool": "directSelection"})).unwrap(); + }), + &["join", "convertToCorner", "convertToSmooth", "simplify", "smooth", "duplicate"], + ), + ( + "anchors picked out", + Box::new(|app| { + let l = line(app); + app.run("tool.select", json!({"tool": "directSelection"})).unwrap(); + app.run("select.anchors", json!({"id": l, "anchors": [[0, 1]]})).unwrap(); + }), + &["removeAnchorPoints", "join", "cutPath", "convertToCorner", "convertToSmooth"], + ), + ("two paths", Box::new(|app| two(app)), &["group", "unite", "duplicate"]), + ( + "a group", + Box::new(|app| { + two(app); + app.run("object.group", json!({})).unwrap(); + }), + &["ungroup", "isolate", "duplicate"], + ), + ( + "a compound path", + Box::new(|app| { + two(app); + app.run("object.compoundPath.make", json!({})).unwrap(); + }), + &["editPath", "releaseCompoundPath", "duplicate"], + ), + ( + "a clipping group", + Box::new(|app| { + two(app); + let g = id(app.run("object.clippingMask.make", json!({})).unwrap()); + select(app, &[g]); + }), + &["editClippingPath", "releaseClippingMask", "duplicate"], + ), + ( + "point type", + Box::new(|app| { + let t = id(app.run("text.create", json!({"x": 60, "y": 80, "text": "Hello"})).unwrap()); + select(app, &[t]); + }), + &["createOutlines", "convertToAreaType", "dynamicText", "fill", "stroke", "lock"], + ), + ( + "the Type tool with type selected", + Box::new(|app| { + let t = id(app.run("text.create", json!({"x": 60, "y": 80, "text": "Hello"})).unwrap()); + select(app, &[t]); + app.run("tool.select", json!({"tool": "type"})).unwrap(); + }), + &["fill"], + ), + ( + "the Type tool editing type", + Box::new(|app| { + edited_type(app, "type"); + }), + &["fill"], + ), + ( + "area type", + Box::new(|app| { + let t = id(app.run("text.create", json!({"x": 60, "y": 80, "text": "Hello"})).unwrap()); + select(app, &[t]); + app.run("type.convertToAreaType", json!({})).unwrap(); + select(app, &[t]); + }), + &["createOutlines", "convertToPointType", "dynamicText"], + ), + ( + "type on a closed path", + Box::new(|app| { + let circle = id(app.run("path.create", json!({"d": "M100 300 A100 100 0 1 1 300 300 A100 100 0 1 1 100 300 Z"})).unwrap()); + let t = id(app.run("text.createInPath", json!({"path": circle, "mode": "onPath", "text": "Round", "at": [90, 300]})).unwrap()); + select(app, &[t]); + }), + &["createOutlines", "typeOnPathOptions", "centerOnTop", "centerOnBottom", "dynamicText"], + ), + ( + "an Image Trace object", + Box::new(|app| { + place_image(app, &dir); + app.run("imageTrace.make", json!({"params": {}})).unwrap(); + }), + &["expand", "duplicate"], + ), + ( + "an image", + Box::new(|app| { + place_image(app, &dir); + }), + &["imageTrace", "cropImage", "removeBackground", "duplicate"], + ), + ( + "an image with a path", + Box::new(|app| { + let img = place_image(app, &dir); + let r = id(app.run("shape.rectangle", json!({"x": 40, "y": 40, "width": 80, "height": 60})).unwrap()); + select(app, &[img, r]); + }), + &["group", "makeClippingMask", "duplicate"], + ), + ( + "a blank canvas", + Box::new(|app| { + let board = app.session.active().unwrap().doc.artboards[0].rect; + bar(app); + let view = app.view_mut().unwrap(); + (view.center, view.zoom) = (board.center(), 0.5); + }), + &["drawPencil", "placeImage"], + ), + ( + "a shape tool after drawing", + Box::new(|app| { + drag_with(app, "rectangle", (60.0, 60.0), (120.0, 120.0)); + }), + &["editPath"], + ), + ( + "the Smooth tool", + Box::new(|app| { + let e = id(app.run("shape.ellipse", json!({"x": 60, "y": 60, "width": 120, "height": 80})).unwrap()); + select(app, &[e]); + app.run("tool.select", json!({"tool": "smooth"})).unwrap(); + }), + &["fidelity", "smoothToolOptions"], + ), + ( + "the Artboard tool", + Box::new(|app| { + app.run("artboard.new", json!({"x": 420, "y": 0, "width": 200, "height": 200})).unwrap(); + app.run("tool.select", json!({"tool": "artboard"})).unwrap(); + }), + &["resizeArtboard", "duplicateArtboards", "rearrangeArtboards", "exportArtboards"], + ), + ]; + for (case, setup, expected) in cases { + let mut app = app(); + app.run("tool.select", json!({"tool": "selection"})).unwrap(); + setup(&mut app); + let (ctx, _) = bar(&mut app); + let offered: Vec<(&str, Option<&str>)> = canvas::task_bar_offered(&ctx).into_iter().map(|(label, action, _)| (label, action)).collect(); + assert!(canvas::task_bar_rect(&ctx).is_some() && !offered.is_empty(), "{case}: the bar shows actions"); + for (label, action) in &offered { + assert!(action.is_some(), "{case}: {label} has no id in Bar Actions"); + } + let ids: Vec<&str> = offered.iter().filter_map(|(_, a)| *a).collect(); + for action in expected.iter() { + assert!(ids.contains(action), "{case}: {action} in {ids:?}"); + } + for action in &ids { + show_action(&mut app, action, false); + } + let (ctx, texts) = bar_texts(&mut app); + for (label, _) in &offered { + assert!(!has(&texts, label), "{case}: {label} is off: {texts:?}"); + } + // The bar still shows, with More Options, where Bar Actions turns them back on. + assert!(canvas::task_bar_rect(&ctx).is_some(), "{case}: the bar still shows"); + let names: Vec = buttons(&mut app).1.into_iter().map(|(n, _)| n).collect(); + assert!(names.iter().any(|n| n == "More Options"), "{case}: {names:?}"); + for (label, _) in &offered { + assert!(!names.iter().any(|n| n == label), "{case}: {label} is off: {names:?}"); + } + } +} + +/// Bar Actions lists a field's name without its colon, as each language writes it, and an item +/// that opens a dialog without its ellipsis. +#[test] +fn bar_actions_list_names_without_a_colon_or_an_ellipsis() { + let lang = |code| crate::i18n::Lang::from_code(code).unwrap(); + for (code, label, name) in + [("en", "Fidelity:", "Fidelity"), ("en", "Tool Options…", "Tool Options"), ("fr", "Fidelity:", "Fidélité"), ("ja", "Fidelity:", "精度")] + .into_iter() + .chain([("zh-hans", "Fidelity:", "精确度"), ("zh-hant", "Fidelity:", "精確度"), ("zh-hans", "Tool Options…", "工具选项")]) + { + let label = crate::i18n::tr(lang(code), label); + assert_eq!(canvas::bar_action_name(label), name, "{code}: {label:?}"); + } + assert_eq!(canvas::bar_action_name("Duplicate"), "Duplicate"); + assert_eq!(canvas::bar_action_name("Tool Options..."), "Tool Options"); + assert_eq!(canvas::bar_action_name("Offset Path."), "Offset Path."); + // The colon and the ellipsis go in either order, with or without a space between them. + for label in [ + "Tool Options...:", + "Tool Options... :", + "Tool Options: ...", + "Tool Options …:", + "Tool Options… :", + "Tool Options…\u{a0}:", + "Tool Options...\u{202f}:", + ] { + assert_eq!(canvas::bar_action_name(label), "Tool Options", "{label:?}"); + } +} diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index f7935c2fd5..20aa11a7f0 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -438,7 +438,7 @@ pub(crate) fn flyout_press(ui: &Ui, resp: &egui::Response, rect: egui::Rect) -> /// Reflect and Shear tools' are their Object › Transform dialogs, the selection tools' are the /// Move dialog, and the Pencil, Paintbrush, Smooth, Blob Brush, Eraser, Shape Builder and Objects /// on Path tools' are their Tool Options, as are the Line Segment, Arc, Rectangular Grid and Polar Grid tools' -/// ([`crate::dialogs::shapes::open_options`]). The Type on a Path and Vertical Type on a Path +/// ([`crate::dialogs::shapes::open_options`]) and the Circle tool's ([`crate::dialogs::circle_options::open`]). The Type on a Path and Vertical Type on a Path /// tools' are Type on a Path Options for the selected type on a path. pub fn open_options(app: &mut VectorcraftApp, tool: &str) -> Result { match tool { @@ -475,6 +475,9 @@ pub fn open_options(app: &mut VectorcraftApp, tool: &str) -> Result crate::dialogs::shapes::open_options(app, tool), + // The Circle tool: what it shows while a circle is drawn, where its anchors go and how + // the third point is placed. + vectorcraft_tools::circle::ID => Ok(crate::dialogs::circle_options::open(app)), // The Three-Point Arc tool: whether the third point gives a direction. vectorcraft_tools::three_point_arc::ID => Ok(crate::dialogs::three_point_arc_options::open(app)), // The Flare tool: its options, which draw the next flare (OK draws none); with flares diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 7aa4017f0d..b67df13c7f 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -27,8 +27,8 @@ pub use blend::{ reference_point_named, }; pub use buttons::{ - SPLIT_ARROW, flat_button, flat_button_fit, icon_button, icon_button_enabled, menu_item, menu_item_name, paint_icon_button, primary_button, - primary_button_enabled, secondary_button, split_button, split_button_named, toggle_icon, + SPLIT_ARROW, flat_button, flat_button_fit, icon_button, icon_button_enabled, menu_item, menu_item_hint, menu_item_name, paint_icon_button, + primary_button, primary_button_enabled, secondary_button, split_button, split_button_named, toggle_icon, }; pub(crate) use buttons::{ button_width, flat_button_fit_width, icon_button_info, menu_item_response, paint_icon_button_named, primary_button_width, secondary_button_width, @@ -38,17 +38,21 @@ use chips::gradient_chip_colors; pub use chips::{ProxyClicks, chip_button, chip_button_named, fill_stroke_proxy, gradient_chip, paint_chip, proxy_chip, swatch_tile}; pub use color::{ FieldAxis, Live, MarkerResponse, RingResponse, SliderValue, WheelAxes, WheelResponse, channel_slider, channel_slider_named, - channel_slider_stepped, channel_slider_valued, color_field, color_mesh, color_slider, color_slider_named, color_slider_stepped, - color_slider_valued, harmony_wheel, hex_field, hex_field_named, hsb32, hue_ring, recolor_wheel, region_texture, ring_markers, ring_square, - segment_color, segment_color_on, segmented_wheel, stepped_area, wheel_of, + channel_slider_stepped, channel_slider_valued, color_field, color_field_shaded, color_mesh, color_slider, color_slider_named, + color_slider_stepped, color_slider_valued, harmony_wheel, hex_field, hex_field_named, hsb32, hue_ring, recolor_wheel, region_texture, + ring_markers, ring_square, segment_color, segment_color_on, segmented_wheel, stepped_area, wheel_of, }; -pub(crate) use color::{HEX_FIELD_CHARS, focus_by_pointer, hex_text, pointer_phase}; +pub(crate) use color::{HEX_FIELD_CHARS, color_rail_bar, focus_by_pointer, hex_text, pointer_phase}; +#[cfg(test)] +pub(crate) use color::{SHADE, shade_cells, shade_edges}; pub use drag::{ PanelDrag, RowClick, SwatchRows, apply_row_click, art_drag_doc, art_drop, doc_preview, drag_art, drag_ghost, drag_source, drop_target_outline, ghost_row, row_click, }; #[cfg(test)] use dropdowns::combo_button_id; +#[cfg(test)] +pub(crate) use dropdowns::top_popup_shapes; pub(crate) use dropdowns::{combo, combo_menu, combo_menu_field_named, combo_named, field_focused_in, menu_min_width, popover_is_open}; pub use dropdowns::{ dropdown, dropdown_icon_names, dropdown_icon_names_sized, dropdown_named, dropdown_names, dropdown_names_named, dropdown_with, diff --git a/crates/ui-egui/src/widgets/buttons.rs b/crates/ui-egui/src/widgets/buttons.rs index 6fb586a43c..0de8ded5e1 100644 --- a/crates/ui-egui/src/widgets/buttons.rs +++ b/crates/ui-egui/src/widgets/buttons.rs @@ -230,3 +230,13 @@ fn menu_item_name_response(ui: &mut Ui, label: &str, enabled: bool, checked: boo let text = if checked { format!("✓ {label}") } else { format!(" {label}") }; ui.add_enabled(enabled, egui::Button::new(egui::RichText::new(text).size(12.5)).frame_when_inactive(false)) } + +/// [`menu_item`] that shows `hint` under the pointer while the row is disabled, to say why it is +/// gray. +pub fn menu_item_hint(ui: &mut Ui, label: &str, enabled: bool, checked: bool, hint: &str) -> bool { + let label = tl!(label); + let text = if checked { format!("✓ {label}") } else { format!(" {label}") }; + ui.add_enabled(enabled, egui::Button::new(egui::RichText::new(text).size(12.5)).frame_when_inactive(false)) + .on_disabled_hover_text(tl!(hint)) + .clicked() +} diff --git a/crates/ui-egui/src/widgets/color.rs b/crates/ui-egui/src/widgets/color.rs index 9bbc15ad83..8f5ec8b2d9 100644 --- a/crates/ui-egui/src/widgets/color.rs +++ b/crates/ui-egui/src/widgets/color.rs @@ -279,6 +279,11 @@ fn rail_step(ui: &Ui, id: egui::Id, focused: bool, always: bool, s: &SliderValue (v != from || (end && v != s.value) || (always && asked)).then_some(if exact { v } else { round_to(v, STEP_DECIMALS).clamp(lo, hi) }) } +/// The colored bar inside the rail `rect` of [`color_slider_stepped`] and its siblings. +pub(crate) fn color_rail_bar(rect: Rect) -> Rect { + Rect::from_min_size(pos2(rect.left() + 4.0, rect.top() + 4.0), vec2(rect.width() - 8.0, 7.0)) +} + /// The rail of [`color_slider_valued`] with the id `id`: its response, the new value from 0 to 1 /// that a click or drag gives and the phase. fn color_rail( @@ -292,7 +297,7 @@ fn color_rail( ) -> (Response, Option, Live) { let t = Tokens::get(ui.ctx()); let (rect, _) = ui.allocate_exact_size(vec2(width, 22.0), Sense::hover()); - let bar = Rect::from_min_size(pos2(rect.left() + 4.0, rect.top() + 4.0), vec2(width - 8.0, 7.0)); + let bar = color_rail_bar(rect); let resp = ui.interact(rect, id, Sense::click_and_drag()); gradient_strip(ui, bar, (bar.width() / 2.0).ceil().max(2.0) as usize, false, track); ui.painter().rect_stroke(bar, 0.0, Stroke::new(1.0, t.border), StrokeKind::Outside); @@ -397,11 +402,26 @@ fn focus_outline(ui: &Ui, resp: &Response, rect: Rect) { pub fn color_field( ui: &mut Ui, id: impl std::hash::Hash, - (name, axes): (&str, [FieldAxis<'_>; 2]), + labels: (&str, [FieldAxis<'_>; 2]), size: Vec2, pos: (f32, f32), marked: bool, color_at: &dyn Fn(f32, f32) -> Color32, +) -> (Option<(f32, f32)>, Live) { + color_field_shaded(ui, id, labels, size, pos, marked, (color_at, &[])) +} + +/// A [`color_field`] with the cells `shade` marks grayed out under its marker, each run of them +/// edged with a dark and a light line. `shade` holds a row of an n × n grid over the field for each +/// of its n rows (16 at most) from the top, and bit `i` of a row marks its cell `i` from the left. +pub fn color_field_shaded( + ui: &mut Ui, + id: impl std::hash::Hash, + (name, axes): (&str, [FieldAxis<'_>; 2]), + size: Vec2, + pos: (f32, f32), + marked: bool, + (color_at, shade): (&dyn Fn(f32, f32) -> Color32, &[u16]), ) -> (Option<(f32, f32)>, Live) { use egui::accesskit::{Action, ActionData}; let t = Tokens::get(ui.ctx()); @@ -410,6 +430,7 @@ pub fn color_field( focus_on_press(&resp); let painter = ui.painter_at(rect.expand(6.0)); painter.add(color_mesh(rect, (32, 32), color_at)); + shade_cells(&painter, rect, shade); painter.rect_stroke(rect, 0.0, Stroke::new(1.0, t.border), StrokeKind::Outside); focus_outline(ui, &resp, rect); let (x, y) = pos; @@ -460,6 +481,55 @@ pub fn color_field( (None, Live::Idle) } +/// The gray over a shaded cell of a [`color_field_shaded`]. +pub(crate) const SHADE: Color32 = Color32::from_rgba_premultiplied(96, 96, 96, 192); + +/// Whether cell `col` of row `row` of `shade` is marked; a cell outside the grid is not. +fn shaded(shade: &[u16], col: usize, row: usize) -> bool { + col < shade.len().min(16) && shade.get(row).is_some_and(|bits| (bits >> col) & 1 == 1) +} + +/// The lines between the marked and the unmarked cells of `shade` (see [`color_field_shaded`]), +/// each from one grid point to the next, as (column, row) from the top-left corner. +pub(crate) fn shade_edges(shade: &[u16]) -> Vec<[(usize, usize); 2]> { + let n = shade.len().min(16); + let mut edges = Vec::new(); + for row in 0..n { + for col in 0..n { + let here = shaded(shade, col, row); + if col + 1 < n && here != shaded(shade, col + 1, row) { + edges.push([(col + 1, row), (col + 1, row + 1)]); + } + if row + 1 < n && here != shaded(shade, col, row + 1) { + edges.push([(col, row + 1), (col + 1, row + 1)]); + } + } + } + edges +} + +/// Gray out the cells `shade` marks over `rect`, and draw the lines between them and the others +/// dark under light. +pub(crate) fn shade_cells(painter: &egui::Painter, rect: Rect, shade: &[u16]) { + let n = shade.len().min(16); + if n == 0 { + return; + } + let cell = rect.size() / n as f32; + let at = |(col, row): (usize, usize)| rect.min + vec2(col as f32 * cell.x, row as f32 * cell.y); + for row in 0..n { + for col in (0..n).filter(|&col| shaded(shade, col, row)) { + painter.rect_filled(Rect::from_min_size(at((col, row)), cell), 0.0, SHADE); + } + } + let edges = shade_edges(shade); + for stroke in [Stroke::new(2.0, Color32::BLACK), Stroke::new(1.0, Color32::WHITE)] { + for [a, b] in &edges { + painter.line_segment([at(*a), at(*b)], stroke); + } + } +} + /// A smoothly shaded colour area: a `cols` × `rows` grid over `rect` with `color_at(x, y)` (0..1 /// each, y down) at its vertices. pub fn color_mesh(rect: Rect, (cols, rows): (u32, u32), color_at: &dyn Fn(f32, f32) -> Color32) -> egui::Shape { diff --git a/crates/ui-egui/src/widgets/dropdowns.rs b/crates/ui-egui/src/widgets/dropdowns.rs index 1baf1f4094..b440007a80 100644 --- a/crates/ui-egui/src/widgets/dropdowns.rs +++ b/crates/ui-egui/src/widgets/dropdowns.rs @@ -149,9 +149,10 @@ fn option_row<'a>(ui: &mut Ui, enabled: bool, selected: bool, atoms: impl egui:: response } -/// The id [`craft_ui::ComboBox::from_id_salt`] gives its button in this `Ui`: `from_id_salt` -/// stores `IdSalt::new(salt)` and hashes it once more with the scope, so the app must hash `id` -/// the same way to read the button's focus and open state before it is drawn. +/// The id of the button of [`combo_atoms_named`] in this `Ui`, the one +/// [`craft_ui::ComboBox::from_id_salt`] gives its button: `from_id_salt` stores +/// `IdSalt::new(salt)` and hashes it once more with the scope. The app reads the button's focus and +/// open state with it before the button is drawn. pub(super) fn combo_button_id(ui: &Ui, id: &impl std::hash::Hash) -> egui::Id { ui.make_persistent_id(egui::IdSalt::new(HashOnly(id))) } @@ -206,9 +207,8 @@ fn combo_atoms_named<'a, R>( if opening { ui.data_mut(|d| d.insert_temp(opened_key, pass)); } - // The menu measures itself against the whole screen on the pass it opens and takes - // the room beside its field on the next one, so the current option is scrolled into - // view on both. + // The list is laid out unseen to measure it on the pass it opens and placed on the + // next one, so the current option is scrolled into view on both. let settling = ui.data(|d| d.get_temp::(opened_key)).is_some_and(|p| pass <= p + 1); // A list drawn inside this one's rows finds its own record, and this one's comes back after it. let outer = if settling { OPENING.replace(Some(Opening::default())) } else { OPENING.take() }; @@ -238,17 +238,14 @@ fn combo_atoms_named<'a, R>( chosen }; let enter_for_combo = ui.memory(|m| m.has_focus(button_id)) || craft_ui::ComboBox::is_open(ui.ctx(), button_id); - let response = craft_ui::ComboBox::from_id_salt(HashOnly(&id)) - .selected_text(current) - .width(width - 4.0) - .height(ui.spacing().combo_height) - .show_ui(ui, list); + let response = combo_button(ui, button_id, current, width - 4.0); + let shown = combo_list(ui, &response, list); // The button or open list handles Enter before the modal can accept it. if enter_for_combo { ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Enter)); } - let _ = name_field(label_field(response.response.clone(), label), name); - let chosen = response.inner.flatten(); + let _ = name_field(label_field(response, label), name); + let chosen = shown.flatten(); // egui closes the list on a click of the pointer only: an option picked with Space or // Enter closes it here, and the combo gives the keyboard back, so that Enter reaches the // dialog's OK (#2789). @@ -261,6 +258,178 @@ fn combo_atoms_named<'a, R>( .inner } +/// The button of [`combo_atoms_named`] with the id `button_id`, at least `width` wide, showing +/// `current`: [`craft_ui::ComboBox`]'s button, with its look, its tooltip for a value cut short and +/// its role for screen readers. It is drawn here so that its list opens in [`combo_list`]. +fn combo_button<'a>(ui: &mut Ui, button_id: egui::Id, current: impl egui::IntoAtoms<'a>, width: f32) -> Response { + use egui::class::HasClasses as _; + use egui::{AtomExt as _, NumExt as _}; + let open = egui::Popup::is_id_open(ui.ctx(), button_id.with("popup")); + let mut classes = egui::class::Classes::default(); + classes.add_class(craft_ui::ComboBox::CLASS); + classes.set_class(craft_ui::ComboBox::CLASS_OPEN, open); + let egui::widget_style::ButtonStyle { atom_layout } = ui.widget_style(button_id, &classes); + let visuals = if open { + ui.visuals().widgets.open + } else if let Some(response) = ui.ctx().read_response(button_id) { + *ui.style().interact(&response) + } else { + ui.visuals().widgets.inactive + }; + let min_size = vec2(width, 0.0).at_least(atom_layout.min_size); + let current = current.into_atoms(); + let text = current.text().map(String::from).unwrap_or_default(); + let rtl = ui.style().right_to_left; + // The combo box's arrow: a downward triangle. + let arrow = egui::Atom::paint(Vec2::splat(ui.spacing().icon_width), move |ui, args| { + let rect = args.rect.expand(visuals.expansion); + let rect = Rect::from_center_size(rect.center(), vec2(rect.width() * 0.7, rect.height() * 0.45)); + ui.painter().add(egui::Shape::rotated_triangle(rect, 0.0, visuals.fg_stroke.color)); + }) + .atom_grow(true) + .atom_align(if rtl { egui::Align2::LEFT_CENTER } else { egui::Align2::RIGHT_CENTER }); + let button = atom_layout + .apply( + egui::WidgetAtom::new((current, arrow)) + .id(button_id) + .sense(Sense::click()) + .fallback_font(egui::TextStyle::Button) + .wrap_mode(ui.wrap_mode()) + .direction(if rtl { egui::Direction::RightToLeft } else { egui::Direction::LeftToRight }), + ) + .min_size(min_size) + .measure(ui, ui.available_size()); + let elided = button.container.iter_texts().any(|galley| galley.elided); + let response = button.allocate(ui).paint(ui).response; + // A value cut short shows in full on hover, as a truncated `Label`'s does. + let response = if elided { + response.on_hover_ui(|ui| { + ui.set_max_width(ui.spacing().tooltip_width); + ui.add(egui::Label::new(text.as_str()).wrap()); + }) + } else { + response + }; + response.widget_info(|| egui::WidgetInfo { + enabled: ui.is_enabled(), + current_text_value: Some(text.clone()), + ..egui::WidgetInfo::new(egui::Role::ComboBox) + }); + response +} + +/// The list of [`combo_atoms_named`] while it is open, drawn by `list` in a popup of its own that +/// opens from `button` and takes the whole list whenever the window has room for it (#5941): below +/// the button when it fits there, above it when it fits there instead, and otherwise moved up from +/// below, over the button, until it ends at the bottom bars. It stays above the bottom bars +/// ([`menu_floor`]), and a list taller than the room above them scrolls. A click closes +/// the list, except a click on its scroll bar, which scrolls it. Returns what `list` returned, or +/// `None` while the list is closed. +fn combo_list(ui: &Ui, button: &Response, list: impl FnOnce(&mut Ui) -> R) -> Option { + let ctx = ui.ctx(); + let id = button.id.with("popup"); + let style = egui::style::StyleModifier::new(|style| { + egui::containers::menu::menu_style(style); + style.spacing.scroll = list_scroll_style(); + }); + // The id of the list's scroll area. egui senses its vertical bar under the area's id with the + // axis, 1, and names the widget a click went to at the start of the pass. + let area_key = id.with("scroll-area-id"); + let on_bar = + ctx.data(|d| d.get_temp::(area_key)).is_some_and(|area| ctx.interaction_snapshot(|s| s.clicked == Some(area.with(1_usize)))); + let close = if on_bar { egui::PopupCloseBehavior::IgnoreClicks } else { egui::PopupCloseBehavior::CloseOnClick }; + let popup = egui::Popup::menu(button).id(id).width(button.rect.width()).style(style.clone()).close_behavior(close); + let screen = ctx.content_rect(); + // The list stops above the bottom bars, as other menus do (#2086). + let floor = menu_floor(ctx).min(screen.bottom()); + // The room on each side of the rect the popup opens from: the part of the button in view. + let anchor = popup.get_anchor_rect().unwrap_or(button.rect); + let below = floor - anchor.bottom(); + let above = anchor.top() - screen.top(); + // The list's size from its last pass: egui lays a popup out unseen on the pass it opens, so the + // list is measured before it is placed. A right-to-left layout lines the list up with the + // button's right edge, as egui's menus do. + let rtl = ui.style().right_to_left; + let expected = popup.get_expected_size(); + let (align, popup) = match expected { + Some(size) if size.y > below && size.y <= above => (if rtl { egui::RectAlign::TOP_END } else { egui::RectAlign::TOP_START }, popup), + // A list too tall for either side moves up from below until it ends at the floor. + Some(size) if size.y > below => { + let top = (floor - size.y).max(screen.top()); + let from = Rect::from_min_max(egui::pos2(anchor.left(), top), egui::pos2(anchor.right(), top)); + (if rtl { egui::RectAlign::BOTTOM_END } else { egui::RectAlign::BOTTOM_START }, popup.anchor(from)) + } + _ => (if rtl { egui::RectAlign::BOTTOM_END } else { egui::RectAlign::BOTTOM_START }, popup), + }; + let mut popup_style = (*ctx.global_style()).clone(); + style.apply(&mut popup_style); + let margins = egui::Frame::popup(&popup_style).total_margin().sum(); + let height = (floor - screen.top() - margins.y).max(ui.spacing().interact_size.y); + // A list that was wider than the window keeps its scroll bar in view: until it closes, it is no + // wider than it measured or than the window, its names cut short and shown in full on hover. + // Only a size measured while the list is open counts: egui keeps the last one after it closes. + // The width it needs is its rows' width on the last pass before it was narrowed, with its + // margins, and the bar's column while the rows scroll. + let too_wide_key = id.with("too-wide"); + let natural_key = id.with("natural-width"); + let scrolls_key = id.with("scrolls"); + let open_last_pass = ctx.read_response(id).is_some(); + if popup.get_expected_size().is_some_and(|size| open_last_pass && size.x > screen.width()) { + // The first measurement is kept: later ones are of the list already narrowed. + ctx.data_mut(|d| { + if d.get_temp::(too_wide_key).is_none() { + let rows = d.get_temp::(natural_key).unwrap_or(screen.width()); + d.insert_temp(too_wide_key, rows); + } + }); + } + let (measured, scrolls) = ctx.data(|d| (d.get_temp::(too_wide_key), d.get_temp::(scrolls_key).unwrap_or(false))); + let too_wide = measured.is_some(); + let shown = popup.align(align).align_alternatives(&[]).show(|ui| { + if let Some(rows) = measured { + let bar = if scrolls { list_scroll_style().allocated_width() } else { 0.0 }; + ui.set_max_width((rows + bar).min(screen.width() - margins.x).max(0.0)); + } + ui.set_min_width(ui.available_width()); + // A popup offers its contents the height it had on its last pass; the list is offered the + // window's instead. + ui.set_max_height(height); + // Labels widen a narrow list rather than wrap, as in egui's combo box. + ui.style_mut().wrap_mode = Some(if too_wide { egui::TextWrapMode::Truncate } else { egui::TextWrapMode::Extend }); + let painted = ui.ctx().graphics(|g| g.get(ui.layer_id()).map_or(0, |shapes| shapes.all_entries().len())); + let shown = egui::ScrollArea::vertical().max_height(height).show(ui, list); + if too_wide { + show_shortened_rows(ui, painted); + } + ui.data_mut(|d| { + if !too_wide { + d.insert_temp(natural_key, shown.content_size.x); + } + d.insert_temp(scrolls_key, shown.content_size.y > shown.inner_rect.height()); + d.insert_temp(area_key, shown.id); + }); + shown.inner + }); + if shown.is_some() { + ctx.accesskit_node_builder(id, |node| node.set_role(egui::Role::ListBox)); + } else { + ctx.data_mut(|d| { + d.remove::(too_wide_key); + d.remove::(natural_key); + d.remove::(scrolls_key); + }); + } + shown.map(|r| r.inner) +} + +/// The shapes painted so far in this pass on the topmost popup that was shown in the last one, such +/// as an open dropdown list, without what lies under it. Read at the end of a test's UI. +#[cfg(test)] +pub(crate) fn top_popup_shapes(ctx: &egui::Context) -> Vec { + let top = ctx.memory(|m| m.layer_ids().filter(|l| l.order == egui::Order::Foreground && m.areas().is_visible(l)).last()); + top.map_or_else(Vec::new, |layer| ctx.graphics(|g| g.get(layer).map(|p| p.all_entries().cloned().collect()).unwrap_or_default())) +} + /// The recessed combo box of [`dropdown`] showing `current`, whose menu keeps a search field and /// filters in place over a list that scrolls (the font menu and the shortcut import's target /// picker, #555). `menu` shows the menu with one of [`craft_ui::combo::Menu`]'s header forms and diff --git a/crates/ui-egui/src/widgets/look_tests.rs b/crates/ui-egui/src/widgets/look_tests.rs index 4ee9e6f412..286be3f10c 100644 --- a/crates/ui-egui/src/widgets/look_tests.rs +++ b/crates/ui-egui/src/widgets/look_tests.rs @@ -133,10 +133,13 @@ fn a_dropdown_in_a_short_window_opens_with_its_current_option_in_view() { for (height, above, current) in [(260.0, 117.0, 19), (260.0, 117.0, 10), (180.0, 77.0, 10), (180.0, 77.0, 3)] { let ctx = themed(Default::default()); let field = std::cell::Cell::new(Rect::NOTHING); + let popup = std::cell::RefCell::new(vec![]); let mut add = |ui: &mut Ui| { ui.add_space(above); field.set(ui.horizontal(|ui| dropdown_names(ui, "short-list", labels[current], &labels, 160.0)).response.rect); + popup.replace(super::top_popup_shapes(ui.ctx())); }; + // The shapes of the open list, without the field under it. let mut run = |time: f64, events: Vec| { let raw = egui::RawInput { time: Some(time), @@ -146,7 +149,7 @@ fn a_dropdown_in_a_short_window_opens_with_its_current_option_in_view() { }; let mut out = ctx.run_ui(raw, &mut add); out.textures_delta.clear(); - out.shapes + popup.take() }; run(0.0, vec![]); let at = field.get().center(); @@ -206,6 +209,7 @@ fn own_rows_reopen(height: f32, above: f32, wheel: f32, row: &str) { let ctx = themed(Default::default()); let field = std::cell::Cell::new(Rect::NOTHING); let current = std::cell::RefCell::new(String::from("Row 00")); + let popup = std::cell::RefCell::new(vec![]); let mut add = |ui: &mut Ui| { ui.add_space(above); let shown = current.borrow().clone(); @@ -224,8 +228,10 @@ fn own_rows_reopen(height: f32, above: f32, wheel: f32, row: &str) { current.replace(items[i].clone()); } field.set(r.response.rect); + popup.replace(super::top_popup_shapes(ui.ctx())); }; let mut time = 0.0; + // The shapes of the open list, without the field under it. let mut run = |events: Vec| { time += 0.1; let raw = egui::RawInput { @@ -236,7 +242,7 @@ fn own_rows_reopen(height: f32, above: f32, wheel: f32, row: &str) { }; let mut out = ctx.run_ui(raw, &mut add); out.textures_delta.clear(); - out.shapes + popup.take() }; // The rows that show whole, with their tops: inside the open list and the clip they are painted // in. @@ -298,10 +304,12 @@ fn own_rows_reopen(height: f32, above: f32, wheel: f32, row: &str) { } let scrolled = rows(clipped); assert!(has(&scrolled, row), "{case}: the wheel scrolls {row} into view: {scrolled:?}"); - // Closed and opened again twice: each time its rows are where they were when it closed. + // Closed and opened again twice: each time its rows are where they were when it closed. Escape + // closes it: a list taller than the room beside its field covers the field. + let escape = |pressed| egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed, repeat: false, modifiers: Default::default() }; for time in ["first", "second"] { - run(vec![egui::Event::PointerMoved(at), press(true)]); - run(vec![press(false)]); + run(vec![escape(true)]); + run(vec![escape(false)]); run(vec![]); let reopened = rows(open(&mut run)); assert_eq!(reopened, scrolled, "{case}: the list opens again where it was scrolled, the {time} time"); @@ -804,6 +812,517 @@ fn kerning_reads_parentheses_around_its_text_with_a_manual_value_too() { } } +/// Long dropdown lists use the window's room instead of stopping at `combo_height` (200 pt), and +/// show a solid scroll bar without hovering when the list still overflows. +#[test] +fn a_long_dropdown_uses_window_room_and_shows_its_scroll_bar_when_clipped() { + let items: Vec = (0..20).map(|i| format!("Format {i:02}")).collect(); + let labels: Vec<&str> = items.iter().map(String::as_str).collect(); + let run = |win_h: f32| { + let ctx = themed(Default::default()); + let button_rect = std::cell::Cell::new(Rect::NOTHING); + let mut draw = |ui: &mut Ui| { + ui.add_space(16.0); + ui.horizontal(|ui| { + ui.add_space(16.0); + let before = ui.next_widget_position(); + let _ = dropdown_names(ui, "long-formats", labels[0], &labels, 160.0); + button_rect.set(Rect::from_min_size(before, vec2(160.0, 26.0))); + }); + }; + let mut step = |time: f64, events: Vec| { + let raw = egui::RawInput { + time: Some(time), + screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(400.0, win_h))), + events, + ..Default::default() + }; + let mut out = ctx.run_ui(raw, &mut draw); + out.textures_delta.clear(); + out.shapes + }; + step(0.0, vec![]); + let at = button_rect.get().center(); + let click = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + step(0.1, vec![egui::Event::PointerMoved(at), click(true)]); + step(0.2, vec![click(false)]); + // Move the pointer away so the scroll bar is dormant, not hovered, and let the popup settle. + step(0.3, vec![egui::Event::PointerMoved(pos2(350.0, 10.0))]); + let mut clipped = vec![]; + for i in 4..10 { + clipped = step(f64::from(i) * 0.1, vec![]); + } + (ctx, clipped) + }; + + // In a tall window, all 20 items show without stopping at the 200 pt cap. + let (_tall_ctx, tall_shapes) = run(720.0); + let mut texts = vec![]; + fn collect_text(s: &egui::Shape, out: &mut Vec) { + match s { + egui::Shape::Vec(v) => v.iter().for_each(|s| collect_text(s, out)), + egui::Shape::Text(t) => out.push(t.galley.text().to_string()), + _ => {} + } + } + for c in &tall_shapes { + collect_text(&c.shape, &mut texts); + } + assert!(texts.iter().any(|t| t == "Format 19"), "the 20th option is shown without scrolling: {texts:?}"); + + // In a short window where the list overflows, a solid scroll bar is drawn even while dormant. + let (short_ctx, short_shapes) = run(220.0); + let mut short_texts = vec![]; + for c in &short_shapes { + collect_text(&c.shape, &mut short_texts); + } + assert!(!short_texts.iter().any(|t| t == "Format 19"), "the list overflows the 220 pt window"); + let popup = short_ctx + .memory(|m| m.layer_ids().filter(|l| l.order == egui::Order::Foreground && m.areas().is_visible(l)).last().and_then(|l| m.area_rect(l.id))) + .expect("the popup is open"); + let mut bar_rects = vec![]; + fn collect_rects(s: &egui::Shape, out: &mut Vec) { + match s { + egui::Shape::Vec(v) => v.iter().for_each(|s| collect_rects(s, out)), + egui::Shape::Rect(r) => out.push(r.clone()), + _ => {} + } + } + for c in &short_shapes { + collect_rects(&c.shape, &mut bar_rects); + } + let has_scroll_bar = bar_rects.iter().any(|r| { + r.fill != Color32::TRANSPARENT + && r.rect.width() <= list_scroll_style().bar_width + 1.0 + && r.rect.height() >= 12.0 + && r.rect.height() < popup.height() + && r.rect.right() <= popup.right() + && r.rect.left() >= popup.right() - list_scroll_style().allocated_width() - 8.0 + }); + assert!(has_scroll_bar, "the overflowing dropdown draws its scroll bar without hover in {popup:?}"); +} + +// #5941: a drop-down list stopped at the room on one side of its field, so a window with room for +// the whole list still cut it short. The list opens below its field when it fits there, above it +// when it fits there instead, and otherwise moves up from below into the window over its field; +// each time every option shows whole, inside the window. +#[test] +fn a_dropdown_list_shows_every_option_when_the_window_has_room() { + let items: Vec = (0..20).map(|i| format!("Option {i:02}")).collect(); + let labels: Vec<&str> = items.iter().map(String::as_str).collect(); + // (window height, space above the field, where the list goes) + for (height, above, side) in [(700.0, 16.0, "below"), (700.0, 650.0, "above"), (640.0, 300.0, "over")] { + let case = format!("{height} pt window, field {above} pt down"); + let ctx = themed(Default::default()); + let field = std::cell::Cell::new(Rect::NOTHING); + let popup = std::cell::RefCell::new(vec![]); + let mut add = |ui: &mut Ui| { + ui.add_space(above); + field.set(ui.horizontal(|ui| dropdown_names(ui, "fit-list", labels[0], &labels, 160.0)).response.rect); + popup.replace(super::top_popup_shapes(ui.ctx())); + }; + let screen = Rect::from_min_size(Pos2::ZERO, vec2(400.0, height)); + // The shapes of the open list, without the field under it. + let mut run = |time: f64, events: Vec| { + let mut out = ctx.run_ui(egui::RawInput { time: Some(time), screen_rect: Some(screen), events, ..Default::default() }, &mut add); + out.textures_delta.clear(); + popup.take() + }; + run(0.0, vec![]); + let at = field.get().center(); + let press = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + run(0.1, vec![egui::Event::PointerMoved(at), press(true)]); + run(0.2, vec![press(false)]); + run(0.3, vec![egui::Event::PointerMoved(pos2(390.0, 2.0))]); + let mut clipped = vec![]; + for i in 4..10 { + clipped = run(f64::from(i) * 0.1, vec![]); + } + let list = ctx + .memory(|m| { + m.layer_ids().filter(|l| l.order == egui::Order::Foreground && m.areas().is_visible(l)).last().and_then(|l| m.area_rect(l.id)) + }) + .expect("the list is open"); + assert!(screen.contains_rect(list), "{case}: the list {list:?} is inside the window"); + let field = field.get(); + // The list opens from the button, 1 pt inside the field's border. + match side { + "below" => assert!(list.top() >= field.bottom() - 1.5, "{case}: the list {list:?} opens below the field {field:?}"), + "above" => assert!(list.bottom() <= field.top() + 1.5, "{case}: the list {list:?} opens above the field {field:?}"), + _ => assert!(list.top() < field.bottom() && list.bottom() > field.top(), "{case}: the list {list:?} covers the field {field:?}"), + } + let mut texts = vec![]; + fn flat(s: &egui::Shape, clip: Rect, out: &mut Vec<(String, Rect, Rect)>) { + match s { + egui::Shape::Vec(v) => v.iter().for_each(|s| flat(s, clip, out)), + egui::Shape::Text(t) => out.push((t.galley.text().to_owned(), t.visual_bounding_rect(), clip)), + _ => {} + } + } + clipped.iter().for_each(|c| flat(&c.shape, c.clip_rect, &mut texts)); + let whole: Vec<&str> = labels + .iter() + .copied() + .filter(|name| { + texts.iter().any(|(s, r, clip)| s == name && list.contains_rect(*r) && r.top() >= clip.top() && r.bottom() <= clip.bottom()) + }) + .collect(); + assert_eq!(whole, labels, "{case}: every option shows whole in {list:?}"); + } +} + +// #5941: a drop-down list stops above the bottom bars, as other menus do (#2086). In a 700 pt window +// whose bars start at 640 pt, the list opens below a field near the top, and from a field in the +// middle it moves up over the field until it ends at the bars; each time every option shows whole. +#[test] +fn a_dropdown_list_stops_above_the_bottom_bars() { + let items: Vec = (0..20).map(|i| format!("Option {i:02}")).collect(); + let labels: Vec<&str> = items.iter().map(String::as_str).collect(); + let floor = 640.0; + for above in [16.0, 300.0] { + let case = format!("field {above} pt down"); + let ctx = themed(Default::default()); + let field = std::cell::Cell::new(Rect::NOTHING); + let popup = std::cell::RefCell::new(vec![]); + let mut add = |ui: &mut Ui| { + set_menu_floor(ui.ctx(), floor); + ui.add_space(above); + field.set(ui.horizontal(|ui| dropdown_names(ui, "floor-list", labels[0], &labels, 160.0)).response.rect); + popup.replace(super::top_popup_shapes(ui.ctx())); + }; + let screen = Rect::from_min_size(Pos2::ZERO, vec2(400.0, 700.0)); + let mut run = |time: f64, events: Vec| { + let mut out = ctx.run_ui(egui::RawInput { time: Some(time), screen_rect: Some(screen), events, ..Default::default() }, &mut add); + out.textures_delta.clear(); + popup.take() + }; + run(0.0, vec![]); + let at = field.get().center(); + let press = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + run(0.1, vec![egui::Event::PointerMoved(at), press(true)]); + run(0.2, vec![press(false)]); + run(0.3, vec![egui::Event::PointerMoved(pos2(390.0, 2.0))]); + let mut clipped = vec![]; + for i in 4..10 { + clipped = run(f64::from(i) * 0.1, vec![]); + } + let list = ctx + .memory(|m| { + m.layer_ids().filter(|l| l.order == egui::Order::Foreground && m.areas().is_visible(l)).last().and_then(|l| m.area_rect(l.id)) + }) + .expect("the list is open"); + assert!(list.top() >= 0.0 && list.bottom() <= floor + 0.5, "{case}: the list {list:?} ends above the bars at {floor}"); + let mut texts = vec![]; + fn flat(s: &egui::Shape, clip: Rect, out: &mut Vec<(String, Rect, Rect)>) { + match s { + egui::Shape::Vec(v) => v.iter().for_each(|s| flat(s, clip, out)), + egui::Shape::Text(t) => out.push((t.galley.text().to_owned(), t.visual_bounding_rect(), clip)), + _ => {} + } + } + clipped.iter().for_each(|c| flat(&c.shape, c.clip_rect, &mut texts)); + let whole: Vec<&str> = labels + .iter() + .copied() + .filter(|name| { + texts.iter().any(|(s, r, clip)| s == name && list.contains_rect(*r) && r.top() >= clip.top() && r.bottom() <= clip.bottom()) + }) + .collect(); + assert_eq!(whole, labels, "{case}: every option shows whole in {list:?}"); + } +} + +// #5941: a click on the scroll bar's track of an open drop-down list scrolls it and leaves it open, +// so an option it scrolled into view can be picked. A list closed by that click would open again +// with its current option in view. +#[test] +fn a_click_on_a_dropdown_lists_scroll_bar_scrolls_it_and_leaves_it_open() { + let items: Vec = (0..40).map(|i| format!("Option {i:02}")).collect(); + let labels: Vec<&str> = items.iter().map(String::as_str).collect(); + let ctx = themed(Default::default()); + let field = std::cell::Cell::new(Rect::NOTHING); + let picked = std::cell::Cell::new(None); + let popup = std::cell::RefCell::new(vec![]); + let mut add = |ui: &mut Ui| { + ui.add_space(16.0); + let r = ui.horizontal(|ui| dropdown_names(ui, "bar-click", labels[0], &labels, 160.0)); + field.set(r.response.rect); + if let Some(i) = r.inner { + picked.set(Some(i)); + } + popup.replace(super::top_popup_shapes(ui.ctx())); + }; + let screen = Rect::from_min_size(Pos2::ZERO, vec2(400.0, 300.0)); + let mut time = 0.0; + // The options that show whole on the open list, with their rects, and the scroll bar's rects. + let mut run = |events: Vec| { + time += 0.1; + let mut out = ctx.run_ui(egui::RawInput { time: Some(time), screen_rect: Some(screen), events, ..Default::default() }, &mut add); + out.textures_delta.clear(); + let (mut texts, mut bars) = (vec![], vec![]); + fn flat(s: &egui::Shape, clip: Rect, out: &mut Vec<(String, Rect)>, bars: &mut Vec) { + match s { + egui::Shape::Vec(v) => v.iter().for_each(|s| flat(s, clip, out, bars)), + egui::Shape::Text(t) => { + let r = t.visual_bounding_rect(); + if r.top() >= clip.top() && r.bottom() <= clip.bottom() { + out.push((t.galley.text().to_owned(), r)); + } + } + egui::Shape::Rect(r) if r.fill.a() > 0 && r.rect.width() <= 8.0 && r.rect.height() > 40.0 => bars.push(r.rect), + _ => {} + } + } + popup.take().iter().for_each(|c| flat(&c.shape, c.clip_rect, &mut texts, &mut bars)); + (texts, bars) + }; + let list_rect = || { + ctx.memory(|m| m.layer_ids().filter(|l| l.order == egui::Order::Foreground && m.areas().is_visible(l)).last().and_then(|l| m.area_rect(l.id))) + }; + let click = + |at: Pos2, pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + run(vec![]); + let at = field.get().center(); + run(vec![egui::Event::PointerMoved(at), click(at, true)]); + run(vec![click(at, false)]); + let (mut before, mut bars) = (vec![], vec![]); + for _ in 0..4 { + (before, bars) = run(vec![]); + } + assert!(list_rect().is_some(), "the list is open"); + assert!(before.iter().any(|(s, _)| s == "Option 00"), "the list opens at its first option: {before:?}"); + // The track, below the handle: near the bottom of the tallest bar rect drawn (the track). + let bar = bars + .iter() + .copied() + .max_by(|a, b| a.height().total_cmp(&b.height())) + .unwrap_or_else(|| panic!("the list {:?} draws its scroll bar: {before:?}", list_rect())); + let track = pos2(bar.center().x, bar.bottom() - 6.0); + run(vec![egui::Event::PointerMoved(track), click(track, true)]); + run(vec![]); + // The button is let go just past the bar's edge, closer than a drag, and the pointer then moves + // sideways onto the rows, in the same pass. + let let_go = pos2(bar.right() + 1.0, track.y); + let onto_row = before.first().map(|(_, r)| pos2(r.center().x, track.y)).expect("a row shows"); + run(vec![egui::Event::PointerMoved(let_go), click(let_go, false), egui::Event::PointerMoved(onto_row)]); + let mut after = vec![]; + for _ in 0..4 { + (after, _) = run(vec![]); + } + assert!(list_rect().is_some(), "a click on the scroll bar leaves the list open"); + let new = after + .iter() + .find(|(s, _)| !before.iter().any(|(b, _)| b == s)) + .cloned() + .unwrap_or_else(|| panic!("the click scrolled options into view: {after:?}")); + let row = new.1.center(); + run(vec![egui::Event::PointerMoved(row), click(row, true)]); + run(vec![click(row, false)]); + run(vec![]); + let index = labels.iter().position(|l| *l == new.0); + assert_eq!(picked.get(), index, "the option scrolled into view is picked: {}", new.0); + assert!(list_rect().is_none(), "picking an option closes the list"); +} + +// #5941: a drop-down list with an option wider than the window ran past the window's right edge, +// and its scroll bar with it. The list stays inside the window and its bar shows; the long option's +// name is cut short. +#[test] +fn a_dropdown_list_wider_than_the_window_keeps_its_scroll_bar_in_view() { + let mut items: Vec = (0..40).map(|i| format!("Option {i:02}")).collect(); + items[1] = "Option 01, whose name is much wider than this window".into(); + let labels: Vec<&str> = items.iter().map(String::as_str).collect(); + let short: Vec<&str> = labels.iter().copied().filter(|l| l.len() < 10).collect(); + let two: Vec<&str> = labels[..2].to_vec(); + // Which list the field offers: 0 all, 1 the short names, 2 the first two. + let offered = std::cell::Cell::new(0); + let ctx = themed(Default::default()); + let field = std::cell::Cell::new(Rect::NOTHING); + let popup = std::cell::RefCell::new(vec![]); + let mut add = |ui: &mut Ui| { + ui.add_space(16.0); + let options = [&labels, &short, &two][offered.get()]; + field.set(ui.horizontal(|ui| dropdown_names(ui, "wide-list", options[0], options, 160.0)).response.rect); + popup.replace(super::top_popup_shapes(ui.ctx())); + }; + let screen = Rect::from_min_size(Pos2::ZERO, vec2(220.0, 300.0)); + let window = std::cell::Cell::new(screen); + let mut time = 0.0; + // The texts painted on the open list with their clip rects, and the scroll bar's rects. + let mut run = |events: Vec| { + time += 0.1; + let mut out = ctx.run_ui(egui::RawInput { time: Some(time), screen_rect: Some(window.get()), events, ..Default::default() }, &mut add); + out.textures_delta.clear(); + let (mut texts, mut bars) = (vec![], vec![]); + fn flat(s: &egui::Shape, clip: Rect, texts: &mut Vec<(String, bool)>, bars: &mut Vec) { + match s { + egui::Shape::Vec(v) => v.iter().for_each(|s| flat(s, clip, texts, bars)), + egui::Shape::Text(t) => texts.push((t.galley.text().to_owned(), t.galley.elided)), + egui::Shape::Rect(r) if r.fill.a() > 0 && r.rect.width() <= 8.0 && r.rect.height() > 40.0 => bars.push(r.rect.intersect(clip)), + _ => {} + } + } + popup.take().iter().for_each(|c| flat(&c.shape, c.clip_rect, &mut texts, &mut bars)); + (texts, bars) + }; + run(vec![]); + let at = field.get().center(); + let press = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + run(vec![egui::Event::PointerMoved(at), press(true)]); + run(vec![press(false)]); + run(vec![egui::Event::PointerMoved(pos2(210.0, 290.0))]); + let (mut texts, mut bars) = (vec![], vec![]); + for _ in 0..6 { + (texts, bars) = run(vec![]); + } + let list_rect = || { + ctx.memory(|m| m.layer_ids().filter(|l| l.order == egui::Order::Foreground && m.areas().is_visible(l)).last().and_then(|l| m.area_rect(l.id))) + }; + let list = list_rect().expect("the list is open"); + assert!(screen.contains_rect(list), "the list {list:?} is inside the window"); + assert!( + bars.iter().any(|b| b.width() > 0.0 && screen.contains_rect(*b) && list.contains_rect(*b)), + "the bar shows in the list {list:?}: {bars:?}" + ); + assert!(texts.iter().any(|(s, elided)| *elided && s.starts_with("Option 01")), "the long name is cut short: {texts:?}"); + // The window grows while the list is open: the list grows as wide as its names need, and no + // wider. + window.set(Rect::from_min_size(Pos2::ZERO, vec2(1000.0, 300.0))); + for _ in 0..6 { + (texts, _) = run(vec![]); + } + let grown = list_rect().expect("the list is still open"); + assert!(grown.width() < 500.0, "the list {grown:?} stays as wide as its names need"); + assert!(texts.iter().any(|(s, elided)| !*elided && s == labels[1]), "the long name shows in full: {texts:?}"); + // Narrowed and widened again, it comes back to the same width. + for size in [screen.size(), vec2(1000.0, 300.0)] { + window.set(Rect::from_min_size(Pos2::ZERO, size)); + for _ in 0..6 { + run(vec![]); + } + } + let again = list_rect().expect("the list is still open"); + assert!((again.width() - grown.width()).abs() < 0.5, "the list is as wide as before: {again:?}, {grown:?}"); + // Closed, the window narrowed again and the long option gone: the list opens as narrow as its + // names, not as wide as the window. + let escape = |pressed| egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed, repeat: false, modifiers: Default::default() }; + run(vec![escape(true)]); + run(vec![escape(false)]); + assert!(list_rect().is_none(), "Escape closes the list"); + window.set(screen); + offered.set(1); + run(vec![]); + let at = field.get().center(); + let press = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + run(vec![egui::Event::PointerMoved(at), press(true)]); + run(vec![press(false)]); + run(vec![egui::Event::PointerMoved(pos2(210.0, 290.0))]); + let mut widths = vec![]; + for _ in 0..4 { + run(vec![]); + widths.push(list_rect().expect("the list is open").width()); + } + assert!(widths.iter().all(|w| *w < 180.0), "the list of short names stays narrow: {widths:?}"); + // Opened in a wide window, narrowed and widened again: it comes back to the width it opened at, + // the long list that scrolls and a list of two that does not. + for (which, count) in [(0, "40"), (2, "2")] { + run(vec![escape(true)]); + run(vec![escape(false)]); + offered.set(which); + window.set(Rect::from_min_size(Pos2::ZERO, vec2(1000.0, 300.0))); + run(vec![]); + run(vec![egui::Event::PointerMoved(at), press(true)]); + run(vec![press(false)]); + run(vec![egui::Event::PointerMoved(pos2(990.0, 290.0))]); + for _ in 0..6 { + run(vec![]); + } + let opened = list_rect().expect("the list is open"); + for size in [screen.size(), vec2(1000.0, 300.0)] { + window.set(Rect::from_min_size(Pos2::ZERO, size)); + for _ in 0..6 { + run(vec![]); + } + } + let restored = list_rect().expect("the list is still open"); + // Within the half point that egui rounds a popup's position to. + assert!((restored.width() - opened.width()).abs() < 0.5, "{count} options: the list is as wide as it opened: {restored:?}, {opened:?}"); + } + // Opened in a narrow window tall enough for every option, then made wide and short: the list + // scrolls now, and its bar's column comes on top of the long name, which shows in full. + run(vec![escape(true)]); + run(vec![escape(false)]); + offered.set(0); + window.set(Rect::from_min_size(Pos2::ZERO, vec2(220.0, 1400.0))); + run(vec![]); + run(vec![egui::Event::PointerMoved(at), press(true)]); + run(vec![press(false)]); + run(vec![egui::Event::PointerMoved(pos2(210.0, 1390.0))]); + for _ in 0..6 { + run(vec![]); + } + window.set(Rect::from_min_size(Pos2::ZERO, vec2(1000.0, 300.0))); + for _ in 0..6 { + (texts, _) = run(vec![]); + } + assert!(texts.iter().any(|(s, elided)| !*elided && s == labels[1]), "the long name shows in full beside the bar: {texts:?}"); +} + +// #5941: in a drop-down list narrowed to the window, an option whose name is cut short shows the +// full name in a tooltip while the pointer rests on it. +#[test] +fn a_dropdown_option_cut_short_shows_its_full_name_on_hover() { + let mut items: Vec = (0..10).map(|i| format!("Option {i:02}")).collect(); + items[1] = "Option 01, whose name is much wider than this window".into(); + let labels: Vec<&str> = items.iter().map(String::as_str).collect(); + let ctx = themed(Default::default()); + let field = std::cell::Cell::new(Rect::NOTHING); + let mut add = |ui: &mut Ui| { + ui.add_space(16.0); + field.set(ui.horizontal(|ui| dropdown_names(ui, "hover-list", labels[0], &labels, 160.0)).response.rect); + }; + let screen = Rect::from_min_size(Pos2::ZERO, vec2(220.0, 300.0)); + let mut time = 0.0; + // Every text painted, on any layer, with its rect and whether it was cut short. + let mut run = |events: Vec| { + time += 0.1; + let mut out = ctx.run_ui(egui::RawInput { time: Some(time), screen_rect: Some(screen), events, ..Default::default() }, &mut add); + out.textures_delta.clear(); + let mut texts = vec![]; + fn flat(s: &egui::Shape, out: &mut Vec<(String, Rect, bool)>) { + match s { + egui::Shape::Vec(v) => v.iter().for_each(|s| flat(s, out)), + egui::Shape::Text(t) => out.push((t.galley.text().to_owned(), t.visual_bounding_rect(), t.galley.elided)), + _ => {} + } + } + out.shapes.iter().for_each(|c| flat(&c.shape, &mut texts)); + texts + }; + run(vec![]); + let at = field.get().center(); + let press = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + run(vec![egui::Event::PointerMoved(at), press(true)]); + run(vec![press(false)]); + run(vec![egui::Event::PointerMoved(pos2(210.0, 290.0))]); + let mut texts = vec![]; + for _ in 0..6 { + texts = run(vec![]); + } + let full = |texts: &[(String, Rect, bool)]| texts.iter().any(|(s, _, elided)| !*elided && s == labels[1]); + assert!(!full(&texts), "the long name is not shown in full before the hover: {texts:?}"); + let row = texts + .iter() + .find(|(s, _, elided)| *elided && s.starts_with("Option 01")) + .map(|(_, r, _)| r.center()) + .unwrap_or_else(|| panic!("the long name is cut short: {texts:?}")); + run(vec![egui::Event::PointerMoved(row)]); + for _ in 0..10 { + texts = run(vec![]); + } + assert!(full(&texts), "the full name shows on hover: {texts:?}"); +} + /// Enter on text that reads as no number in a range field refuses it as a unit field does: the /// field flashes and an open dialog is not confirmed with the old value. #[test] diff --git a/crates/ui-egui/src/workspaces.rs b/crates/ui-egui/src/workspaces.rs index e3ce74bcbf..c409b6b71a 100644 --- a/crates/ui-egui/src/workspaces.rs +++ b/crates/ui-egui/src/workspaces.rs @@ -42,6 +42,10 @@ pub struct Workspace { pub toolbar_compact: bool, pub toolbar_advanced: bool, pub task_bar: bool, + /// The Contextual Task Bar's actions and chips its Bar Actions has off (built-in workspaces, and + /// workspaces saved without this field: none). + #[serde(skip_serializing_if = "std::collections::BTreeSet::is_empty", deserialize_with = "crate::canvas::read_hidden_task_bar_actions")] + pub task_bar_hidden_actions: std::collections::BTreeSet, pub dock: bool, pub dock_tab: DockTab, /// The dock's tabbed group is collapsed to icons (built-in workspaces: expanded). @@ -208,6 +212,7 @@ pub fn capture(ui: &UiState, name: &str) -> Workspace { toolbar_compact: ui.toolbar_compact, toolbar_advanced: ui.toolbar_advanced, task_bar: ui.task_bar, + task_bar_hidden_actions: ui.task_bar_hidden_actions.clone(), dock: ui.dock, dock_tab: ui.dock_tab, dock_collapsed: ui.dock_collapsed, @@ -247,6 +252,7 @@ pub fn apply(ui: &mut UiState, w: &Workspace) { ui.toolbar_compact = w.toolbar_compact; ui.toolbar_advanced = w.toolbar_advanced; ui.task_bar = w.task_bar; + ui.task_bar_hidden_actions = w.task_bar_hidden_actions.clone(); ui.dock = w.dock; ui.tab_hid = None; ui.dock_tab = w.dock_tab; @@ -949,4 +955,42 @@ mod tests { let read: UiState = serde_json::from_value(prefs).unwrap(); assert!(read.control_bar_hidden_groups.is_empty(), "older preferences show every group"); } + + /// A workspace keeps the Contextual Task Bar's actions its Bar Actions has off: switching + /// brings each workspace's back, Reset turns a built-in workspace's on again, and they survive + /// the preferences' JSON. A workspace saved without them, or with ids the bar does not have, + /// shows every action, or the ones it names that the bar has. + #[test] + fn saved_workspaces_restore_the_task_bar_actions() { + let hidden = |ids: &[&str]| ids.iter().map(|s| s.to_string()).collect::>(); + let mut ui = UiState { task_bar_hidden_actions: hidden(&["duplicate", "fill"]), ..Default::default() }; + save_as(&mut ui, "Lean").unwrap(); + switch(&mut ui, ESSENTIALS).unwrap(); + assert!(ui.task_bar_hidden_actions.is_empty(), "Essentials shows every action"); + ui.task_bar_hidden_actions = hidden(&["simplify"]); + switch(&mut ui, "Lean").unwrap(); + assert_eq!(ui.task_bar_hidden_actions, hidden(&["duplicate", "fill"]), "the saved workspace's actions"); + switch(&mut ui, ESSENTIALS).unwrap(); + assert_eq!(ui.task_bar_hidden_actions, hidden(&["simplify"]), "Essentials as it was left"); + reset(&mut ui); + assert!(ui.task_bar_hidden_actions.is_empty(), "Reset Essentials shows every action again"); + switch(&mut ui, "Lean").unwrap(); + let json = serde_json::to_value(&ui).unwrap(); + assert_eq!(json["custom_workspaces"][0]["taskBarHiddenActions"], serde_json::json!(["duplicate", "fill"])); + let back: UiState = serde_json::from_value(json).unwrap(); + assert_eq!(back.task_bar_hidden_actions, hidden(&["duplicate", "fill"]), "kept in the preferences"); + assert_eq!(back.custom_workspaces[0].task_bar_hidden_actions, hidden(&["duplicate", "fill"]), "kept with the workspace"); + let mut old = serde_json::to_value(&back.custom_workspaces[0]).unwrap(); + assert!(old.as_object_mut().unwrap().remove("taskBarHiddenActions").is_some()); + let old: Workspace = serde_json::from_value(old).unwrap(); + apply(&mut ui, &old); + assert!(ui.task_bar_hidden_actions.is_empty(), "an older workspace shows every action"); + let mut prefs = serde_json::to_value(&back).unwrap(); + prefs["custom_workspaces"][0]["taskBarHiddenActions"] = serde_json::json!(["fill", "teleport", 3]); + let read: UiState = serde_json::from_value(prefs.clone()).unwrap(); + assert_eq!(read.custom_workspaces[0].task_bar_hidden_actions, hidden(&["fill"]), "ids the bar does not have are dropped"); + prefs["custom_workspaces"][0]["taskBarHiddenActions"] = serde_json::json!("fill"); + let read: UiState = serde_json::from_value(prefs).unwrap(); + assert!(read.custom_workspaces[0].task_bar_hidden_actions.is_empty(), "a value that is not a list shows every action"); + } } diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 0af0e02a42..dafab93a58 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -92,7 +92,7 @@ the two can still win that race. | `engine.execute` | `{command, params}` | run any engine or UI command (see `engine.commands`). A key of `params` that the command's params description doesn't name is an error naming it and the nearest key the command takes, before anything runs (`unknown parameter `widht`; did you mean `width`?`); see [Parameter keys](mcp.md#parameter-keys) | | `engine.commands` | | every command with label, shortcut, params doc, enablement | | `document.inspect` | `{depth?, childLimit?, ids?, kind?, limit?, offset?}` | layer tree, selection, the key object (`key`, null without one; a key ruler guide as `keyGuide`), history, paint defaults; `depth` / `childLimit` slice the layer tree as `document.node {summary: true}` does; `ids`, `kind`, `limit` and `offset` list just some nodes as `nodes` (with `total`) instead of the whole tree, see [mcp.md](mcp.md). Each node reports `opacity` below 1 and `blend` when it isn't Normal; objects and compound paths report `fill`, `stroke` and `strokeWidth`, a compound path's members `compoundMember: true` instead | -| `ui.inspect` | | tool, UI state, `screenMode` (0 normal, 1 full screen with menu bar, 2 full screen, 3 Presentation Mode), `taskBar` (`pinned`, and `rect` `[x, y, w, h]` while the Contextual Task Bar shows), `freeTransformWidget` (`[x, y, w, h]` while the Free Transform widget shows), view, canvas rect, window size, perf, background saves and exports still running, `nativeMenuBar` (true when the menus are in the macOS menu bar rather than the window; `ui.menu.list` lists the in-window menus either way), `fileDialog` (`"open"`, `"place"`, `"save"` or `"folder"` while a native file dialog is open, `null` otherwise; see below), `opening` (the paths of the documents still being read). Under `--automation-read-root` the reply leaves out the paths outside the read roots (see `docs/mcp.md`) | +| `ui.inspect` | | tool, UI state, `screenMode` (0 normal, 1 full screen with menu bar, 2 full screen, 3 Presentation Mode), `taskBar` (`pinned`, and `rect` `[x, y, w, h]` while the Contextual Task Bar shows), `quickPenToolbar` (the same for the Quick Pen toolbar), `freeTransformWidget` (`[x, y, w, h]` while the Free Transform widget shows), view, canvas rect, window size, perf, background saves and exports still running, `nativeMenuBar` (true when the menus are in the macOS menu bar rather than the window; `ui.menu.list` lists the in-window menus either way), `fileDialog` (`"open"`, `"place"`, `"save"` or `"folder"` while a native file dialog is open, `null` otherwise; see below), `opening` (the paths of the documents still being read). Under `--automation-read-root` the reply leaves out the paths outside the read roots (see `docs/mcp.md`) | | `ui.menu.list` / `ui.menu.invoke` | `{command, params}` | the full menu tree / invoke an item | | `ui.contextMenu.list` | | the canvas context menu for the current selection, flattened like `ui.menu.list` (`path` holds its submenus). `ui.click {x, y, button: "right"}` on the canvas opens it, after selecting the object there unless it is already selected. With the Artboard tool it lists the artboard entries (see `docs/mcp.md`), after selecting the artboard there unless it is already selected. While a menu opened over locked objects is open, it has an `Unlock` submenu with one item for each locked object under the pointer, topmost first and at most 20, labeled with the object's name, which runs `layer.setProps {ids: [id], locked: false}`. A locked group gets one item, and the locked objects inside it get none. Hidden objects, objects on hidden, locked or template layers, and in isolation mode objects outside the isolated group get no item | | `ui.tool.select` / `ui.tool.list` | `{tool}` | | @@ -272,10 +272,13 @@ My Themes tab lists the saved themes; every action runs a command (`colorTheme.s Color Wheel panel (`window.panel {panel: "colorWheel"}`): a hue ring around a saturation and brightness square. A pick runs the commands the Color panel's sliders run: `paint.setFill` or `paint.setStroke` with `keepModel`, `paint.editGradient` for a gradient's selected stop, and `paint.freeform.setPoint` for a freeform gradient's selected -point (the first stop or point when none is selected). `ui.colorWheel {view?, channel?, harmony?, harmonyRule?, vision?}` -shows the wheel or the box (a color field with a channel strip at its right), picks the box's channel, shows the -other colors of a harmony rule as markers on the wheel's ring, and shows or hides the color vision row; it returns -the settings, and `ui.inspect` reports them as `ui.color_wheel`. +point (the first stop or point when none is selected). `ui.colorWheel {view?, channel?, sliders?, gamut?, harmony?, +harmonyRule?, vision?}` shows the wheel or the box (a color field with a channel strip at its right), picks the box's +channel, shows OKLCH Sliders, HSL Sliders or neither, grays out the colors the CMYK space cannot print, shows the +other colors of a harmony rule as markers on the wheel's ring, and shows or hides the color vision row; it returns the +settings, and `ui.inspect` reports them as `ui.color_wheel`. +The key `sliders` takes (`"oklch"`, `"hsl"` or `"none"`; `"oklch"` is an error while the active document's RGB space, its assigned +profile or else the working RGB space, is not sRGB), and the settings carry it too. Edit Colors dialogs: `ui.colorBalanceDialog` opens Adjust Colors (`colorBalance`: fields `mode` `gray`/`rgb`/`cmyk`/ `global`, the channels `r` `g` `b` / `c` `m` `y` `k` / `gray` / `tint` (global mode) from −100 to 100, `convert`, `fill`, `stroke`, @@ -333,6 +336,16 @@ The dialog previews step; with no art selected only the group changes). In the Swatches panel, double-clicking a colour group's folder, or the options button while a group is selected, opens it. +`color.used {selection?, limit?}` lists the colors of the selection, or with nothing selected the colors of the art +`select.all` takes, most used first, as `recolor.colors {}` counts them. Each entry adds `color`, the color in its own +model as the paint commands take it, and `tint`, the percent of its global `swatch` it is, to three decimals. The +swatch and tint come from the color's first linked use in paint order; a plain use goes before a gradient stop that +mixes a spot ink with process inks, and a color only such stops link has no `swatch` here. `selection: false` reads +the art `select.all` takes while something is selected, and the answer's `selection` says whether the colors are +the selection's. `limit` keeps only the most used entries, and the answer's `uses` counts the uses of every color. +The selection does not change. The Color Wheel panel's Show Document Colors row (`ui.colorWheel {documentColors: +true}`) shows these colors. + Library panel: `engine.execute {command: "window.swatchLibrary", params: {library}}` opens the read-only library panel on a swatch library (`ui.inspect` shows it as `library_panel: {kind, id}`; `library: null` closes it). Clicking a swatch there runs `swatch.library.add {library, names: [name], apply}` (the active proxy, or the other @@ -494,6 +507,12 @@ Bar Position (`window.taskBar.reset`), which unpins it and puts it back under th Panel. As in Illustrator, neither the position nor the pin is saved: each launch starts with the bar under the selection. +The Quick Pen toolbar shows while the Quick Pen tool is active and Window › Quick Pen Toolbar +(`window.quickPenToolbar`) is on. Its handle drags it as the Contextual Task Bar's does. Its buttons set the tool's +action and flip the last sharp-corner arc (`tool.quickPen.flipArc`), and its More Options (…) menu has Hide Toolbar +(`window.quickPenToolbar`), Pin Toolbar Position (`window.quickPenToolbar.pin {pinned?}`) and Reset Toolbar Position +(`window.quickPenToolbar.reset`). `docs/mcp.md` (Drawing with the Quick Pen tool) says where it sits. + The Compound Shapes add-on's setting, `window.pathfinder.compoundShapes` (omitted params toggle; checked while on; kept with the preferences; off by default), swaps what a click and an Alt-click do on the Pathfinder panel's Shape Mode buttons: on, a click makes a compound shape (`object.compoundShape.make`) and Alt-click gives the permanent Pathfinder result. Selected members of a compound @@ -925,7 +944,8 @@ when the export refuses the options or the artboard choice, `pens` stays null an remembers the options for the next HP-GL Options (not `exportSelection`) and writes the `.plt` file(s), asking for a path when there is none (one per artboard with Use Artboards). A canceled save dialog writes nothing and keeps the options remembered before; a save dialog shown in line (not as a sheet or off the UI thread) also keeps HP-GL -Options open. +Options open. When another document has become the active one since the dialog opened, `ui.dialog.confirm` closes +it and writes nothing. TIFF, BMP and Targa Options: Export As… with the TIFF, BMP or Targa format (`file.exportAs {format: "tiff"}`, then the save dialog) opens `tiffOptions`, `bmpOptions` or `tgaOptions`: the raster rows of PNG Options (`ppi`, diff --git a/docs/effects-parity.md b/docs/effects-parity.md index c4c3a4ba9c..a3ba859915 100644 --- a/docs/effects-parity.md +++ b/docs/effects-parity.md @@ -24,7 +24,7 @@ Part of [target-app-parity.md](target-app-parity.md); open work is in [gaps.md]( | Crop Marks | Crop Marks | 1/1 | — | | Distort & Transform | Free Distort, Pucker & Bloat, Roughen, Transform, Tweak, Twist, Zig Zag | 7/7 | Free Distort's dialog has a handle on each corner of the object's bounds, moved by dragging or with the arrow keys; Zig Zag's ridges are evenly spaced along each segment (#1558), and Smooth points make a continuous wave whose peaks and valleys have handles along the path (#2343); Roughen with Smooth keeps turn-backs smooth instead of cusps that draw as spikes (#1646); Expand Appearance of a path whose Transform effect makes copies gives a group of one object per copy, each painted as the path, and a second Transform effect's copies nest in a group per copy of the first (#5612); drawn, each copy of a path with a fill and a stroke (or several, an even-odd fill or a partly transparent one) paints below the one before, the fills above covering the strokes of the copies below, instead of one path of every copy (#5920), and a group's copies each hold all its members except guides, the original group on top (#6316); a clipping group, a group with a fill or stroke of its own, a group whose type is kept as type, and a group with a member that carries a geometry, Pathfinder or 3D effect copy each member in its place; Twist's handles follow the rotation's derivative, so a strongly twisted path is a smooth spiral without kinks where its pieces join (#7069, `twist_joins_its_pieces_smoothly`). | | Path | Offset Path, Outline Object, Outline Stroke | 3/3 | With Use Preview Bounds on, Align, Distribute and the Transform panel still measure type that carries Outline Object by its layout box (preview bounds leave out effects) | -| Pathfinder | Add, Intersect, Exclude, Subtract, Minus Back, Divide, Trim, Merge, Crop, Outline, Hard Mix, Soft Mix, Trap | 13/13 | Trap traps only solid fills (gradients and patterns hide what is below them but don't trap) and spreads each colour's visible area as a whole; the public page gives no default values, so Trap's 0.25 pt, 100% and 40% are VectorCraft's own | +| Pathfinder | Add, Intersect, Exclude, Subtract, Minus Back, Divide, Trim, Merge, Crop, Outline, Hard Mix, Soft Mix, Trap | 13/13 | Trap traps only solid fills (gradients and patterns hide what is below them but don't trap) and spreads each colour's visible area as a whole; the public page gives no default values, so Trap's 0.25 pt, 100% and 40% are VectorCraft's own; each of the other Pathfinder effects keeps its own Precision, Remove Redundant Points and Divide and Outline Will Remove Unpainted Artwork, taken from Pathfinder Options when applied and edited in Pathfinder Options opened from its Appearance panel row ([Pathfinder effects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/combine-objects-using-pathfinder-effects.html)) | | Rasterize | Rasterize… (as a live effect) | 1/1 | — | | Stylize | Drop Shadow, Feather, Inner Glow, Outer Glow, Round Corners, Scribble | 6/6 | Scribble Options' Settings presets | | SVG Filters | Apply SVG Filter… and the filter list | 1/1 | The submenu lists 14 default filters and then the document's own; the public page names no default set, so the set, names and values are VectorCraft's own, and a default is copied into the document when it is applied or edited. A filter that is the object's last effect is written to SVG as a `` element; otherwise SVG export draws the object as an image. A filter on a turned, skewed or unevenly scaled object in an imported SVG is kept and runs in that object's user space, and SVG export writes it back under the same transform. A blur or drop shadow that blurs more in one direction than another in the document (two different standard deviations, or one in a skewed or unevenly scaled user space) is kept as this effect rather than opened as an even Gaussian Blur or Drop Shadow | @@ -179,9 +179,9 @@ VectorCraft choices; an original approximation, never compared with another appl | Item | Ours | |---|---| | Revolve | initial: live, editable profile, rotation and light gizmos, default-on Cap with continuous curved rims that also closes a partial sweep's cut sides, smooth vector shading and round seam joins, overlapping faces drawn in the order of their depths where they overlap, SVG/PDF output, Expand Appearance ([revolve.md](revolve.md), #846) | -| Extrude & Bevel, Inflate, Rotate | initial: live, round seam joins, depth, twist, taper, solid or hollow caps, five original bevel shapes, Inflate volume, both sides, twist, taper and cap, Rotate of every fill and stroke, groups and layers turned about one shared axis (#4506), contours that cross, touch or overlap merged first ([three-d.md](three-d.md)), Position presets, rotation and light gizmos, SVG/PDF output, Expand Appearance ([three-d.md](three-d.md)) | -| Materials panel, lighting, ray-traced render | Window › 3D and Materials panel with the object types (Plane, Extrude, Revolve, Inflate) and the Object, Rotation and Lighting settings of the applied effect, Render Settings › Wireframe, which draws the live effect as the edges of its faces, and Quick Actions › Expand as Wireframes ([three-d.md](three-d.md#3d-and-materials-panel)); one to ten directional lights with per-light Color (opaque RGB, white by default), Intensity, Rotation, Height, Softness and neutral Ambient Light, Revolve and colored Inflate use smooth vector shading; Extrude & Bevel and Rotate retain planar shading; original Standard, Diffuse, Top Left and Right lighting rigs; shadows behind or below the object from the first light, blurred by its Softness ([three-d.md](three-d.md#shadows)); the Materials tab's Graphics, document symbols mapped onto Extrude & Bevel's caps and onto a plane, moved with an artboard handle, wrapped around Extrude & Bevel's walls and bevels and around Revolve's side, and carried onto Inflate's puffed front and back ([three-d.md](three-d.md#graphics)); no base materials or ray tracing | -| 3D (Classic): Extrude & Bevel, Revolve, Rotate | Extrude & Bevel (Classic) initial: live, round seam joins, Extrude Depth, Cap, five original bevel shapes with Height and Bevel Extent In or Out, Position presets and rotation gizmo, Perspective, Wireframe, No Shading, Diffuse and Plastic surfaces with one to ten lights, Light Intensity, Ambient Light, Highlight Intensity and Size, Blend Steps, Black, Custom, Black Overprint or no Shading Color ([Black Overprint](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=188)), Draw Hidden Faces ([create 3D objects](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/create-3d-objects.html)); Revolve (Classic) initial: live, round seam joins, Angle, Cap, Offset from the left or right edge, Position presets and rotation gizmo, Perspective, the same four surfaces, lights, highlight, Blend Steps and Shading Color, groups and layers revolved about one shared axis (same page); Rotate (Classic) initial: live, round seam joins, every fill and stroke turned as one plane, Position presets and rotation gizmo, Perspective, No Shading and Diffuse surfaces with lights, Ambient Light, Blend Steps and Shading Color ([rotate objects in 3D](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/rotate-objects-in-3d.html)); Preserve Spot Colors in all three, unavailable with a Custom Shading Color ([Preserve Spot Color](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=260)); all three: a lighting sphere on the Lighting tab whose lights drag, move to the back or front, and are added at the front center or deleted down to one ([lighting options](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=272)); all three: the track cube (face, edge, Shift and ring drags, keyboard steps; [three-d.md](three-d.md#track-cube)); Map Art for Extrude & Bevel (Classic) and Revolve (Classic): one document symbol on each numbered surface, surface navigation with visible and hidden marks and a red outline on the artboard, move, scale and rotate on the surface laid out flat, Scale to Fit, Clear, Clear All, Shade Artwork, Invisible Geometry, kept by Expand Appearance and exports, `threeD.mapArt` ([map artwork to a 3D object](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=189)) | +| Extrude & Bevel, Inflate, Rotate | initial: live, round seam joins, depth, twist, taper, solid or hollow caps, five original bevel shapes and custom bevels drawn as open paths in the bevels file ([add custom bevel paths](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/add-custom-bevel-paths.html), [three-d.md](three-d.md#custom-bevels)), Inflate volume, both sides, twist, taper and cap, Rotate of every fill and stroke, groups and layers turned about one shared axis (#4506), contours that cross, touch or overlap merged first ([three-d.md](three-d.md)), Position presets, rotation and light gizmos, SVG/PDF output, Expand Appearance ([three-d.md](three-d.md)) | +| Materials panel, lighting, ray-traced render | Window › 3D and Materials panel with the object types (Plane, Extrude, Revolve, Inflate) and the Object, Rotation and Lighting settings of the applied effect, Render Settings › Wireframe, which draws the live effect as the edges of its faces, and Quick Actions › Expand as Wireframes ([three-d.md](three-d.md#3d-and-materials-panel)); one to ten directional lights with per-light Color (opaque RGB, white by default), Intensity, Rotation, Height, Softness and neutral Ambient Light, Revolve and colored Inflate use smooth vector shading; Extrude & Bevel and Rotate retain planar shading; original Standard, Diffuse, Top Left and Right lighting rigs; shadows behind or below the object from the first light, blurred by its Softness ([three-d.md](three-d.md#shadows)); the Materials tab's Graphics, document symbols mapped onto Extrude & Bevel's caps and onto a plane, moved with an artboard handle, and wrapped around Extrude & Bevel's walls and bevels and around Revolve's side ([three-d.md](three-d.md#graphics)); no base materials, graphics on Inflate, or ray tracing | +| 3D (Classic): Extrude & Bevel, Revolve, Rotate | Extrude & Bevel (Classic) initial: live, round seam joins, Extrude Depth, Cap, five original bevel shapes and the custom bevels with Height and Bevel Extent In or Out, Position presets and rotation gizmo, Perspective, Wireframe, No Shading, Diffuse and Plastic surfaces with one to ten lights, Light Intensity, Ambient Light, Highlight Intensity and Size, Blend Steps, Black, Custom, Black Overprint or no Shading Color ([Black Overprint](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=188)), Draw Hidden Faces ([create 3D objects](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/create-3d-objects.html)); Revolve (Classic) initial: live, round seam joins, Angle, Cap, Offset from the left or right edge, Position presets and rotation gizmo, Perspective, the same four surfaces, lights, highlight, Blend Steps and Shading Color, groups and layers revolved about one shared axis (same page); Rotate (Classic) initial: live, round seam joins, every fill and stroke turned as one plane, Position presets and rotation gizmo, Perspective, No Shading and Diffuse surfaces with lights, Ambient Light, Blend Steps and Shading Color ([rotate objects in 3D](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/rotate-objects-in-3d.html)); Preserve Spot Colors in all three, unavailable with a Custom Shading Color ([Preserve Spot Color](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=260)); all three: a lighting sphere on the Lighting tab whose lights drag, move to the back or front, and are added at the front center or deleted down to one ([lighting options](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=272)); all three: the track cube (face, edge, Shift and ring drags, keyboard steps; [three-d.md](three-d.md#track-cube)); Map Art for Extrude & Bevel (Classic) and Revolve (Classic): one document symbol on each numbered surface, surface navigation with visible and hidden marks and a red outline on the artboard, move, scale and rotate on the surface laid out flat, Scale to Fit, Clear, Clear All, Shade Artwork, Invisible Geometry, kept by Expand Appearance and exports, `threeD.mapArt` ([map artwork to a 3D object](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=189)) | | Turntable (30.0 beta) | none | | Export 3D objects (OBJ, USDA, glTF) | initial: Asset Export's Export 3D Object, and the 3D and Materials panel's Export 3D Object button (which then shows Asset Export with the new assets selected, [three-d.md](three-d.md#3d-and-materials-panel)), collect an object with Extrude & Bevel, Revolve, Inflate or Rotate as a 3D asset, and Export writes its solids as a USDA (the default), USDZ, glTF or OBJ mesh with a material in each solid's paint color (`assets.add3D`, `assets.set3DFormat`, `assets.export3D`); graphics mapped onto a plane or Extrude & Bevel's caps are exported as PNG textures of those faces, flat and unlit; no graphics on Revolve's side, no materials and no shading ([3D export help](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/export-3d-vector-artwork.html)) | diff --git a/docs/gaps.md b/docs/gaps.md index ffd85c9b3a..5132520ee6 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Gaps -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-18 · **Change:** minor (Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: SVG export preserves document units on root width/height for physical units, #864; G11 estimate 8–15 → 6–13 h; G4 and G13 Missing lists drop the shipped Touch Type, Snap to Glyph and Dimension tool, and G13's snapping entry keeps only what is still missing, the partial Snapping panel and the items not yet checked (#8387); G13 keeps one estimate (13–23 h); estimates unchanged; previously: Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: G4 type: modal Check Spelling dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: Type: the Middle Eastern & South Asian composers are done as a per-paragraph choice with the Standard composers (#4935); G5: built-in Neon & Glow graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); estimate unchanged (3–13 h); previously: Tech Circuit brush library, G5; previously: G5: built-in Weather Icons symbol library (Sun, Moon, Cloud, Rain, Thunder, Snow); estimate 5–15 → 4–14 h; previously: 3D: the seams of white-light Extrude & Bevel, Inflate and Rotate, and the face seams of the 3D (Classic) effects, have round joins instead of miters; previously: PDF import: preserve Type 3 font text runs as named groups , or as live text in TextAs::Text mode if ToUnicode exists on non-colour fonts (TextAs::Outlines produces grouped outlines), #6740; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: oversized editing artboard import; Glyphs panel: Alternates for Current Selection applies an OpenType feature value (`salt=2`) to the selected letter alone, so an Arabic word stays joined, and Entire Font lists the unencoded glyphs, #5514; #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: G5: built-in Energy Beams brush library; estimate 5–15 → 4–14 h; previously minor: G5: built-in Skill Icons symbol library; estimate 6–16 → 5–15 h; previously minor: ruler double-click adds a guide at the pointer, #5239; G5: built-in Status Effects graphic style library; estimate 7–17 → 6–16 h; MCP docs catch-up for UI Frames and Map Markers; previously minor: G5: built-in Inventory Icons symbol library; estimate 8–18 → 7–17 h; previously minor: G9: `.ai` save names a variable font instance's design-space setting, #6388; previously minor: G5: built-in Game Trails brush library; estimate 9–19 → 8–18 h; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: docs tidy-up, no content change: stray notes at the top moved into the revision table; scores and estimates unchanged; previously minor: G5: built-in Game HUD graphic style library; estimate 10–20 → 9–19 h; previously minor: G5: built-in Map Markers symbol library; estimate 11–21 → 10–20 h; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview; estimate 1–2 h → 0; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: built-in UI Frames symbol library with default 9-slice; estimate 11–21 h; previously minor: G5: dynamic symbol part on-canvas takes opacity, blend, gradient and pattern; docs Overlap/auto-corners sync; estimate 12–22 h; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap, Pattern brush auto corners and Global Edit Shift-click leave-out moved from Missing to Done (code already shipped); previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; G9: EPS gradients drawn as abutting strips import as one gradient, without seams; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; opening a slow file shows a progress window, part of #5930; Hindi catalog and contributor loanword preferences; agent wording pass complete; wider native proofreading welcome; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); scores and estimates unchanged; a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window; scores and estimates unchanged; large images in CMYK documents are shrunk before they are separated into ink planes (#4155); scores and estimates unchanged; `.ai` paths with a Calligraphic brush open brushed, with the 6D Art Pen's channels, and Windows reads the pen's tilt and barrel rotation, #372; scores and estimates unchanged; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; a slow first frame is waited for instead of restarting without the graphics adapter, and the menu bar no longer waits for the installed fonts' scan; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-19 · **Change:** minor (Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: G12: Brushes panel: item right-click context menu (Brush Options, Duplicate Brush, Delete Brush) with selection handling; scores and estimates unchanged; previously: G12: Links panel row context menu (Relink…, Go To Link, Update Link, Edit Original, Show in Folder, Embed Image / Unembed…) with selection handling; scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: SVG export preserves document units on root width/height for physical units, #864; G11 estimate 8–15 → 6–13 h; G4 and G13 Missing lists drop the shipped Touch Type, Snap to Glyph and Dimension tool, and G13's snapping entry keeps only what is still missing, the partial Snapping panel and the items not yet checked (#8387); G13 keeps one estimate (13–23 h); estimates unchanged; previously: Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: G4 type: modal Check Spelling dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: Type: the Middle Eastern & South Asian composers are done as a per-paragraph choice with the Standard composers (#4935); G5: built-in Neon & Glow graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); estimate unchanged (3–13 h); previously: Tech Circuit brush library, G5; previously: G5: built-in Weather Icons symbol library (Sun, Moon, Cloud, Rain, Thunder, Snow); estimate 5–15 → 4–14 h; previously: 3D: the seams of white-light Extrude & Bevel, Inflate and Rotate, and the face seams of the 3D (Classic) effects, have round joins instead of miters; previously: PDF import: preserve Type 3 font text runs as named groups , or as live text in TextAs::Text mode if ToUnicode exists on non-colour fonts (TextAs::Outlines produces grouped outlines), #6740; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: oversized editing artboard import; Glyphs panel: Alternates for Current Selection applies an OpenType feature value (`salt=2`) to the selected letter alone, so an Arabic word stays joined, and Entire Font lists the unencoded glyphs, #5514; #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: G5: built-in Energy Beams brush library; estimate 5–15 → 4–14 h; previously minor: G5: built-in Skill Icons symbol library; estimate 6–16 → 5–15 h; previously minor: ruler double-click adds a guide at the pointer, #5239; G5: built-in Status Effects graphic style library; estimate 7–17 → 6–16 h; MCP docs catch-up for UI Frames and Map Markers; previously minor: G5: built-in Inventory Icons symbol library; estimate 8–18 → 7–17 h; previously minor: G9: `.ai` save names a variable font instance's design-space setting, #6388; previously minor: G5: built-in Game Trails brush library; estimate 9–19 → 8–18 h; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: docs tidy-up, no content change: stray notes at the top moved into the revision table; scores and estimates unchanged; previously minor: G5: built-in Game HUD graphic style library; estimate 10–20 → 9–19 h; previously minor: G5: built-in Map Markers symbol library; estimate 11–21 → 10–20 h; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview; estimate 1–2 h → 0; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: built-in UI Frames symbol library with default 9-slice; estimate 11–21 h; previously minor: G5: dynamic symbol part on-canvas takes opacity, blend, gradient and pattern; docs Overlap/auto-corners sync; estimate 12–22 h; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap, Pattern brush auto corners and Global Edit Shift-click leave-out moved from Missing to Done (code already shipped); previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; G9: EPS gradients drawn as abutting strips import as one gradient, without seams; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; opening a slow file shows a progress window, part of #5930; Hindi catalog and contributor loanword preferences; agent wording pass complete; wider native proofreading welcome; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); scores and estimates unchanged; a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window; scores and estimates unchanged; large images in CMYK documents are shrunk before they are separated into ink planes (#4155); scores and estimates unchanged; `.ai` paths with a Calligraphic brush open brushed, with the 6D Art Pen's channels, and Windows reads the pen's tilt and barrel rotation, #372; scores and estimates unchanged; Compound Shapes add-on, beyond Illustrator; scores and estimates unchanged; Contour add-on, beyond Illustrator; scores and estimates unchanged; a slow first frame is waited for instead of restarting without the graphics adapter, and the menu bar no longer waits for the installed fonts' scan; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) > Scissors snapping update (2026-11-11): with Alt released, hover and cuts use the Pen's path, alignment, intersection and anchor snaps (#6470). Scores and estimates unchanged. @@ -10,6 +10,8 @@ ## Feature submission evidence +**Scissors cut-point preview (#8655):** A native point marker shows the anchor or position on a curve that the current Scissors click targets, including the existing snapping rules. Hovering changes no artwork; an ineligible or stale hover has no marker. Existing cut and Alt Add Anchor behavior are retained. Focused tool and Session regressions live in `crates/tools/src/draw2/anchor/tests.rs` and `crates/engine/tests/scissors_snap.rs`. Scores and estimates are unchanged. + Draft enhancement #5804: Preferences › File Handling can select a raster editor through the native picker, with a private draft outside engine preferences and generic dialog fields. OK saves it, Cancel discards it, and Reset restores PhotoCraft. With Use System Defaults off, a missing chosen editor falls back to PhotoCraft, then the system default; validation and launch failures are reported. Control/MCP and synthetic input cannot choose an application or run external Edit Original. Web behavior, parity scores and estimates are unchanged; macOS/Linux smoke tests remain pending. **2026-11-19 revision:** merged main while preserving the private raster-editor choice; no parity rescore. @@ -50,6 +52,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-11-19 | minor | G12: Graphic Styles panel item context menus (Options…, Duplicate, Delete, Redefine, Break Link); regression tests in crates/ui-egui/src/panels/graphic_styles.rs; scores and estimates unchanged. | | 2026-11-19 | minor | G12: Place: show progress window with Cancel for slow placed files exceeding 0.4 s (part of #5930, `file.cancelPlace`); indeterminate moving bar, Cancel (Esc) leaves the document unmodified without undo steps; scores and estimates unchanged. | | 2026-11-18 | minor | G11: SVG export writes physical unit suffixes on the root for documents with physical units (mm, cm, in, pc), preventing drawings from scaling to 75% in external tools and preserving units across round-trips (#864; general unit preference on restart remains open under #864). Estimate 8–15 → 6–13 h. | | 2026-11-18 | minor | G5: Media Controls joins Basic Shapes, UI Frames, Map Markers, Inventory Icons, Skill Icons and Weather Icons as a seventh built-in symbol library (Play, Pause, Stop, Skip Next, Shuffle, Repeat; original procedural vector symbols generated in code, no default 9-slice); estimate decremented (3–13 → 2–12 h). | @@ -144,6 +147,8 @@ from G14 and the budget run of G15: **~170–270 h** one agent, ~50–80 h wall macOS cursor delivery (#2292) is narrowed to a native host adapter using the existing artwork and aligned 1×/2× representations. Headless tests cover visible fallbacks, preparation and ownership; native focus/menu/handback timing, mixed displays, Spotlight and full-screen Spaces remain open validation work (see [hardware parity](hardware-parity.md)). This does not close the interaction-fidelity gap or change its score/estimate. +- **Temporary handle mirroring (#7842):** with Direct Selection, add Control (Command on macOS) after a direction-handle drag begins to mirror the opposite handle at equal length. This includes ordinary paths, type on a path and blend spines; a missing opposite handle is pulled out while the modifier is held. At an open end, where no segment leaves the anchor on the other side, the handle moves as it does without the modifier. Letting go returns to the drag's normal handle behavior, Shift constrains before mirroring, and Alt takes independent-handle priority. The existing Control/Command-before-press Selection-tool loan is unchanged, and the Control/Command press that lends Direct Selection while another tool, such as the Pen, is chosen does not mirror until it is let go and pressed again. This does not add a persistent coupling mode or change Pen, mesh or warp gestures; the broader G1 scope and estimates remain. + - **Selection fill eligibility (#6625):** Path and compound-path interiors use any enabled non-None fill row (#6625). A lower visible fill remains selectable beneath a top None row in the same object; hidden-only and true-None interiors miss. Zero-opacity fills remain selectable. Original CPU-render and document-hit regressions in `crates/engine/tests/path_fill_hits.rs` cover seven Path and five Compound cases, including stroke edges, geometric outlines, Outline/path-only modes and compound holes. Hidden-fill and no-fill stroked paths must respect butt, round and square caps and bevel, round and miter joins. Focused cap/join CPU regressions passed. Scores and estimates unchanged. - **Panel collapse controls (#5925, in part):** The small » in a floating tab-group header moves that group into the side icon rail, reusing the existing rail or creating one. An opened rail panel has the same control to fold its flyout back into the rail, including after a tab switch. Both controls preserve the tab group and its menu; other floating groups and full-width docked headers stay as they were. Pointer regressions in `crates/ui-egui/src/panel_docking/tests.rs` cover grouped tabs, reopening, separate groups, a missing rail, the menu and flyout closure after switching tabs; `native_tests.rs` covers the native-window click and removal of the empty palette. Scores and estimates unchanged. @@ -507,6 +512,8 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi ## G12 Preferences and panels that don't act yet +- **Implemented and tested (2026-11-19):** Graphic Styles panel thumbnail and list views have item context menus with Graphic Style Options…, Duplicate Graphic Style, Delete Graphic Style, Redefine Graphic Style, and Break Link to Graphic Style. Right-click on an unselected style selects it first; existing multi-selections are preserved and offer plural commands ("Duplicate Graphic Styles", "Delete Graphic Styles"). Default Graphic Style disables Options and Delete; large preview remains accessible when holding the secondary button. Regression tests in `crates/ui-egui/src/panels/graphic_styles.rs` verify right-click selection, command dispatch, and one-step undo. Scores and estimates unchanged. + - **Production workflow addition (2026-11-18):** Window > Production Preflight brings existing output-aware font/overflow checks, linked-file probes and effective image resolution into one panel. Findings select and zoom to affected art, and results recheck after edits, Undo/Redo and external link changes. Resource-art resolution is explicitly not checked. This does not close the remaining G12 gaps or change estimates. - **Implemented and tested (2026-11-15):** Swatches list rows and thumbnail cells have item context menus with Swatch Options…, Duplicate Swatch and Delete Swatch. Right-click selects the target without painting art; actions use that item's name and are disabled for reserved or missing swatches. All 39 Swatches tests pass, covering all five views, command dispatch, selection and Undo; the regression fails with the menu hooks removed. Rendered list and thumbnail menus were inspected. Full workspace CI passed on Linux/WSL on the merged branch (all 13 gates), including the test-helper correction for the upstream compile error tracked in #7727; native Windows full CI has two unchanged engine-test failures. Other panels without context menus remain in G12; estimate unchanged. @@ -557,6 +564,7 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi run hyphenates in its own language (Character panel). English, eleven Indian languages, Bulgarian, Turkish and Russian have break points, and German, Polish, Portuguese and Italian have them in builds that embed their patterns; other languages stay whole apart from the Exceptions list (#394, #4947). +- **Done (2026-11-19):** Links panel row context menu: right-clicking a link row presents an item context menu offering Relink…, Go To Link, Update Link, Edit Original, Show in Folder, and Embed Image / Unembed…; right-clicking an unselected row selects it first, preserving selection if already part of a multi-selection. Tests in `crates/ui-egui/src/panels/tests_links.rs`. - **Done (2026-11-18, #8592):** Layers panel guide and blend spine row context menus: right-clicking a ruler guide row shows Hide / Show, Lock / Unlock, Release Guides, Delete and Locate Object / Locate Layer (selecting an unselected editable guide or preserving a multi-guide selection); right-clicking a blend spine row selects the blend and shows Select, Blend Options…, Reverse Spine, Reverse Front to Back, Expand, Release and Locate Object / Locate Layer. Tests in `crates/ui-egui/src/panels/layers/tests.rs`. - **Done (2026-11-14):** Layers panel row context menu: right-clicking a layer, group, or object row shows a context menu (Options…, Duplicate, Delete, Lock Others / Unlock All, Hide Others / Show All, Locate Object, Collect for Export) with proper selection behavior and Undo/Redo tracking. Tests in `crates/ui-egui/src/panels/layers/tests.rs`. - **Done (2026-11-18):** Layers panel guide row context menu: right-clicking a guide row presents specialized actions (Release Guide, Duplicate, Delete Guide, Lock/Unlock, Hide/Show). Clicking "Release Guide" converts the guide back to a normal unpainted path using `view.guides.release` in one undo step. Tests in `crates/ui-egui/src/panels/layers/tests.rs`. @@ -715,8 +723,8 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi libraries ([public source](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/create-new-brush-libraries.html), [import](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/import-brushes-from-brush-libraries-or-other-files.html)): Window › Brush Libraries and the Brushes panel's Brush Libraries Menu open each library in a library panel of - its own (fourteen original libraries generated in code: Art Ribbons, Ink and Wash, Calligraphic Nibs, Pressure Sensitive, Bristle Brushes (one - bristle brush for each tip shape), Pattern Borders, Scatter Shapes, Stipple (Fine, Dense, Soft and Bold dot textures), Game Trails, Energy Beams, Dry Media (grainy chalk, pencil, crayon and charcoal art brushes), Tech Circuit (Circuit Trace, Bus Lines and Terminal Nodes), Engraving (Fine, Dense, Tapered and Broken Hatching) and Arrows (Solid, Open, Double, Chevron and Dashed Arrow); User Defined; Other Library… reads the brushes of any document VectorCraft opens); a + its own (fifteen original libraries generated in code: Art Ribbons, Ink and Wash, Calligraphic Nibs, Pressure Sensitive, Bristle Brushes (one + bristle brush for each tip shape), Pattern Borders, Decorative (Leaf Vine, Blossom Chain, Pennant Garland and Lantern String pattern brushes), Scatter Shapes, Stipple (Fine, Dense, Soft and Bold dot textures), Game Trails, Energy Beams, Dry Media (grainy chalk, pencil, crayon and charcoal art brushes), Tech Circuit (Circuit Trace, Bus Lines and Terminal Nodes), Engraving (Fine, Dense, Tapered and Broken Hatching) and Arrows (Solid, Open, Double, Chevron and Dashed Arrow); User Defined; Other Library… reads the brushes of any document VectorCraft opens); a click adds a brush to the document's Brushes with the patterns, symbols and other resources its art uses, as one undo step (applied to the selected paths in the same step), dragging one onto a path adds and applies it and @@ -956,6 +964,9 @@ trap, and the defaults (0.25 pt, 100%, 40%) are VectorCraft's own, the pages giv | Date | Change | Summary | |---|---|---| +| 2026-11-19 | minor | Scissors previews its actual anchor or curve cut point with a native point marker while hovering, retaining existing snapping, Alt Add Anchor and cut behavior (#8655). Scores and estimates unchanged. | +| 2026-11-19 | minor | G12: Brushes panel item right-click context menu offering Brush Options…, Duplicate Brush, and Delete Brush (disabled if the last remaining brush); right-clicking an unselected brush selects it first, and right-clicking within a multi-selection preserves it offering Duplicate Brushes / Delete Brushes; headless tests in `crates/ui-egui/src/panels/brushes/tests.rs`; scores and estimates unchanged. | +| 2026-11-19 | minor | G12: Links panel row context menu (Relink…, Go To Link, Update Link, Edit Original, Show in Folder, Embed Image / Unembed…); right-clicking an unselected link row selects it first, and right-clicking within a multi-selection preserves it; headless tests in `crates/ui-egui/src/panels/tests_links.rs`; scores and estimates unchanged. | | 2026-11-18 | minor | G12: Layers panel context menu on guide rows (Release Guide, Duplicate, Delete Guide, Lock/Unlock, Hide/Show); regression tests in `crates/ui-egui/src/panels/layers/tests.rs`; scores and estimates unchanged. | | 2026-11-18 | minor | G4 type: Retype phase 1 (#4934), `type.retype` for outlined text that exactly matches an available font; near matches, the ranked font list and images remain. Scores and estimates unchanged | | 2026-11-18 | minor | Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged. See [production-preflight.md](production-preflight.md) for scope and limits. | diff --git a/docs/mcp.md b/docs/mcp.md index e73bef1536..5a2c7eeb7d 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -675,25 +675,47 @@ objects' fills or strokes differ (`fillMixed` / `strokeMixed`, drawn as a "?" pr In the app's Color panel and Color Picker, RGB, HSB, hex and Web Safe RGB values describe the active working RGB space. RGB edits preserve the other native channels; HSB uses those same working RGB components. Colors outside display sRGB retain their native numeric values. `ui.colorPanel` selects the panel mode and `ui.colorPicker` -opens the picker through `run_command` with the remote backend. `ui.colorPanel {"recentColors": false}` unchecks -the panel menu's Show Recent Colors, which hides the Color panel's Recent Colors row, and `true` shows it again; -applied colors still join the list while it is hidden. `ui.colorPanel {"rgbPercent": true}` shows the Color panel's -RGB fields in percent, as a double-click right of an RGB field does, and `false` shows them from 0 to 255 again. -`ui.colorRgbPercent` (Toggle RGB Percent in the command palette and Keyboard Shortcuts) switches between the two -and answers true when the fields show in percent. +opens the picker through `run_command` with the remote backend. Edit › Keyboard Shortcuts lists `ui.colorPicker` as +Color Picker… with no default key; a key assigned there opens the picker for the proxy in front, as `{}` does. +`ui.colorPanel {"recentColors": false}` unchecks the panel menu's Show Recent Colors, which hides the Color panel's +Recent Colors row, and `true` shows it again; applied colors still join the list while it is hidden. +`ui.colorPanel {"rgbPercent": true}` shows the Color panel's RGB fields in percent, as a double-click right of an RGB +field does, and `false` shows them from 0 to 255 again. `ui.colorRgbPercent` (Toggle RGB Percent in the command +palette and Keyboard Shortcuts) switches between the two and answers true when the fields show in percent. `ui.colorWheel {"view": "box", "channel": "red"}` shows the Color Wheel panel's box (a color field with the channel's strip at its right) in place of the wheel, as the panel menu's Box View and Box Channel do, and `"view": "wheel"` -shows the wheel again. `{"harmony": true, "harmonyRule": "triad"}` puts a marker on the wheel's ring for each other +shows the wheel again. `"gamut": true` grays out the parts of the wheel's square and the box's field whose colors +the CMYK space cannot print, as the panel menu's Show Out-of-Gamut Colors does, and `false` shows them again. The +test is the out-of-gamut warning's, which `color.gamutCheck` answers for one color. The shading is approximate: the +panel tests the color at the center of each cell of a 16 by 16 grid over the square or the field and grays out the +whole cell or none of it, so a grayed cell can hold printable colors and a clear cell can hold colors that cannot +print. `{"harmony": true, "harmonyRule": "triad"}` puts a marker on the wheel's ring for each other color of a Color Guide harmony rule, as Show Harmony and Harmony Rule do; the wheel takes the 15 rules whose colors each have a hue of their own (not `monochromatic`, `shades`, `complementary2`, `triad2`, `triad3` or -`highContrast2`). Keys left out keep their values. Params that are not an object, another key or a value off -the list return an error and change nothing. The command returns `{view, channel, harmony, harmonyRule, vision}`, +`highContrast2`). `{"documentColors": true}` shows the row the panel menu's Show Document Colors adds under the wheel +or the box. Keys left out keep their values. Params that are not an object, another key or a value off +the list return an error and change nothing. The command returns `{view, channel, sliders, gamut, harmony, harmonyRule, vision, documentColors}`, and the settings are kept with the preferences. + +`ui.colorWheel {"sliders": "oklch"}` shows the Color Wheel panel's OKLCH Sliders (L, C and H rows under the wheel or +the box), and `"none"` hides them in any RGB space. `"oklch"` is an error while the active document's RGB space is +not sRGB: the profile assigned to the document when it has one, else the working RGB space of Edit › Color Settings. +`ui.colorWheel {"sliders": "hsl"}` shows HSL Sliders in their place: H, S and L rows with the hue (0 to 360°), +saturation and lightness (0 to 100 %) of the color's display sRGB, as CSS Color 4's `hsl()` defines them. +`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 and tritanopia simulations of `view.proofSetup`, and for achromatopsia as the gray with the color's CIE L*. Each chip reports its name and hex value to screen readers, and a click on a chip does not apply its color. `false` hides the row, and `null` keeps the setting. Any other value returns an error and changes nothing. +`ui.colorWheel {"documentColors": true}` shows the Color Wheel panel's row of the colors the selection uses, or with +nothing selected the colors of the art `select.all` takes, in the order `color.used {}` lists them. A click on a color +applies it to the active proxy, keeping its link to a global swatch. The answer includes `documentColors` +with the other settings, and the setting is kept with the preferences. 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 @@ -1620,7 +1642,12 @@ their stop opacity and stop where the shading doesn't extend. Text becomes point the file's font (by name; fonts that aren't available are listed in `warnings` and show in the fallback font, and every export that draws that type — PDF, EPS, EMF/WMF, raster images, SVG with outlined or embedded fonts — says in its `warnings` that it wrote the fallback font) — `textAs: "outlines"` keeps the glyph outlines the file draws instead -(its embedded fonts, installed or not). Lines wrapped in a frame (each wrapped line ending in a space, sharing a left +(its embedded fonts, installed or not). In the app, the Import PDF and Place PDF dialogs' Text choice (Editable or +Outlines) sends `textAs`; for a PDF it starts from the `pdfTextAs` preference and OK keeps the choice there (a +`.ai` or `.ait` file starts from Editable). Outlines clears +Import PDF pages as links, and a linked place dims the choice: a linked page shows the file's own text. A PDF that opens +or is placed embedded without the dialog (one page, or Show Import Options off) takes `pdfTextAs` when its params +give no `textAs`; a `.ai` or `.ait` file, and an open with `linkPages`, open as their params say. Lines wrapped in a frame (each wrapped line ending in a space, sharing a left edge, font and leading) come back as one area type object, left aligned or justified, where laying it out breaks the lines where the file does; a stroke written as each glyph's outline stroked is the type object's stroke; glyphs set apart by gaps wider than a space keep their places. Strokes stay live strokes (width, cap, join, miter limit, dash and paint), and @@ -2335,7 +2362,7 @@ naming the key, and leave the document and its undo history as they were: `opaci The blend and envelope commands refuse a string, a number or another value that is not true or false with `` `smooth` must be true or false ``, naming the key, and leave the document, its undo history and the options new blends and envelopes start with as they were: `smooth` in `object.blend.make` and `object.blend.options`; -`independent` and `link` in `object.blend.spine.moveAnchor`; `perpendicular` in `object.blend.spine.reshapeSegment`; `horizontal` +`independent`, `symmetric` and `link` in `object.blend.spine.moveAnchor`; `perpendicular` in `object.blend.spine.reshapeSegment`; `horizontal` in `object.envelope.makeWithWarp`, `resetWithWarp` and `options`, also when an `orientation` is given; `maintainShape` in `object.envelope.resetWithMesh`; `antiAlias`, `distortAppearance`, `distortLinearGradients` and `distortPatternFills` in `object.envelope.options`; and `editing` in `object.envelope.editContents`. A null is read as @@ -3482,6 +3509,16 @@ enabled while the document has a saved view. In the desktop app the views are li checked when it opens: past 25, blank or repeated names, and views without a finite centre and a positive zoom are dropped. +## Recent commands + +Help › Search Commands… keeps the last commands, tools, panels and effects picked from it, most recent first: an +empty search lists them, and so does the Recent Commands list beside the search field. The desktop app saves the ids +with the UI state, and also how many times each command was picked, which ranks the results. +`help.clearRecentCommands {}` (Clear Recent Commands) empties the list, the saved ids and the pick counts, and +returns `null`. A pick of it in the search is not kept as a recent pick or counted. It is a UI command, so it needs +the desktop app (`--connect`); `command_list` gives it `enabled: false` while no ids and no counts are saved. Saved ids +the list leaves out, such as those of a plug-in that is not loaded, count as saved and are cleared with the rest. + ## Messages over the window `app.toast {message, level?, seconds?}` shows a short message over the desktop app's window without stopping work @@ -3881,23 +3918,34 @@ already walks Image Trace. Short agent entry points: [the archived manual](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=118)): `symbol.adjust` takes `method` (`userDefined`, `average` or `random`; not used by `shift`), `usePressure` with `points` as `[x, y, pressure]` (each point's pen pressure, 0..1, is the intensity there), and for `size` - `proportional` (true) and `affectsDensity` (false). `symbol.spray` takes `attributes` + `proportional` (true) and `affectsDensity` (false). With `tool: style`, the style goes on by the brush's strength at + each instance: one sample applies it in full only at the brush's center at intensity 10 or full pressure, and the + samples of a stroke add up (two samples at the center at intensity 5 apply it in full). With `alt`, `userDefined` + and `random` remove all of an instance's appearance items under the brush at once, whatever the brush's strength. + A `style` name the document + has no graphic style for counts as none (the document's first style after the default one). The Symbol Styler and the + Symbol Sprayer (its User Defined Style) send the style last clicked into the Graphic Styles panel's selection. `tool.setOption` on a symbolism tool refuses a `method` or + Symbol Sprayer option that is not one of its names, a non-number `diameter`, `intensity` or `density`, a + `diameter` outside 2..2000 or an `intensity` or `density` outside 1..10, a non-boolean switch, and a `symbol` or + `style` that is neither a name nor null, and sets none of the values. The options dialog's OK checks the same way + before it changes any symbol set's density. + `symbol.spray` takes `attributes` `{scrunch?, size?, spin?, screen?, stain?, style?}`, each `average` or `userDefined`, with `color`, `keepModel` and `style` for the User Defined stain and style (with `style: userDefined`, a `style` the document does not have is an error). `symbol.setDensity {from, to, ids?|id?}` gives the selected symbol sets a new Symbol Set Density. VectorCraft's own rules: - `random` gives each instance its own share of the tool's change for the whole stroke, from none of it to twice - it (the Spinner: a turn either way), the same each time the stroke is applied. + it (the Spinner: a turn either way; the Styler without `shift`: from none to the `userDefined` amount), the same + each time the stroke is applied. - `average` moves each instance's value toward the mean of the instances within the brush at that point: the Scruncher its distance from their middle toward their mean distance, the Sizer the geometric mean of their sizes on the page, whatever their symbols, the Spinner their mean direction, the Stainer and the Styler their mean amount, the Screener their mean opacity. `alt` does not reverse it. An instance already at the mean is left as it is, and no undo step is added when no instance changes. The Screener's average, and the opacity a sprayed instance takes as its average, can be below the 5% that the Screener otherwise stops at. - - With `userDefined` the Styler gives each instance under the brush the whole style, whatever the intensity or the - pen pressure; `random` scales each instance's share by the brush strength there. - - With `proportional` false a drag resizes along its own direction (a level drag the width, an upright one the - height) and one point resizes both. With `affectsDensity` an instance also moves away from the point as it grows + - With `proportional` false a drag resizes along its own direction: the width by the drag's horizontal share and + the height by its vertical share (a level drag the width, an upright one the height, a 45° drag both alike), and + one point resizes both. With `affectsDensity` an instance also moves away from the point as it grows and toward it as it shrinks. - A sprayed instance's `average` values are the means of the selected set's instances within `radius` of the stroke point: their spacing, size on the page (of any symbol), rotation and opacity, and the stain or style of @@ -3907,15 +3955,31 @@ already walks Image Trace. Short agent entry points: - `symbol.setDensity` moves each instance of a set along the line from the middle of the set's instances, to (1.15 − 0.1·`to`) / (1.15 − 0.1·`from`) of its distance from it (each factor at least 0.1), as one undo step, and adds none when no instance moves and every set already has density `to`. `from` is the density each set was - created at or last given, and the `from` passed applies only to a set without one (a group named "Symbol Set" by + created at or last given (a set duplicated has its source's, and a pasted set the one its source had at Copy), + and the `from` passed applies only to a set without one (a group named "Symbol Set" by hand); every set then has density `to`, also one whose instances do not move (one instance, or each locked). A locked or hidden instance stays where it is. It returns `{ids, count}`: the sets changed and the instances moved. - A `method` or an attribute outside these values, a point's third number that isn't a number (in `symbol.spray` too, which does not use it), a `from` or `to` of `symbol.setDensity` outside 1..10, or no symbol set among its - objects, is an error and changes nothing. + objects, is an error and changes nothing. `symbol.spray` takes a `density` number outside 1..10 as the nearer end. - Average leaves an instance without a size (a scale of 0) as it is; the other methods change it. A stroke that changes no instance counts none and adds no undo step. +- The symbolism tools with Shift held ([the manual](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=199), + [the CS6 reference](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=136)) send + `shift: true` with `symbol.adjust`: a Shift-click with the Symbol Shifter brings the instances under the brush + forward in the stacking order and Alt+Shift sends them backward; the Symbol Sizer keeps the set's density while it + resizes; the Symbol Stainer and the Symbol Styler keep the amount of stain or style and move the color or style + toward the current fill or the selected style. VectorCraft's own rules: + - The Shifter moves each instance within `radius` of any stroke point one place forward among its siblings (with + `alt`, one place backward), past the next one that is not under the brush, once for the whole stroke. It does not + move them on the canvas. It returns `{count}`, the instances that moved. + - The Sizer keeps each instance's center where it is, even with `affectsDensity`. + - The Stainer moves an instance's paint toward `color` by the tool's amount at its distance from the point, and the + Styler toward the style by the brush's strength there, whatever `method` is. A paint with no form between it and + the new one (a solid color and a pattern) takes the new one at once. An instance without a stain or style is left + as it is, and `alt` has no effect. + - No undo step is added when nothing moves or changes. - Dynamic symbols: an instance of a symbol whose `type` is `dynamic` changes the appearance of objects in the symbol's art for itself only and stays linked. `symbol.instance.setAppearance {id?, path, fill?, stroke?, opacity?, blend?}` names the object by `path`, child indices in paint order from the art's root down through its groups (`[]` is the @@ -4625,8 +4689,23 @@ already walks Image Trace. Short agent entry points: `builtIn: true`, then the saved ones with `builtIn: false`, and returns a `revision` that grows each time the saved presets change. `imageTrace.make {preset}` takes a saved preset's name, with ASCII letters matching in either case. Its journal entry records the saved preset's settings as `savedPreset`, so a replay traces with them after the preset - is changed, renamed or deleted. In the app, - `ui.imageTracePresetDialog {params?, rename?}` opens the Image Trace panel's Save as New Preset… or Rename… dialog. + is changed, renamed or deleted. `imageTrace.presets.export {names?, path?}` writes saved presets (default: every one; + a built-in preset's name is an error) as a `.vctracepresets` file, VectorCraft's own JSON layout + (`{"format": "vctracepresets", "version": 1, "presets": [{"name", "params"}]}`), to `path`, else returns its text as + `data`; it refuses more than 1,000 presets or a file over 4 MiB, the limits of the import. + `imageTrace.presets.import {path? | data? | dataBase64?, replace?}` adds the presets of such a file (at most + 4 MiB and 1,000 presets) → `{imported, replaced, skipped}`: a preset with a saved preset's name is skipped unless + `replace` is true. Every preset in the file is checked first, and a file with a built-in preset's or `Custom`'s name, + two presets of one name, a preset without a name or `params`, settings `imageTrace.presets.save` refuses, or a newer + `version` changes nothing. In the app, opening a `.vctracepresets` file (File › Open, a drop, or the file picked + for Import… on the web) imports it as Import… does. Also in the app, + `ui.imageTracePresetDialog {params?, rename?}` opens the Image Trace panel's Save as New Preset… or Rename… dialog, + and `ui.tracingPresetsDialog {selected?}` opens Edit › Tracing Presets…: the built-in presets in brackets (read-only) + and the saved ones, with the selected preset's settings. Its New… (from the selected preset) and Edit… (a saved + preset) open an editor with the Image Trace panel's settings; OK saves with `imageTrace.presets.save` and Cancel saves + nothing, and a built-in preset's name, `Custom` or another saved preset's name keeps the editor open. Delete selects + the saved preset below the deleted one, else the one above it, else Default. Import… asks whether to replace saved presets whose names the file holds (Cancel + keeps them), and Export… writes every saved preset. - Live Paint: `livePaint.make`, `livePaint.merge`, `livePaint.fill {group?, point}`, `livePaint.strokeEdge`, `livePaint.info {group?|id?}`, `livePaint.release`, `livePaint.expand`, and `livePaint.gapOptions {ids?, detect?, size?, color?, closeGaps?}` (Object › Live Paint › Gap Options). Make gives each covered face the fill rows that draw of @@ -4768,7 +4847,13 @@ already walks Image Trace. Short agent entry points: Appearance panel's active row changes. The Fill and Stroke proxies (`paint.proxies`) show those colors, never mixed, the Stroke panel shows that stroke as it does with nothing selected, and with New Art Has Basic Appearance off the selection's appearance does not replace them after a command. They are also the fill and stroke for new art, so another tool chosen - afterwards keeps them until a command or a new selection changes them. + afterwards keeps them until a command or a new selection changes them. All of this also holds while a Cmd/Ctrl-click + with the bucket uses the Selection tool, and while the Eyedropper samples into a stop of the bucket's gradient for + the Gradient panel's eyedropper (`tool.select {tool: "eyedropper"}`, then + `tool.setOption {tool: "eyedropper", values: {stop: "livePaintBucket"}}`): the stop + stays selected, and the click's `paint.sampleColor {color, stop}` recolors that stop of the bucket's gradient and + leaves the selection's paint as it is. Once that stop is no longer selected (a Cmd/Ctrl-click selected another + object), the next click ends the pick without sampling and switches back to the bucket. With the Live Paint Bucket selected and no drag in progress, Left and Right without Shift, Alt or Cmd/Ctrl (which keep their shortcuts) run `paint.setFill {swatch, ids: []}` (or `paint.setStroke` when the Stroke proxy is in front) with the color swatch before or after the active paint in the @@ -4798,15 +4883,23 @@ already walks Image Trace. Short agent entry points: `paint.none` paint the faces or the edges. `paint.editGradient`, `paint.setGradientGeom` and the `paint.freeform` point and line edits change the faces' or the edges' gradients, `paint.invert` and `paint.complement` recolor the faces' fills or the edges' strokes, and `stroke.set`, `stroke.weightUp`, `stroke.weightDown` and - `stroke.setAdvanced` change the edges. The Fill proxy shows the faces' fill, and the Stroke proxy, the Stroke panel - and the Control bar show the edges' stroke. A face or edge selected or given together with its whole group follows - the group's rule: a fill does not reach an edge, and a stroke does not reach a face. `paint.swap` gives the faces - the stroke the edges share and gives the edges the fill the faces share, with a gradient fitted to each face or - edge. It leaves a group as it is when its faces' fills or its edges' strokes differ, when any of them is a freeform - gradient, or when it has no face or no edge. `paint.default` replaces each face's appearance with no fill and each - edge's appearance with a 0.5 pt black stroke, also when the document's Default Graphic Style is redefined. With - only Live Paint groups selected or given, the fill and stroke for new art become no fill and a 0.5 pt black stroke; - with New Art Has Basic Appearance off, new art then takes the selection's appearance, as after any command. + `stroke.setAdvanced` change the edges. `object.setOverprint` sets the faces' fill overprint and the edges' stroke + overprint. `appearance.copyFrom` (the Eyedropper) gives the picked fill attributes to the faces and the picked + stroke attributes to the edges, also onto a group given as `source` with `reverse`. A whole-appearance pick gives + each face every picked fill row and each edge every picked stroke row, and the faces and edges keep their rows of + the other kind and their effects; `append` adds the source's rows to them but not its object effects. A whole group + picked up as the source (given as `source`, or selected first with `reverse`) gives its first face's fills with its + first edge's strokes above them, and the group's own opacity, blend mode and effects. The Fill proxy shows the + faces' fill, and the Stroke proxy, the Stroke panel and the Control bar show the edges' stroke, whatever the order of + a selection that holds the group, directly or inside a selected group, and some of its parts. A face or edge + selected or given together with its whole group follows the group's rule: a fill does not reach an edge, and a + stroke does not reach a face. `paint.swap` gives the faces the stroke the edges share and gives the edges the fill + the faces share, with a gradient fitted to each face or edge. It leaves a group as it is when its faces' fills or its + edges' strokes differ, when any of them is a freeform gradient, or when it has no face or no edge. `paint.default` + replaces each face's appearance with no fill and each edge's appearance with a 0.5 pt black stroke, also when the + document's Default Graphic Style is redefined. With only Live Paint groups selected or given, the fill and stroke + for new art become no fill and a 0.5 pt black stroke; with New Art Has Basic Appearance off, new art then takes the + selection's appearance, as after any command. `brush.selectionArt {ids?|id?}` (a query) replies `{art}`: the object that `brush.new` given the same `ids` or `id`, or the same selection, takes as a new scatter or art brush's art and as a new pattern brush's side tile. Several @@ -5169,7 +5262,7 @@ it, masks that member's solids ([three-d.md](three-d.md#groups)). `threeD.extrude`: `depth` (points, 0..2000, default 50), `twist` (degrees, 0..360, 0), `taper` (1..100%, 100), `cap` (true solid, false hollow), `bevel` (`none`, `classic`, `rounded`, `cove`, `step`, `ogee`), `bevelWidth` and `bevelHeight` (points, default 4), `bevelRepeat` (1..32), `bevelSpace` (0..90%), `bevelInside`, -`bevelBothSides`. `threeD.inflate`: `depth` (points, default 0), `twist` (degrees, 0..360, 0), `taper` (1..100%, 100), `cap` (true +`bevelBothSides`; `bevel` `custom` with `bevelName` and `bevelProfile` is a custom bevel (below). `threeD.inflate`: `depth` (points, default 0), `twist` (degrees, 0..360, 0), `taper` (1..100%, 100), `cap` (true solid, false open behind), `volume` (0..100%, default 50), `bothSides`. All three take `rotationX/Y/Z` (degrees, -180..180, default the Off-Axis Front position -21.88/-23.4/9.06), `perspectiveAngle` and the lighting parameters as Revolve. See [three-d.md](three-d.md) for the Position presets, @@ -5181,12 +5274,47 @@ points returns "The shape is too complex for a 3D effect", and one whose faces d has so many points across so many of its grid's cells that filling the grid would pass its work limit. `threeD.rotate` takes up to 65,536 points. +Custom bevels come from the bevels file, `Bevels.vectorcraft` next to the preferences (none on the web or in runs +with `VECTORCRAFT_NO_PREFS`). `threeD.bevels.edit` (3D and Materials panel › Bevel Shape › Edit Bevels…) opens it, +and first creates it with one example bevel when it is missing. Each symbol whose art is one open path is one bevel, +named after the symbol and listed after the built-in shapes. These rules are VectorCraft's own: the path runs from its +first anchor at the cap's edge to its last at the side wall, across the page across the bevel's width and down the +page along its height, and curves are cut into straight lines of at most 64 points. The file is read when the app +starts and again each time VectorCraft saves it; `threeD.bevels.reload` reads it again. A file larger than 64 MB is +not read, at most 256 symbols are read, and a symbol that is not one open path, has more than 4,096 anchors, is cut +into more than 8,192 straight lines, needs more point-to-line distances to simplify than are left of the 40,000,000 +the file may take, has ends that are not apart both across and down, or repeats an earlier name is +listed in `skipped`. `threeD.bevels.list` +returns each bevel's `name` and `points`, the `file` path, the `skipped` symbols and any read `error`. + +Under automation read roots, the bevels file counts as a path the client did not give. `threeD.bevels.list` returns +`file` as `null` when the file is outside the read roots, and its `error` names the file by its file name; the bevels, +`skipped` and the reason stay. `threeD.bevels.edit` and `threeD.bevels.reload` refuse a file outside the read roots +with the root-check error, naming the file by its file name: `edit` then makes no folder or file and neither opens the +file nor brings it to the front, and `reload` does not read it. Inside the read roots, `edit` opens the file under the +client's roots. The 3D and Materials panel's Edit Bevels… is not confined. + +`threeD.extrude` and `threeD.classicExtrude` take `bevel: {"custom": name}` in `effect.apply` and `effect.setParams`, +and store it as `bevel: "custom"` with `bevelName` and `bevelProfile`, a copy of the points (`[[x, y], …]`, 2 to 64 +shares 0..1 of the width and height from `[0, 0]` to `[1, 1]`), so the document draws the bevel without the file. An +unknown name, `custom` without `bevelProfile`, points that do not run from `[0, 0]` to `[1, 1]` within 0..1, or a +`bevelName` that is not a string is refused and the document is not changed. The command's journal entry records the +points as `savedBevel`, and `savedBevel` given with `{"custom": name}` is used in place of the file's points, so a +replay draws the same bevel after the file changes or drops the name. The help page +[Add custom bevel paths](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/add-custom-bevel-paths.html) +describes custom bevels drawn as open paths and kept as symbols in a bevels document. + +```json +{"name":"run_command","arguments":{"command":"threeD.bevels.list","params":{}}} +{"name":"run_command","arguments":{"command":"effect.apply","params":{"effect":"threeD.extrude","item":null,"params":{"bevel":{"custom":"Example Bevel"},"bevelWidth":8,"bevelHeight":8}}}} +``` + ## Extrude & Bevel (Classic) `effect.apply {effect: "threeD.classicExtrude", params: {...}, ids?, item?}` is Effect › 3D and Materials › 3D (Classic) › Extrude & Bevel (Classic)…. It builds the same solid as `threeD.extrude` and draws its faces with the classic surfaces. Parameters: `depth` (points, 0..2000, default 50), `cap` (true solid, false hollow), `bevel` (`none`, -`classic`, `rounded`, `cove`, `step`, `ogee`), `bevelHeight` (points, 1..100, default 4; the bevel is as wide as it +`classic`, `rounded`, `cove`, `step`, `ogee`, or a custom bevel as for `threeD.extrude`), `bevelHeight` (points, 1..100, default 4; the bevel is as wide as it is tall), `bevelInside` (false adds the bevel around the shape, true carves it into the shape), `rotationX/Y/Z` and `perspectiveAngle` as above, and the surface: @@ -5573,7 +5701,13 @@ fills and strokes above it paint over the members (characters), those below unde `contents` to say where the row ends up in the same undo step; `document.node` shows the slot as `appearance.contents_index`. The `appearance.*`, `effect.*` and `graphicStyle.apply` commands edit the selected objects themselves (a group's own stack; layers through `ids`) or, with `target: "contents"`, the objects inside the -groups and layers. `appearance.targetContents` selects a group's members (double-clicking the Contents row). +groups and layers. In a Live Paint group those are its faces and edges, not its hidden source paths. +`appearance.addFill` adds a fill to the faces only, and `appearance.addStroke` adds a stroke to the edges only; a selected group left with only its hidden source paths is returned without a change. A +fill or stroke command with an `item` and `target: "contents"` (such as `paint.setFill`, `stroke.set`, +`paint.invert`, `paint.setGradientGeom` and `object.setOverprint`) changes the faces for a fill row and the edges for +a stroke row. The row commands (`appearance.setItem`, `appearance.removeItem` and the others) find their rows on each +face and edge as on any other object in the contents. +`appearance.targetContents` selects a group's members (double-clicking the Contents row). SVG and PDF export bake a group's own fills, strokes and geometry effects into paths; its raster effects stay a filter on the whole group in SVG and become an image of the whole group in PDF. A geometry effect on one of type's own fills or strokes (`effect.apply` with `item`) reshapes the whole outline that @@ -5662,15 +5796,28 @@ document's swatches, as a library to add from. From an `.ase` file it reads RGB, spot or process swatches and keeps their color groups. A color book (such as a Pantone book you own) gives its RGB, CMYK or Lab colors named with the book's prefix and suffix ("PANTONE 185 C"), as spot colors unless the book marks them as process colors; `.acb` files are read, never written. A file in the user library folder, or a file with the -same extension and bytes as one there, loads as that User Defined library (category `user`). +same extension and bytes as one there, loads as that User Defined library (category `user`). A file larger than 256 MB +is refused before it is read. From a document, such as a `.ai` or `.eps` swatch library, it reads the colors, tints, gradients and pattern swatches in the document's order and color groups; `swatch.library.add` brings a pattern swatch's pattern, with its tile and art, into the document as a pattern swatch under the library swatch's name and in its color group. A global or spot color the pattern's art links to keeps the library's color: when the document gives its name another color, it comes in under a numbered name ("Ink 2") and the pattern links to that. A document with no swatches, and a `.ai`, `.eps` or PostScript file whose swatches are only the default ones, are refused with -"`` has no swatches of its own". The Swatch Libraries filter of Other Library… lists `.ai`, `.ait` and `.eps` -(`.epsf`) files as well as the library files. +"`` has no swatches of its own", unless the document has graph designs: it then loads with no swatches. The +Swatch Libraries filter of Other Library… lists `.ai`, `.ait` and `.eps` (`.epsf`) files as well as the library files. +A document's graph designs come with it: the reply's `graphDesigns` counts them, and +`graph.column`, `graph.marker` and `graph.design` take the library's id as `library` until the app quits (a User +Defined copy made with `swatch.library.copyToUser` holds the swatches alone, so the designs stay under the loaded id). +`graph.column {design, library}` and `graph.marker {design, library}` copy a design the document lacks into it, with the +swatches, patterns, symbols, styles, brushes and images its art uses, in the same undo step as the graph change. +`graph.design {library, add: name | [names]}` copies designs without applying them and returns `{added, existing}`, and +`graph.design {library}` lists the library's designs. A design the document already has under the same name stays as it +is. `graph.column` and `graph.marker` with no `design`, and `graph.design {}`, list the loaded libraries that hold +designs as `libraries: [{library, name, designs}]`. Copying a graph and pasting it into another document brings the designs its series +draw with in the same way; a pasted graph is drawn again with the document's design of that name when that design +would draw it otherwise. The graphs already in the document that draw with a design the copy or paste adds, one a copied +design's art uses included, are drawn again with it. `swatch.library.copyToUser {library}` copies a loaded library into the user library folder of the desktop app (a library file as it is; a document's swatches or a library loaded from `data` or `dataBase64` as `.vcswatches`; a library with pattern swatches is refused) under a name no file there has, and lists it as User @@ -5752,12 +5899,15 @@ error. ## Brush libraries -Brush libraries are read-only sets of brushes: fourteen generated in code (Art Ribbons, Ink and Wash, Calligraphic Nibs, Pressure Sensitive with Flex Ribbon, Pulse Stroke, Round Flow and Chisel Flow, Bristle -Brushes with one bristle brush for each tip shape, Pattern Borders, Scatter Shapes, Stipple with Fine, Dense, Soft and Bold dot textures, Game Trails, Energy Beams, and Dry Media with the Chalk Grain, Graphite Pencil, Wax Crayon and +Brush libraries are read-only sets of brushes: fifteen generated in code (Art Ribbons, Ink and Wash, Calligraphic Nibs, Pressure Sensitive with Flex Ribbon, Pulse Stroke, Round Flow and Chisel Flow, Bristle +Brushes with one bristle brush for each tip shape, Pattern Borders, Decorative with Leaf Vine, Blossom Chain, Pennant Garland and Lantern String, Scatter Shapes, Stipple with Fine, Dense, Soft and Bold dot textures, Game Trails, Energy Beams, and Dry Media with the Chalk Grain, Graphite Pencil, Wax Crayon and Charcoal Dust art brushes, id `dry-media`, Tech Circuit with Circuit Trace (art), Bus Lines and Terminal Nodes (pattern), id `tech-circuit`, Engraving with Fine Hatching, Dense Hatching, Tapered Hatching and Broken Hatching art brushes, id `engraving`, and Arrows with Solid, Open, Double, Chevron and Dashed Arrow art brushes, id `arrows`), the `.vectorcraft` files in the user library folder of the desktop app (User Defined) and the brushes of any document loaded with `brush.loadLibrary` (a document without brushes of its own has the default ones). `brush.libraries` lists them (`id`, `name`, `category`: `builtIn`, `user` or `loaded`, `count`) and -`brush.library {library}` returns one's brushes (`name`, `type`; `library` is an id or a name). +`brush.library {library}` returns one's brushes (`name`, `type`; `library` is an id or a name). A name +that a built-in library and a User Defined or loaded library share selects the built-in one; select the other by its +`user/…` or `loaded/…` id. The exact id `artistic` selects the built-in Artistic Brushes library, and `Artistic` +selects it too when no library is named `Artistic`. `brush.addFromLibrary {library, name? | names?}` copies brushes into the document's Brushes as one undo step (no names: the whole library), with the resources their art uses: patterns, symbols, swatches (`swatchConflict` as for `edit.paste`), graphic styles and images. Brushes the document already has (same name and definition) are reported @@ -6064,6 +6214,26 @@ at the back in Minus Front, or a line in front in Minus Back), the error says so {"name":"run_command","arguments":{"command":"object.pathfinder.options","params":{"precision":0.1,"removeUnpainted":true}}} ``` +Each Effect › Pathfinder effect (`pathfinder.add` … `pathfinder.softMix`, not Trap) keeps Pathfinder Options of its own +in its params: `precision` (a number, 0.001–10 pt), `removeRedundantPoints` and `removeUnpainted` (true or false), which +mean what they mean for the panel's operations; the other operations ignore `removeUnpainted`. With `removeUnpainted` +on, a compound shape's area counts as filled when the shape has a visible fill of its own, and Divide keeps every piece +when the group or compound shape has one. Outline strokes a compound shape's area in the shape's own fill. `effect.apply` +fills the ones `params` leave out from the current Pathfinder Options, and the values join its journal entry. An effect +saved without them evaluates with precision 0.01 and both switches off, as before effects kept them. `effect.setParams +{index, params: {precision?, removeRedundantPoints?, removeUnpainted?}}` edits them as one undo step; values the +effect already evaluates with record no undo step and return `{ids: []}`. A precision out of range, or a switch that +isn't true or false, is refused with an error and nothing changes. Scale Strokes & Effects scales `precision` with the +object (0.01 when it is missing), and the stored value may then pass 10 or fall below 0.001; the effect evaluates at +the nearest bound, and setting a precision that differs from the stored one is an edit, the bound included. In the app, +a Pathfinder effect's name or a double-click on its row in the Appearance panel opens Pathfinder Options for it (Soft +Mix's dialog also has Mixing Rate). A stored precision out of range opens at the bound, and OK keeps the stored value +unless Precision is set. + +```json +{"name":"run_command","arguments":{"command":"effect.setParams","params":{"index":0,"params":{"precision":1,"removeRedundantPoints":true}}}} +``` + Compound shapes (the Pathfinder panel menu, and Alt-clicking a Shape Mode button): `object.compoundShape.make {mode?, ids?}` makes the two or more selected objects (paths, compound paths, groups, compound shapes, type, blends, envelopes) the members of one live compound shape, each in shape mode `mode` (`"add"`, the default, `"subtract"`, @@ -6751,6 +6921,14 @@ is not a whole number of 0 or more, such as 1.5, -1 or "1" ("`subpath` must be a an `anchor` or `segment` in the same way. The document does not change and no undo step is recorded. `path.moveAnchor` to the point the anchor is at, and `path.setHandle` to the point the handle is at on an anchor that keeps its kind, leave the document as it is and record no undo step. +`path.setHandle` with `symmetric: true` also places the anchor's other handle opposite the moved one at the same +length, and the anchor keeps its kind. At an open end, where no segment leaves the anchor on the other side, +`symmetric` has no effect and the handle moves as it would without it. Both `symmetric` and `independent` default to false, and a call with both true is +refused with `` `independent` and `symmetric` cannot both be true ``; the document does not change and no undo step +is recorded. Direct Selection sends `symmetric` while Cmd/Ctrl is held during a handle drag, unless that Cmd/Ctrl +press lent Direct Selection for the gesture while another tool, such as the Pen, was chosen and has not been let go +since (#7842). A call that puts both handles where they already are records no undo step. `symmetric: true` with `link: true` is refused +("`link` and `symmetric` cannot both be true"), and so is `symmetric: true` with `link: true` in `object.blend.spine.moveAnchor`. `path.setHandle` with `link: true` (the Anchor Point tool's Alt-drag on a handle) places the handle and makes the anchor smooth: the other handle turns to lie in line on the far side of the anchor and keeps its length. A retracted other handle is pulled out to the placed handle's length when a segment leaves the anchor on its side, and stays @@ -6877,7 +7055,7 @@ Left out or null, `width` is 8 pt. The range is VectorCraft's own value. These commands refuse a string, a number or another value that is not true or false with `` `closed` must be true or false ``, naming the key; the document does not change and no undo step is recorded: -`independent` in `path.close` and `path.setHandle`; `link` in `path.setHandle`; `patterns` in `path.moveAnchors`; `closed`, `keepSelected` and +`independent` in `path.close` and `path.setHandle`; `symmetric` and `link` in `path.setHandle`; `patterns` in `path.moveAnchors`; `closed`, `keepSelected` and `fill` in `path.freehand` (and in `brush.freehand`); `closed` and the `corner` of a point in `path.curvature`; `corner` in `path.curvatureEdit`; `perpendicular` in `path.reshapeSegment`; and `keepSelected`, `mergeOnlySelection` and `merge` in `path.blob`. A null is read as a key left out. @@ -6992,8 +7170,9 @@ slider back to the Auto-Smooth level. ## Circle through two or three points -`shape.circleThroughPoints {points?: [[x, y], [x, y]] or [[x, y], [x, y], [x, y]]}` draws the circle whose edge passes -through the points, as a live ellipse with the current paint, and selects it. Two points are the ends of a diameter. +`shape.circleThroughPoints {points?: [[x, y], [x, y]] or [[x, y], [x, y], [x, y]], anchors?}` draws the circle whose +edge passes through the points, with the current paint, and selects it: a live ellipse with the default +`anchors: "standard"`, and a plain path with `anchors: "points"`. Two points are the ends of a diameter. Without `points`, it uses the two or three selected anchor points, from one path or several: anchor points selected with Direct Selection, or all the anchor points of a path selected whole, such as a triangle. The ends of selected segments do not count. The result is `{id, cx, cy, radius}`, and one undo removes the circle. The circle is not pixel-aligned, @@ -7003,6 +7182,12 @@ one line (twice the triangle's area at most 10⁻¹⁰ of its longest side squar canvas (4,000,000 pt from the origin), when `points` is not two or three pairs of numbers, and when `points` is left out and the selection does not hold two or three anchor points of paths. +`anchors` sets where the circle's anchors go. With `"standard"`, the default, the circle has four anchors at 0°, 90°, +180° and 270°. With `"points"`, the circle is a plain path with an anchor exactly at each point, and more anchors +between them, evenly spaced, so that no curve turns more than a quarter of the circle: two points give four anchors, +and three points give four to six. Any other `anchors` value is an error (`` `anchors` must be one of standard, points ``), and nothing +is drawn. + The Circle tool, after the Ellipse tool in its toolbar group, draws with this command. A drag from one point to another, or a click on each, draws the circle with the two points as the ends of a diameter. A click on a first point, then a press on a second point dragged to a third, draws the circle through the three. Shift keeps the second point at @@ -7018,6 +7203,28 @@ Escape, a dropped press, and an edit, Undo or Redo made outside the tool drop th screen points of the first point, or one that snaps to it, is a press on it: let go there (a double-click), it places no second point, and dragged out, it draws the circle on the diameter it drags out. +Circle Tool Options (`tool.options {tool: "circle"}`, or a double-click on the tool, dialog `circleOptions`) sets the +tool's options, which `tool.setOption {tool: "circle", values}` also sets and the preferences keep. All are on by +default, and `color` is `"blue"`: + +- `center`, `radii` and `diameter` (Show Center, Show Radii, Show Diameter) show or hide the cross at the center, the + lines from the center to the points and the diameter label. The diameter label also needs Measurement Labels on. +- `color` (Color) is the color of the cross and the lines: `"red"`, `"blue"`, `"magenta"`, `"green"`, `"black"` or + `"gray"`. The outline stays blue. +- `standardAnchors` (Anchors at Standard Positions) off draws the circle with `anchors: "points"`, so its anchors are + at the points it was drawn through. +- `dragThird` (Third Point by Dragging) off changes how the points are placed. A click on a second point places it, and + a click on a third point draws the circle through the three. A click on the second point again, as the second click + of a double-click there is, draws the circle on the two points. An Alt-click places the second point where Alt's + rounding of the diameter puts it, and both circles pass through it there. A click on the first point, or a second + point dragged back and let go on it, places nothing, and a click on the line through the first two points draws + nothing and keeps them. A drag from the first point still draws the circle on the diameter it drags out, and a drag + from a second point places it where it is let go. Switching `dragThird` drops the points placed so far. + +`tool.setOption` returns an error and changes none of the options when a value is not one the option takes +(`` `radii` must be true or false ``, `` `color` must be one of red, blue, magenta, green, black, gray ``) or the key is +not one of these (`` unknown Circle tool option `size` ``). + With the Ellipse tool, the first two Shift-clicks place points, and the third draws the circle through the three with this command. After two points the tool previews the circle through them and the pointer as a dashed outline. Once a point is placed, a Shift-click on the selection's handles, center point or shape widgets places a point too. Escape, a @@ -7100,11 +7307,37 @@ path's last point, drawn with the tool's `action` option: Alt (Option on macOS) pressed and let go with no other key, click or wheel turn in between switches to the next action: Line, Continuous Arc, Sharp Corner Arc, and back to Line. C flips the last piece, while it is a sharp-corner arc, to the other side of its chord. `[` and `]` make the arc size 15° smaller or larger, for the last sharp-corner arc and the -arcs after it. A click on the first point closes the path, and a click on an end of an open path goes on drawing from -that end. Escape or Enter ends the path, and so does an edit made to it by another command. The path's points show as circles without handles, and a preview shows the -piece the next click adds. Points snap to Smart Guides. Each piece, flip and size change is one undo step. The arc -size of 180°, its 15° steps, the side an arc bulges to and Enter ending the path are VectorCraft's own rules. The -tool keeps `action` and `turn` with the preferences (`tool.setOption {tool: "quickPen", key, value}`). +arcs after it. During a drag, C and `[` `]` change the sharp-corner arc being dragged, and Alt switches its action. A +dragged piece ends where the press is let go. A click on the first point closes the path, and a click on an end of an +open path goes on drawing from that end. Escape or Enter ends the path, and so does an edit made to it by another +command. An edit made by another command during a drag, to the path or to other art, also ends the path: the edit +stays, and the piece stays as last shown. With the `realTimeDrawing` preference off, a press during which another +command edits the document adds no piece, and the edit stays. The path's points show as circles without handles, and a +preview shows the piece the next click adds. Points snap to Smart Guides. Each piece is one undo step, together with the +flips and size changes made during its drag, and each flip or size change made between presses is one undo step. The +arc size of 180°, its 15° steps, the side an arc bulges to, what C and `[` `]` do during a drag and Enter ending the +path are VectorCraft's own rules. The tool keeps `action` and `turn` with the preferences +(`tool.setOption {tool: "quickPen", key, value}`). + +Selecting the tool shows its toolbar on the canvas: Straight Line, Continuous Arc and Sharp Corner Arc set `action`, +Flip Arc flips the last sharp-corner arc as C does (`tool.quickPen.flipArc {}`, which first finishes any pending tool edit, +which can change the document, then returns false and changes nothing more when the Quick Pen tool is not active +or the last piece is not a sharp-corner arc), and More Options (…) has Hide +Toolbar (`window.quickPenToolbar`, which toggles; the toolbar stays hidden until the tool is selected again) and Reset +Toolbar Position (`window.quickPenToolbar.reset`), as the help page describes. +The handle at its left end drags it. While a path is being drawn, the toolbar sits beside the path's last point, 24 +screen points off it diagonally whatever the zoom, on the side the path heads toward (to the right and below for a path +drawn right and down), away from what was drawn, as the +[design write-up](https://adobe.design/ideas/behind-the-design-adobe-illustrator-s-quick-pen-tool) describes. The +following are VectorCraft's own rules. Where the side the path heads toward runs off the canvas, the toolbar goes on the +other side; with no path being drawn, it sits at the bottom center of the canvas. A drag's offset moves it from its +place beside the drawing, or from its resting place, in the document it was made in, and not where it would cover the +path's last point. More Options also has Pin Toolbar Position (`window.quickPenToolbar.pin {pinned?}`, omitted +toggles), which holds the toolbar at its place in the canvas window while the view scrolls or zooms, and Window › Quick +Pen Toolbar shows or hides it. It hides while a press drags on the canvas, and in a canvas pane narrower than the +toolbar its controls wrap onto more rows. `ui.inspect` gives `quickPenToolbar` (`pinned`, and `rect` while it shows); its position, +the pin and whether it shows are not saved. These commands run in the desktop app; the headless host does not run them, +so they need `--connect`. `path.quickPen {start?: [x, y], id?, subpath?, keep?, pieces?, closed?}` draws such a path and selects it, as one undo step, and answers `{id}`. With `start`, it makes a new path with the current paint (a black stroke when the paint @@ -7311,6 +7544,47 @@ warped (`from`, or the selection's bounds) change nothing and add no undo step. {"name":"run_command","arguments":{"command":"object.distort","params":{"from":[-100,0,0,100],"angle":90,"corners":[[0,100],[0,0],[120,-20],[100,100]]}}} ``` +## Perspective Distort and Free Distort on images + +`object.distort` moves an image's four corners exactly where the warp takes them, alone or with other objects, and +draws its pixels in perspective between them. The image is bounded, selected and clicked by the shape its corners +make, and moving, scaling, rotating or shearing it later, or a Transform effect on it, takes the corners along. +Outline view draws its frame through the corners. Blends, the Eyedropper, the Color Theme Picker of Recolor Artwork +and the weed box of Weed Box and Lines (`addon.cutting.weed`) read the image where its corners put it. When the +corners make a parallelogram, the image is placed by its transform as before. Otherwise the native file saves them in +the image's `image_quad` field (top left, top right, bottom right and bottom left of its pixels, in page +coordinates); files without the field open as before. The canvas, printing and every export except DXF, WMF and HP-GL +(an HP-GL plot leaves images out) draw a distorted image as a mesh of affine image pieces, clipped by the corners; no warped copy of the pixels is stored. In +printing and exports the mesh takes as many cells as it needs for the pieces to stay within 0.05 pt of the exact +perspective at the points it checks, with cells at least 2 pt long on the corners' longest side, and each piece reaches +0.5 pt into its neighbors. The canvas cuts the mesh for the zoom, by the view's largest stretch: within a quarter of a +screen pixel at the points it checks, with cells at least 4 pixels long, and each piece reaches 2 pixels into its +neighbors. Either way the mesh takes no more than 64 by 64 cells, and no more cells across than the image has pixels on +its longer side (or 8, if that is more). A stronger perspective, or a smaller image, is drawn with the cells it is +allowed. In EMF each piece stores only the pixels inside its clip, with a pixel more on each side. DXF and WMF cannot +clip, so they write the image as the parallelogram nearest its corners and warn. Corners that would fold the image over +itself, put three corners on one line, join two corners, cross the warp's horizon or lie too close together for a +perspective map are an error, and nothing changes. A transform that squeezes the corners past what a perspective map +can place leaves the image at the parallelogram nearest them. A file whose `image_quad` holds other than four points, +or breaks these rules, opens with the image placed by its transform. A drag is one undo step, and a distort that leaves +the corners where they are records none. Image info (`image.info`) gives a distorted image's resolution at its middle, and Link +Info (`links.info`) gives its scale and rotation there. + +Crop Image (`object.cropImage`), Image Trace (`imageTrace.make`, `imageTrace.makeAndExpand`), Relink (`links.relink`), +Embed (`links.embed`), Unembed (`links.unembed`), Create Object Mosaic (`object.createObjectMosaic`) and Place with +Replace (`file.place` with `replace`) of anything but a text file refuse a distorted image with an error that names the +distortion; Place with Replace does not refuse a clipping group that holds a distorted image of a DCS file's plates. Relink and Unembed refuse a named or selected distorted image before they search a folder or write a file. +Create Gradient Mesh (`object.mesh.create`) converts the other objects it is given and lists each distorted image it +leaves as it is in `skipped`, with its `id` and the error as `reason`; with nothing else to convert, it returns that +error. Update Links (`links.update`) puts a changed file's pixels between a distorted +image's corners, without applying its Placement Options. Mask (`object.maskImage`) draws its clipping path through the +image's corners. Rasterize (`object.rasterize`) draws the image between its corners and makes a plain image of the +result. These rules are VectorCraft's own. + +```json +{"name":"run_command","arguments":{"command":"object.distort","params":{"corners":[[40,0],[60,0],[100,100],[0,100]]}}} +``` + ## Transform Each: Relative and Absolute `object.transformEach` scales by percentages of each object's size (the dialog's Relative, the default), or with @@ -7397,7 +7671,7 @@ and files saved without it open with it off. ## Live Corners -`object.setLiveShape {id?, ids?, radius?, kind?, corners?, items?}` sets the corners of any path (one undo step): a live +`object.setLiveShape {id?, ids?, radius?, kind?, corners?, rectanglesOnly?, items?}` sets the corners of any path (one undo step): a live rectangle's or polygon's, a star's, a pen path's. A corner is an anchor where two sides, straight or curved, meet at an angle (not an open path's ends, not a smooth anchor, not one the sides run straight on through); a curved side is trimmed to what the cut leaves of it. `radius` (pt) and `kind` @@ -7416,7 +7690,9 @@ or keeps its size with Scale Corners off), and a rectangle from a file that kept (elliptical corners) gets circular ones in document units when its corners are next set. Dragging a corner widget rounds the corners whose widgets show (every corner, or the Direct-Selected ones) on every selected path at once, outlining in red those that reach their limit; the Selection tool shows the widgets of live rectangles and polygons, -the Direct Selection tool those of any path. Several objects each with their own corners are one call: +the Direct Selection tool those of any path. `rectanglesOnly: true` sets them on the live rectangles among the targets +alone and leaves the other objects as they are (the Rectangle Properties corner fields and menus send it with the +selection, so an action that records them acts on the rectangles selected when it plays). Several objects each with their own corners are one call: `items: [{id, corners?}]` in place of `ids` and `corners`. Alt-clicking one cycles their kind and double-clicking one opens Corners (`ui.corners {id?, corners?}`, dialog `corners`: `kind`, `radius`; OK runs `object.setLiveShape`). `view.shapeWidgets {on?}` (desktop app, the Hide Shape Widgets and Show Shape Widgets button in the Control bar of the @@ -7620,7 +7896,7 @@ commands are listed this way: (Object › Perspective), under Perspective; - `text.spelling.dictionary` (Edit › Edit Custom Dictionary…), under Text; - the UI commands `ui.recolorDialog` (Edit › Edit Colors › Recolor Artwork…), `ui.flattenerPresetsDialog`, - `ui.printPresetsDialog`, `ui.pdfPresetsDialog`, `ui.perspectivePresetsDialog`, `ui.svgFilterDialog`, + `ui.printPresetsDialog`, `ui.pdfPresetsDialog`, `ui.tracingPresetsDialog`, `ui.perspectivePresetsDialog`, `ui.svgFilterDialog`, `ui.saveSwatchLibrary`, `ui.saveBrushLibrary`, `ui.saveGraphicStyleLibrary` and `ui.saveSymbolLibrary`, under Ui; `file.exportAs` and `file.exportSelection`, under File; `links.editOriginal`, under Links; `type.applyBullets` and `type.applyNumbers`, under Type; and `window.toolbar.new`, `window.toolbarColumns`, `window.toolsBesideCanvas`, @@ -8015,6 +8291,8 @@ Printing / Exporting, `accurate` by default) does the same for RGB raster export Print as Bitmap: `rich` draws pure CMYK black as RGB black in the pixels; CMYK ink exports and the document's colours stay as they are. `antiAliasedBitmaps` (off by default; desktop app): in View › Pixel Preview, on softens placed and embedded bitmaps; off, their pixels stay hard-edged. +`pdfTextAs` (Preferences › File Handling › PDF Text, `text` by default; `text` or `outlines`): what the text of a PDF +opened or placed embedded from the app becomes when the open or place gives no `textAs` (see `document.open`). `disableAutoAddDelete` (off by default): on, the Pen no longer adds or deletes an anchor when a click lands on a segment or an anchor of a selected path. @@ -8605,6 +8883,27 @@ is kept with the preferences and with the workspace; a workspace or preferences and a group id the bar does not have is dropped when they are read. Another `group`, or none, fails with "`group` must be one of …", and a `visible` that is not true or false fails with "`visible` must be true or false"; either leaves every group as it is. The groups and their contents are VectorCraft's own. +`window.taskBar.actions {action, visible?}` (desktop app) turns one of the Contextual Task Bar's actions or chips on +(`visible: true`), off (`false`) or toggles it (omitted or null), and returns `{action, visible}`. The actions are `imageTrace`, +`cropImage`, `removeBackground`, `removeAnchorPoints`, `join` (Connect and Join), `cutPath`, `convertToCorner`, +`convertToSmooth`, `group`, `makeClippingMask`, `unite`, `expand`, `editClippingPath`, `releaseClippingMask`, +`ungroup`, `isolate`, `editPath`, `releaseCompoundPath`, `createOutlines`, `convertToPointType`, `convertToAreaType`, +`typeOnPathOptions`, `centerOnTop`, `centerOnBottom`, `dynamicText`, `offsetPath`, `simplify`, `smooth`, `duplicate`, +`drawPencil`, `placeImage`, `fidelity` and `smoothToolOptions` (the Smooth tool's), and `resizeArtboard`, +`duplicateArtboards`, `rearrangeArtboards` and `exportArtboards` (the Artboard tool's); the chips are `fill`, `stroke`, +`recolor` (Recolor Artwork), `lock` and `shapeProperties` (a basic shape's Shape Properties, in Lock's place). The bar's +More Options menu has Bar Actions, which lists the actions and chips the bar offers for the current selection or tool, +each checked while it is on and named without a final colon or ellipsis, and runs the command for the one clicked. An +action or chip that is off stays out of the bar and out of More Options wherever the bar would offer it; turning one off +changes only the bar. With every action and chip it would offer off, the bar still shows its handle and More Options, +where Bar Actions turns them on again. Every action starts +on. The type font controls are not in Bar Actions and stay on the bar. Which actions are off is kept with the preferences +and with the workspace; a workspace or preferences saved without them show every action, and an id the bar does not have +is dropped when they are read. A `visible` of null toggles, as an omitted one does. Another `action`, or none, fails +with "`action` must be one of …", and a `visible` that is not true, false or null fails with "`visible` must be true +or false"; either leaves every action as it is. +`window.taskBar.resetActions {}` (More Options › Reset Bar Actions) turns every action and chip on again and returns +the ids it turned on. Choosing the bar's actions is VectorCraft's own. ```json {"name":"run_command","arguments":{"command":"file.new","params":{"preset":"A4","orientation":"landscape","artboards":4,"artboardLayout":{"columns":2},"bleed":9}}} @@ -10184,7 +10483,8 @@ its color, remove it or add one), Draw the Nearest Path Next (`sortPaths`) and D artboards, the bounds of the art, or the selection with Export Selection or Export Selected Art Only), or one black pen when that art draws nothing. When the export refuses the options or the artboard choice, One Pen per Color stays chosen and the dialog shows why. OK checks the options and the artboard choice, and remembers the options for the -next export; a canceled save panel writes nothing and keeps the options remembered before. +next export; a canceled save panel writes nothing and keeps the options remembered before. When another document has +become the active one since the dialog opened, OK closes it and writes nothing. ## TIFF, BMP and Targa export @@ -10891,10 +11191,12 @@ undo step. Object › Transform › Scale, the Scale tool and the Transform pane `text.reshapePath {id, anchors: [[subpath, anchor]…], dx, dy}` does the same for the path of type on a path (Direct Selection dragging one of its anchors): the start and end brackets keep their fractions of the path and the text reflows along it. -`text.setPathHandle {id, subpath?, anchor, which: "in"|"out", x, y, independent?}` moves a direction handle of one -of its anchors, as `path.setHandle` moves a path's (Direct Selection dragging a handle of the path, #3565), in one -undo step. A call of `text.reshapeArea`, `text.reshapePath` or `text.setPathHandle` that changes nothing (`dx` and -`dy` both 0, or a handle moved to where it already is) adds no undo step and keeps redo. +`text.setPathHandle {id, subpath?, anchor, which: "in"|"out", x, y, independent?, symmetric?}` moves a direction handle +of one of its anchors, as `path.setHandle` moves a path's (Direct Selection dragging a handle of the path, #3565), in +one undo step. With `symmetric: true` the other handle goes opposite the moved one at the same length, measured on +the page, as in `path.setHandle`; `symmetric` and `independent` cannot both be true. A call of `text.reshapeArea`, +`text.reshapePath` or `text.setPathHandle` that changes nothing (`dx` and `dy` both 0, or handles left where they +already are) adds no undo step and keeps redo. ```json {"name":"run_command","arguments":{"command":"text.reshapeArea","params":{"id":42,"anchors":[[0,2]],"dx":40,"dy":60}}} @@ -12273,6 +12575,47 @@ on an open path that are not drawn because they fall before the path's start can {"name":"run_command","arguments":{"command":"text.touchType","params":{"id":7,"start":1,"dx":10,"dy":4}}} ``` +## Retype tracking + +`type.retype {fonts?}` turns selected outlined text back into point text when its shapes are glyphs of a font the app +has. A line of three or more glyphs gets the spacing that most of its gaps share as its tracking, in 1/1000 em. Retype +tries the value rounded to a whole number first when it is within 0.05 of one, then the value as measured. The font's +advances and pair kerning are left out of the measure, and word spaces are counted after the tracking. The tracking is +kept when the tracked type draws the whole line in place, or more of it from its start than untracked type does. When +untracked type also draws the whole line, for example when gaps are as wide as whole spaces, the line stays untracked +if the tracking is under one unit or the tracked type would drop a gap one space wide, so `a b c` stays `a b c`. +Otherwise the tracked type is kept, and only gaps wider than the tracking alone keep spaces (narrower gaps, when +tracking tighter than a space gives each space a negative advance). Glyphs tracked tighter than a quarter em stay on +one line as long as each one starts after the one before it. Negative tracking is set only on a line that is opaque, +uses the Normal blend mode, has a solid fill or none and has no stroke; other tightly spaced lines split into one object +per glyph. A line splits where its type stops drawing the outlines in place, and the glyphs after the split take the +tracking their own gaps give. These rules are VectorCraft's own. Each entry of the result's `fonts` list has +`tracking`. + +```json +{"name":"run_command","arguments":{"command":"type.retype","params":{}}} +``` + +## Retype several lines + +`type.retype` joins lines that follow each other in paint order, with the same group, paint, font, size, turn and +tracking (an untracked line of one or two glyphs takes the tracking of the others), into one type object when each +line's baseline is the same distance below the one before (between 0.25 and 3 times the size) and the lines line up at their starts, ends or centers. The object is area type with Convert To Area +Type's frame, its lines separated by line breaks, with left, right or center alignment, checked in that order. Its +leading is Auto when Auto puts the last baseline in place, else the mean distance between the baselines, to a +thousandth of a point when that still puts the last baseline in place. Lines with an opacity below 100%, a blend mode +other than Normal, a gradient or pattern fill, or a stroke stay one object per line. These rules are VectorCraft's own. + +Every joined object is laid out and compared with the outlines. When area type would not draw each glyph where its +outline was, including after Text Wrap objects above it reflow it, or when its frame would reach past the canvas's +coordinate limit, the lines become one multi-line point type object (one object per line when its bounds would reach +past that limit). When that also moves a glyph, the lines before that glyph's line stay one object, and the lines +from that line on are joined again from it. When the Text Wrap objects on the layers Retype changes would copy more +than 2,000,000 units into the wrap shapes of their area type (one for each anchor, subpath and shape, for each area +type object below them), Retype does not check the wrap and the lines become multi-line point type. Each entry of +the result's `texts` list holds an object's lines joined by `\n`, and each entry of its `fonts` list also has +`leading` (points; null for Auto leading or a single line) and `area`. + ## Retype panel `type.retypeFonts {count?}` lists the fonts whose glyphs match the selected outlined text. It compares each selected path @@ -13555,7 +13898,8 @@ the compound path selected), and the next click starts a new path. Choosing any A blend's spine is the straight lines between its key centres until it is edited. `object.blend.info` lists it (`spine.anchors`, `keyAnchors`: the point each key sits on). `object.blend.spine.addAnchor {x, y}` adds a point where the spine passes nearest, `object.blend.spine.moveAnchor {anchor, x, y}` moves a point (a key on it moves along; with -`handle: "in" | "out"` it places that handle), `object.blend.spine.convertAnchor {anchor, to: "smooth" | "corner", x?, y?}` converts a point's handles (a Smooth drag with `x, y` creates opposite handles; Corner retracts both), `object.blend.spine.reshapeSegment {segment, t, dx, dy, perpendicular?}` bends a segment +`handle: "in" | "out"` it places that handle, and with `symmetric: true` also the other handle opposite it at the +same length, as `path.setHandle` does; `symmetric` needs `handle` and cannot go with `independent`), `object.blend.spine.convertAnchor {anchor, to: "smooth" | "corner", x?, y?}` converts a point's handles (a Smooth drag with `x, y` creates opposite handles; Corner retracts both), `object.blend.spine.reshapeSegment {segment, t, dx, dy, perpendicular?}` bends a segment so its point at `t` moves by (dx, dy), turning a straight spine into a curve (`perpendicular` works as in `path.reshapeSegment`), and `object.blend.spine.removeAnchor {anchor}` deletes a point no key sits on; the first edit turns the spine into a path. Moving a key moves its end of the spine. Release (`object.blend.release`) leaves the spine of a blend that has one as a path that paints nothing (`spines` in the result): diff --git a/docs/plugins.md b/docs/plugins.md index 344e3b7c00..09bb7c8dbd 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -678,7 +678,10 @@ every attribute: of JSON: type whose runs and paragraphs don't fit what the type before it in paint order left comes with `truncated: true` too. - An image (`"image"`): `pixelSize` is its width and height in pixels; `colorMode` is `"rgb"`, `"cmyk"`, `"gray"` or - `"unknown"`, read from the image itself. An embedded image whose pixels take at most 1 MiB in base64 (443 × 443 + `"unknown"`, read from the image itself. An image whose corners Perspective Distort or Free Distort moved to a shape + that is not a parallelogram also has `corners`, its pixel rectangle's corners on the page (top left, top right, + bottom right, bottom left), and its `transform` is then the affine placement nearest them, the one that matches the + perspective at the middle of its pixels. An embedded image whose pixels take at most 1 MiB in base64 (443 × 443 pixels fit) has them in `pixelsBase64`: straight RGBA, 8 bits a channel, row by row from the top, and `pixelsOmitted: false`. A CMYK image's pixels are its inks through the working CMYK profile, as sRGB. The pixels of all the images in one input take at most 16 MiB in base64, and an image the host starts to decode takes its size diff --git a/docs/roadmap.md b/docs/roadmap.md index 759baae5bd..836af37d97 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -1,6 +1,6 @@ # Roadmap: milestones and what's next -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-18 · **Change:** minor (Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); M11: a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: Layers: selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: M4: PDF import: type filled and stroked after a page of type filled only comes in filled and stroked, #8549 follow-up; scores and estimates unchanged; previously: selected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: M4: `.ai` and EPS import: an Art brush in Tints of a swatch-linked stroke color comes in brushed, #8200; scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: M4: `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths, #8128; scores and estimates unchanged; previously: import: type filled and stroked by a `TJ` whose kerning starts a new line comes in filled and stroked, #8543; PDF Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: M1: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; M1: an Alt-drag in the Layers panel copies a row above or below its own place, #8237; scores and estimates unchanged; previously: PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; M1: Layers panel Alt-drag shows the copy cursor, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: M7: Check Spelling modal dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; M10/G5: Neon & Glow built-in graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); previously: Tech Circuit brush library, G5; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: M10/G5: Energy Beams brush library; MCP docs list Energy Beams; previously minor: M10/G5: Skill Icons symbol library; MCP docs list Skill Icons; previously minor: M10/G5: Status Effects graphic style library; MCP docs catch-up for symbol libraries; previously minor: M10/G5: Inventory Icons built-in symbol library; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: M10/G5: Game HUD graphic style library; previously minor: resizable icon-strip flyouts and bottom-aligned panel footers, #5713; previously minor: M10/G5: Map Markers built-in symbol library; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview are in; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; M4/M7: `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; M4/M7: `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; Hindi catalog and contributor loanword preferences; full wording review in progress; Effect dialogs: a colour swatch beside a hex colour opens the Color Picker, #5365; shape tools move the selection from its centre point and turn it from the zone outside a box corner, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-20 · **Change:** minor (M11: Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid, #8363; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: M5: In the web build, an edit while the view of a heavy document moves (a tool drag held at an edge of the canvas, #8551, or a wheel scroll during a drag) draws only the part it changed into the last frame, which stays drawn moved with the view, instead of rendering the whole canvas each frame (an edit that changes more than half of the frame, or a change of more than the view and the document, still renders it whole at once), and edits that go on once the view is still don't put off its render (#8688); scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); M11: a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: Layers: selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: M4: PDF import: type filled and stroked after a page of type filled only comes in filled and stroked, #8549 follow-up; scores and estimates unchanged; previously: selected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: M4: `.ai` and EPS import: an Art brush in Tints of a swatch-linked stroke color comes in brushed, #8200; scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: M4: `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths, #8128; scores and estimates unchanged; previously: import: type filled and stroked by a `TJ` whose kerning starts a new line comes in filled and stroked, #8543; PDF Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: M1: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; M1: an Alt-drag in the Layers panel copies a row above or below its own place, #8237; scores and estimates unchanged; previously: PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; M1: Layers panel Alt-drag shows the copy cursor, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: M7: Check Spelling modal dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; M10/G5: Neon & Glow built-in graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); previously: Tech Circuit brush library, G5; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: M10/G5: Energy Beams brush library; MCP docs list Energy Beams; previously minor: M10/G5: Skill Icons symbol library; MCP docs list Skill Icons; previously minor: M10/G5: Status Effects graphic style library; MCP docs catch-up for symbol libraries; previously minor: M10/G5: Inventory Icons built-in symbol library; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: M10/G5: Game HUD graphic style library; previously minor: resizable icon-strip flyouts and bottom-aligned panel footers, #5713; previously minor: M10/G5: Map Markers built-in symbol library; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: G2: Effect Gallery thumbnails and in-dialog preview are in; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; M4/M7: `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; M4/M7: `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Indian-language hyphenation review and license allowlist, #4947; Hindi catalog and contributor loanword preferences; full wording review in progress; Effect dialogs: a colour swatch beside a hex colour opens the Color Picker, #5365; shape tools move the selection from its centre point and turn it from the zone outside a box corner, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x) > > Oversized artboard import update (2026-11-12): Explicit editing-data import retains a single artboard beyond a capped 14,400 pt PDF page (#6865). > @@ -26,6 +26,8 @@ ## Feature submission evidence +**Scissors cut-point preview (#8655):** A native point marker shows the anchor or position on a curve that the current Scissors click targets, including the existing snapping rules. Hovering changes no artwork; an ineligible or stale hover has no marker. Existing cut and Alt Add Anchor behavior are retained. Focused tool and Session regressions live in `crates/tools/src/draw2/anchor/tests.rs` and `crates/engine/tests/scissors_snap.rs`. Scores and estimates are unchanged. + Draft enhancement #5804: Preferences › File Handling can select a raster editor through the native picker, with a private draft outside engine preferences and generic dialog fields. OK saves it, Cancel discards it, and Reset restores PhotoCraft. With Use System Defaults off, a missing chosen editor falls back to PhotoCraft, then the system default; validation and launch failures are reported. Control/MCP and synthetic input cannot choose an application or run external Edit Original. Web behavior, parity scores and estimates are unchanged; macOS/Linux smoke tests remain pending. **2026-11-19 revision:** merged main while preserving the private raster-editor choice; no parity rescore. @@ -71,6 +73,7 @@ M7 type: Touch Type moves a right-to-left character along its line and up from i | Date | Change | Summary | |---|---|---| +| 2026-11-19 | minor | M14/G12: Graphic Styles panel item context menus in thumbnail and list views (Options…, Duplicate, Delete, Redefine, Break Link); regression tests in crates/ui-egui/src/panels/graphic_styles.rs; scores and estimates unchanged. | | 2026-11-18 | minor | M10/G5: Media Controls joins Basic Shapes, UI Frames, Map Markers, Inventory Icons, Skill Icons and Weather Icons as a seventh built-in symbol library (Play, Pause, Stop, Skip Next, Shuffle, Repeat; original procedural vector symbols generated in code, no default 9-slice); G5 estimate decremented to 2–12 h, milestone estimates unchanged | | 2026-11-18 | minor | M14: PDF export writes the document language (Document Setup) as the catalog's `/Lang` (#3644). Scores and estimates unchanged. | | 2026-11-13 | minor | Layers: selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged. | @@ -176,21 +179,21 @@ Gujarati interface follow-up (2026-11-14): the catalog and zero/one plural rule |---|---|---|---| | M0 | Skeleton + vertical slice | ✅ done | — | | M1 | Selection, transform, layers, MCP (common command tools, strict keys, session resources and version-aware result hints) | ✅ mostly done (path and compound-path interior selection follows enabled fill rows (#6625); a marquee leaves locked or hidden guide paths out inside groups, as clicks do (#8538); hidden-fill and no-fill stroke cap/join CPU regressions passed; document-tab artwork drag with lossless resource transfer and one target Undo; malformed MCP app replies discard the connection without replay, #1761; bounded control socket waits and connection-slot recovery, #1726; bounded synthetic control input, #1709; no-op anchor Align keeps Undo, Redo and saved state (#1180 follow-up); transform reference point snaps to anchors/centres; rotated objects keep a rotated bounding box and their angle; Free Transform, Scale and Reflect along a rotated box pending; the Transform fields take one Tab each, the W/H link after them) | 4–6 | -| M2 | Drawing tools + smart guides | ✅ mostly done (Eraser preserves fill outside fixed and varied tip sweeps and Alt-drag marquees on fill-only open paths and keeps their compound holes; clipping masks retain surviving contours or empty geometry in the same node; ordinary Group/Layer paints and evaluated gradient placements are preserved when the stored paint reproduces their appearance; hidden Rasterize and Along/Across stroke rows do not block visible gradients; replacement-art effects, plug-ins/Rasterize, along/across-stroke gradients and placements that cannot be reproduced keep their existing fitting; stroked open paths retain main behavior (#6582); #3380 deletion creates independent selected path pieces and keeps bounds-fitted gradients in place; endpoint highlighting remains open; Polygon/Star exact-size count persistence, with repeated-drag, tool-switch and Cancel regression coverage; Curvature point markers without direction handles (#1236, in part); Direct Selection segment click/Delete preserves neighboring edges, #1278; Flare, Reshape, Live Corners widget dragging and per-corner radii and kinds landed, on any path's corners; Shaper rough-shape recognition and orientation steps, the remaining Pen modifier nuances; Shaper Groups with editable sources and separate fill/stroke edits landed; custom ruler origin with drag preview, active-artboard reset, relative X/Y fields and native round-trip (#1212); construction widget/refinements pending); a shape just drawn moves by its centre point and turns from the zone outside a corner with its tool still active (#5477); Tangent and straight-segment perpendicular snapping use saved Smart Guides Geometric Guides preferences and Control bar quick access (#2537), including the existing Snap to Glyph and Alignment Guides toggles (#6164); no View submenu; Copy and Cut with the Pen or Curvature tool take the anchors a Cmd/Ctrl-lent Direct Selection picked (#6123); Scissors hover and cuts use the Pen's path/align/intersect/anchor snaps, with Alt Add Anchor and cut endpoint selection retained (#6470) | 12–18 | +| M2 | Drawing tools + smart guides | ✅ mostly done (Eraser preserves fill outside fixed and varied tip sweeps and Alt-drag marquees on fill-only open paths and keeps their compound holes; clipping masks retain surviving contours or empty geometry in the same node; ordinary Group/Layer paints and evaluated gradient placements are preserved when the stored paint reproduces their appearance; hidden Rasterize and Along/Across stroke rows do not block visible gradients; replacement-art effects, plug-ins/Rasterize, along/across-stroke gradients and placements that cannot be reproduced keep their existing fitting; stroked open paths retain main behavior (#6582); #3380 deletion creates independent selected path pieces and keeps bounds-fitted gradients in place; endpoint highlighting remains open; Polygon/Star exact-size count persistence, with repeated-drag, tool-switch and Cancel regression coverage; Curvature point markers without direction handles (#1236, in part); Direct Selection segment click/Delete preserves neighboring edges, #1278; Flare, Reshape, Live Corners widget dragging and per-corner radii and kinds landed, on any path's corners; Shaper rough-shape recognition and orientation steps, the remaining Pen modifier nuances; Shaper Groups with editable sources and separate fill/stroke edits landed; custom ruler origin with drag preview, active-artboard reset, relative X/Y fields and native round-trip (#1212); construction widget/refinements pending); a shape just drawn moves by its centre point and turns from the zone outside a corner with its tool still active (#5477); Tangent and straight-segment perpendicular snapping use saved Smart Guides Geometric Guides preferences and Control bar quick access (#2537), including the existing Snap to Glyph and Alignment Guides toggles (#6164); no View submenu; Copy and Cut with the Pen or Curvature tool take the anchors a Cmd/Ctrl-lent Direct Selection picked (#6123); Scissors hover and cuts use the Pen's path/align/intersect/anchor snaps, with Alt Add Anchor and cut endpoint selection retained (#6470); Scissors previews the current anchor or curve cut point (#8655) | 12–18 | | M3 | Paint & appearance (swatches, color, gradient, stroke, appearance, transparency, styles) | ✅ done (M3.7–M3.98): swatches, groups, libraries, tints, Lab spots and Registration; Eyedropper copies transformed character dimensions (#6404) and styles highlighted text only (atomic transparency rejection); Eyedropper reads visible locked and outside-isolation sources (#1251); Color Picker, Color panel (its spectrum grows with a resized panel, #8005), Color Guide, Color Themes, Edit Colors and Recolor Artwork (screen-bounded Edit chip list, #3416; native Lab entry and swatch libraries in the picker, Assign-row menus, #8031/#4028); gradients that follow every transform, the annotator, linked stops, freeform gradients, focal points, gradients on strokes and Expand; visible strokes when paint is added to inherited None/zero-width art (#1253); stroke geometry, arrowheads, dashes fitted to corners, stroke on type, width profiles and the Width tool (Shift-double-click enables adjoining adjustment in Width Point Edit; finite-arithmetic follow-up regressions and full CI passed ([Validation evidence](target-app-parity.md#evidence-what-ships-today-by-area))), Scale Strokes and preview bounds; Appearance targeting, container appearance, target circles, Expand Appearance; knockout, isolation, blend accuracy, CMYK blending, overprint, Attributes, masks and clipping, Flatten Transparency; graphic styles, links and libraries; CSS library export preserves fractional linear and radial gradient stop positions. Left: freeform gradients in SVG/PDF, mixed spot/process gradients in SVG and PDF gradients mixing a spot color with RGB or Lab stops export as stops or process colors; PDF export writes dithered gradient fills with spot stops, and Perceptual spot gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve, as images in process colors; confirm the Scale Strokes & Effects default; Recolor model selection is available through the engine and MCP only (#2520); the dialog retains its existing controls; Library panels' lists (swatch, Color Book, brush, symbol and graphic style libraries) fill a taller panel above its footer (#2992; scores and estimates unchanged); Graphic Styles list fills a taller panel above its footer (#2992; scores and estimates unchanged); Swatches list fills a taller panel above its footer (#1638; `the_list_fills_a_tall_panel_above_its_footer`; scores and estimates unchanged); | 4–8 | | M4 | Files (native, SVG, PDF, raster, Export for Screens, clipboard interop) | `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths (#8128; estimates unchanged); Production Preflight checks fonts, overflow, links and image resolution with clickable findings and automatic rechecking (VectorCraft addition; estimates unchanged); PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked (#8300; estimates unchanged); PDF import: type filled and stroked by one text-showing operator comes in as one filled and stroked type object (#8015; not for type filled and stroked at less than full opacity, which still comes in as a filled object and a stroked one, as the file composites them; estimates unchanged); PDF import: type filled and stroked by a `TJ` whose kerning starts a new line part way through comes in filled and stroked, a type object for each part, also where it draws a glyph again where it drew one, in an `ActualText` span too, where it stays one replacement type object on the first glyph's line and in its style; a `TJ` over more than 65 lines (the 64 its fill pass finished, kept back, and the open one) stays a filled object and a stroked one for each part (#8543; estimates unchanged); PDF import: type filled and stroked after a page of type filled only (more than 64 lines) comes in as one filled and stroked type object again, with or without a path between, and a `TJ` over more lines than are kept with a glyph kept as an outline still stays a filled object and a stroked one for each part (#8549 follow-up; estimates unchanged); PDF import: stroked type keeps the file's line cap, line join and miter limit (#7741; estimates unchanged); Rename artboards in Export for Screens (#7275); Explicit editing-data import keeps oversized capped-page artboards (#6865; estimates unchanged); Save refusal continuation (#6146): ordinary Save offers Save As; unchanged format keeps options, changed format opens its Save options; cancellation/automation isolation; focused UI regressions passed, native acceptance pending; PDF authored ActualText preserved once in editable import (#6165; first-glyph line/style, bounded input; estimates unchanged); PDF export keeps harakat and zero-advance Noto Arabic dot glyphs in one compatible batch per layout line, with per-glyph vertical offsets (#6309). `crates/pdf/src/tests/realtext.rs` (`mark_text_*`) checks decoded cluster mappings, mixed Arabic/Latin/digits, contour placement against outline export, vertical columns, differing path rotations and PDF/X-1a/3/4. Editable-text import preserves authored ActualText separately (#6165), with cross-line/style layout limits; separately styled or differently rotated clusters and external viewer search/copy remain outside this export-only evidence. `.ai`/EPS type from the text document keeps its paragraphs' tab stops (#6147); `.ai`/EPS type from the text document keeps auto leading per line, its hyphenation options, and may show more of the last lines the file sets in an area frame of its own, when growing the frame by its lines' deepest descent plus 0.05 pt shows them (#6137); ✅ done (M4.14–M4.98 on 2026-10-05): Save As/Save a Copy/Revert/templates, Data Recovery and background save, SVG import and export fidelity (units, text, symbols, filters, SVGZ, Preserve Editing, SVG Options), shared guarded PDF writer and windowed reader ([pdf-backend.md](pdf-backend.md)), PDF import (colours, layers, masks, editable text, security) and export (presets, marks, bleed, ICC and output intent, raster effects, subset fonts, PDF/X-1a, X-3 and X-4, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3), Place and Links, Package, EPS and DXF in and out (EPS legacy mesh corners, vector opacity masks and raster page comparison verified; closed SPLINE flags round-trip and circular paths export as native CIRCLE/ARC, #1299), EMF/WMF, TIFF/BMP/Targa/PSD/GIF/PNG-8 export, Print and print presets, slices, Save for Web, TIFF in Export for Screens and Asset Export, clipboard flavours, File Info; AF.1–AF.4 add Affinity import (native layers, artboards, vectors, text and images from Affinity 1–3 files; the embedded preview only as a warned fallback; AF.4 expands current `.af` fixtures and every-board round-trip validation); EPS Save and Save As keep an opened EPS as EPS with its page frame and complete editable VectorCraft document (2026-10-26; G9 import fidelity unchanged). Left: DWG (use DXF), PSD placement as layers, overprint read back from PDF, Affinity export, polish; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; PDF import: glyphs inside a marked-content span with an empty `ActualText` come in as outlines in their fill and stroke, adding no text (#6971; scores and estimates unchanged); | 3–6 (existing scope; Affinity export unestimated) | -| M5 | Performance | 🟡 background render + caches + MT done; text thread overlays index repeated selection lookups, keeping the first lookup and singleton selections direct (#6543); `vectorcraft-cli bench` and `vectorcraft-cli perf` (budget suite); opaque solid-fill knockout paths draw once in hard-edge/supersampled raster export, with analytical-AA compositing unchanged; file format v2 opens 3× faster (50k paths: 722 → 244 ms); raster effects (glows, shadows, blur, feather) no longer force the whole frame single-threaded (filtered offscreen per effect, verified equal to the single-threaded reference); Craquelure/Mosaic Tiles/Stained Glass distance searches optimized with pixel-invariance checks and the `texture_drag_perf` probe (#1257); effect-heavy demos need a clean-machine benchmark; dirty-region rendering, GPU backend spike pending | 15–25 | +| M5 | Performance | 🟡 background render + caches + MT done; text thread overlays index repeated selection lookups, keeping the first lookup and singleton selections direct (#6543); `vectorcraft-cli bench` and `vectorcraft-cli perf` (budget suite); opaque solid-fill knockout paths draw once in hard-edge/supersampled raster export, with analytical-AA compositing unchanged; file format v2 opens 3× faster (50k paths: 722 → 244 ms); raster effects (glows, shadows, blur, feather) no longer force the whole frame single-threaded (filtered offscreen per effect, verified equal to the single-threaded reference); Craquelure/Mosaic Tiles/Stained Glass distance searches optimized with pixel-invariance checks and the `texture_drag_perf` probe (#1257); effect-heavy demos need a clean-machine benchmark; in the web build an edit while the view of a heavy document moves draws only the part it changed into the last frame (#8688); dirty-region rendering, GPU backend spike pending | 15–25 | | M6 | Path operations (Pathfinder, Shape Builder, offset…) | ✅ mostly done (live compound shapes: Make, Alt-click a Shape Mode, member modes, Release, Expand (#4522); single-result Pathfinder names and SVG IDs retained (#1293); Divide open-cutting-path geometry, appearance and history verified (#1307; existing segment cap remains); Simplify preview/counts and rewritten-path component selection verified (#1272; the slider opens at the Auto-Simplify level; a Direct Selection part of a path simplifies on its own); Compound appearance and member fill-rule edits verified (#1197); Boolean precision on almost-horizontal edges fixed and the property tests made deterministic; Shape Builder gap detection, large-offset bug open); Shape Builder Gap Detection shares Live Paint’s spatial gap finder and temporary merge bridges (#2526); Custom is capped at 72 pt in the existing options dialog | 3–6 | -| M7 | Type (point/area/path, editing, styles, OpenType, threading, glyphs) | Spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, the custom dictionary and Ignore All commands, Auto Spell Check with its right-click suggestions, Ignore All and Add to Dictionary, Spelling › Auto Spell Check in the context menu of type, the Edit Custom Dictionary dialog, and the modal Check Spelling dialog (Edit › Spelling › Check Spelling…, `Cmd+I`, `ui.checkSpelling`, #4936); 🟡 Retype phase 1: `type.retype` turns outlined text that exactly matches an available font back into point text (#4934); Right-aligned area type sets the text after a line's last tab against the right edge, the text before it at its stops (#6147); A line a soft return ends is justified as a wrapped line is (#6137); Indian-language pattern hyphenation preserves syllables in both composers (#4947); 🟡 Hanging punctuation keeps its published amounts under Glyph Scaling, and Standard burasagari counts a hung line start as room; Fullwidth `!` / `?` keep an upright fallback in vertical type; Hyphenation… and Justification… per paragraph (#2310, #2755), Auto Leading also driving the Character panel's Leading, the Alt+↑/↓ leading nudge and Fill with Placeholder Text; Document-point character controls after object/group scaling (#1034; optional font-size preservation remains separate), Character/Paragraph Styles (explicit Auto-leading resets and local leading overrides), per-paragraph paragraph attributes, mixed paragraph alignment indication (headless regressions, full integration CI and visual review pass), Area Type Options (with Width/Height, Auto Size and Shrink Text to Fit; overflow reported to agents and vertical Align), type areas resized by their handles and reshaped with Direct Selection, threaded text, Fit Headline, Glyphs (feature-valued alternates and unencoded glyphs applied in one Undo step while keeping Arabic joining, #5514), OpenType panel (including font-defined Stylistic Sets), Find Font (Document, Recent and System replacement sources, #5217), installed system fonts in every font menu (fonts registered with Windows outside its font folders, the XDG and Flatpak host font folders on Linux, and fonts installed while the app runs, listed when it comes back to the front; searchable; the Character and Properties menus show each family's sample of the selected text, preview it live under the pointer or ↑/↓, show recently applied families first (#3515), filter by script and kind, list a family's styles, and star favourites; the Glyphs panel and Find Font's Replace With use the same menu without the live preview) and found by name on open/import (full-name aliases and Missing Fonts searches verified, #1258; Windows font-service QA pending), variable fonts' named instances as styles, CJK names in the UI, input methods (marked text in place, candidate window at the caret; Japanese IME), Text Wrap (offset, invert, both sides of an object; follows edits), Type on a Path effects and Options with draggable start/centre/end brackets (slide, flip), tab stops + Tabs panel (Above Text floats it over the selected text, its ruler at the canvas zoom so stops line up with the columns, #729), inline symbols in text (beyond parity), Hebrew/Arabic bidirectional text, Paragraph Direction, Every-line/Single-line Composer per object (ragged text too) done; paint-only Arabic harakat keep joining with GDEF-mark ownership and Insert Kashidas tatweels on the base letter's paint (`tests::harakat`); tab leaders, vertical type pending | 45–60 | +| M7 | Type (point/area/path, editing, styles, OpenType, threading, glyphs) | Spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, the custom dictionary and Ignore All commands, Auto Spell Check with its right-click suggestions, Ignore All and Add to Dictionary, Spelling › Auto Spell Check in the context menu of type, the Edit Custom Dictionary dialog, and the modal Check Spelling dialog (Edit › Spelling › Check Spelling…, `Cmd+I`, `ui.checkSpelling`, #4936); 🟡 Retype phase 1: `type.retype` turns outlined text that exactly matches an available font back into point text (#4934), keeping even spacing as tracking and making stacked, aligned lines one area type object; Right-aligned area type sets the text after a line's last tab against the right edge, the text before it at its stops (#6147); A line a soft return ends is justified as a wrapped line is (#6137); Indian-language pattern hyphenation preserves syllables in both composers (#4947); 🟡 Hanging punctuation keeps its published amounts under Glyph Scaling, and Standard burasagari counts a hung line start as room; Fullwidth `!` / `?` keep an upright fallback in vertical type; Hyphenation… and Justification… per paragraph (#2310, #2755), Auto Leading also driving the Character panel's Leading, the Alt+↑/↓ leading nudge and Fill with Placeholder Text; Document-point character controls after object/group scaling (#1034; optional font-size preservation remains separate), Character/Paragraph Styles (explicit Auto-leading resets and local leading overrides), per-paragraph paragraph attributes, mixed paragraph alignment indication (headless regressions, full integration CI and visual review pass), Area Type Options (with Width/Height, Auto Size and Shrink Text to Fit; overflow reported to agents and vertical Align), type areas resized by their handles and reshaped with Direct Selection, threaded text, Fit Headline, Glyphs (feature-valued alternates and unencoded glyphs applied in one Undo step while keeping Arabic joining, #5514), OpenType panel (including font-defined Stylistic Sets), Find Font (Document, Recent and System replacement sources, #5217), installed system fonts in every font menu (fonts registered with Windows outside its font folders, the XDG and Flatpak host font folders on Linux, and fonts installed while the app runs, listed when it comes back to the front; searchable; the Character and Properties menus show each family's sample of the selected text, preview it live under the pointer or ↑/↓, show recently applied families first (#3515), filter by script and kind, list a family's styles, and star favourites; the Glyphs panel and Find Font's Replace With use the same menu without the live preview) and found by name on open/import (full-name aliases and Missing Fonts searches verified, #1258; Windows font-service QA pending), variable fonts' named instances as styles, CJK names in the UI, input methods (marked text in place, candidate window at the caret; Japanese IME), Text Wrap (offset, invert, both sides of an object; follows edits), Type on a Path effects and Options with draggable start/centre/end brackets (slide, flip), tab stops + Tabs panel (Above Text floats it over the selected text, its ruler at the canvas zoom so stops line up with the columns, #729), inline symbols in text (beyond parity), Hebrew/Arabic bidirectional text, Paragraph Direction, Every-line/Single-line Composer per object (ragged text too) done; paint-only Arabic harakat keep joining with GDEF-mark ownership and Insert Kashidas tatweels on the base letter's paint (`tests::harakat`); tab leaders, vertical type pending | 45–60 | | M8 | Transform & distort (Puppet Warp, Liquify tools, Envelopes, Blends, Perspective Grid) | ✅ done (M8.1–M8.20 on 2026-10-06, fidelity pass): Liquify Tool Options with one shared brush, pen pressure, hold-to-apply, a safe scope and incremental strokes; tool options that last; Puppet Warp rotation, multi-select, Control bar and a rest-shape session that follows Undo; Width tool on compound paths; Envelope dialogs with preview, Reset with Warp/Mesh, full Envelope Options, type/images/symbols/appearance/gradients/patterns distorted on canvas and in every export, warps that keep their frame, Edit Contents, mesh handles and Control bar; Blend Options, anchor-targeted Blend tool, editable spine, keys picked on the canvas, faithful interpolation and knockout; Anchor Point spine conversion/handle editing and selection priority (#2544), with #2425 Shift reshape preserved; Perspective Grid with Define Grid, presets, lock/snap/rulers, widgets, the 1–4 plane switch, movable planes, Perspective Selection scale/copy/perpendicular/Transform Again, and type and symbols truly projected with Edit Text. Left: Anti-Alias and Preserve Shape output, warp-envelope point editing, brush interpolation in blends, Free Transform/Scale/Reflect along a rotated box | 2–4 | | M7 | Type (point/area/path, editing, styles, OpenType, threading, glyphs) | Spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, the custom dictionary and Ignore All commands, Auto Spell Check with its right-click suggestions, Ignore All and Add to Dictionary, Spelling › Auto Spell Check in the context menu of type, the Edit Custom Dictionary dialog, and the modal Check Spelling dialog (Edit › Spelling › Check Spelling…, `Cmd+I`, `ui.checkSpelling`, #4936); Right-aligned area type sets the text after a line's last tab against the right edge, the text before it at its stops (#6147); A line a soft return ends is justified as a wrapped line is (#6137); Indian-language pattern hyphenation preserves syllables in both composers (#4947); 🟡 Hanging punctuation keeps its published amounts under Glyph Scaling, and Standard burasagari counts a hung line start as room; Fullwidth `!` / `?` keep an upright fallback in vertical type; Hyphenation… and Justification… per paragraph (#2310, #2755), Auto Leading also driving the Character panel's Leading, the Alt+↑/↓ leading nudge and Fill with Placeholder Text; Document-point character controls after object/group scaling (#1034; optional font-size preservation remains separate), Character/Paragraph Styles (explicit Auto-leading resets and local leading overrides), per-paragraph paragraph attributes, mixed paragraph alignment indication (headless regressions, full integration CI and visual review pass), Area Type Options (with Width/Height, Auto Size and Shrink Text to Fit; overflow reported to agents and vertical Align), type areas resized by their handles and reshaped with Direct Selection, threaded text, Fit Headline, Glyphs (feature-valued alternates and unencoded glyphs applied in one Undo step while keeping Arabic joining, #5514), OpenType panel (including font-defined Stylistic Sets), Find Font (Document, Recent and System replacement sources, #5217), installed system fonts in every font menu (fonts registered with Windows outside its font folders, the XDG and Flatpak host font folders on Linux, and fonts installed while the app runs, listed when it comes back to the front; searchable; the Character and Properties menus show each family's sample of the selected text, preview it live under the pointer or ↑/↓, show recently applied families first (#3515), filter by script and kind, list a family's styles, and star favourites; the Glyphs panel and Find Font's Replace With use the same menu without the live preview) and found by name on open/import (full-name aliases and Missing Fonts searches verified, #1258; Windows font-service QA pending), variable fonts' named instances as styles, CJK names in the UI, input methods (marked text in place, candidate window at the caret; Japanese IME), Text Wrap (offset, invert, both sides of an object; follows edits), Type on a Path effects and Options with draggable start/centre/end brackets (slide, flip), tab stops + Tabs panel (Above Text floats it over the selected text, its ruler at the canvas zoom so stops line up with the columns, #729), inline symbols in text (beyond parity), Hebrew/Arabic bidirectional text, Paragraph Direction, Every-line/Single-line Composer per object (ragged text too) done; paint-only Arabic harakat keep joining with GDEF-mark ownership and Insert Kashidas tatweels on the base letter's paint (`tests::harakat`); tab leaders, vertical type pending | 45–60 | | M8 | Transform & distort (Puppet Warp, Liquify tools, Envelopes, Blends, Perspective Grid) | ✅ done (M8.1–M8.20 on 2026-10-06, fidelity pass): Liquify Tool Options with one shared brush, pen pressure, hold-to-apply, a safe scope and incremental strokes; tool options that last; Puppet Warp rotation, multi-select, Control bar and a rest-shape session that follows Undo; Width tool on compound paths; Envelope dialogs with preview, Reset with Warp/Mesh, full Envelope Options, type/images/symbols/appearance/gradients/patterns distorted on canvas and in every export, warps that keep their frame, Edit Contents, mesh handles and Control bar; Blend Options, anchor-targeted Blend tool, editable spine, keys picked on the canvas, faithful interpolation and knockout; Anchor Point spine conversion/handle editing and selection priority (#2544), with #2425 Shift reshape preserved; Perspective Grid with Define Grid, presets, lock/snap/rulers, widgets, the 1–4 plane switch, movable planes, Perspective Selection scale/copy/perpendicular/Transform Again, and type and symbols truly projected with Edit Text. Left: Anti-Alias and Preserve Shape output, warp-envelope point editing, brush interpolation in blends, Free Transform/Scale/Reflect along a rotated box; #5179 curved-spine redraw bounds include rotated keys and steps (two focused CPU regressions) | 2–4 | | M9 | Live effects (+ 3D & Materials) | 🟡 2D effects done incl. Effect → Pathfinder, Color Adjustments and Document Raster Effects Settings; PDF export warns when the pixel cap lowers raster-effect resolution; Artistic › Colored Pencil, Cutout, Dry Brush, Film Grain, Fresco, Neon Glow, Paint Daubs, Palette Knife, Poster Edges, Rough Pastels, Smudge Stick, Sponge, Underpainting and Watercolor and Sketch › Halftone Pattern, Bas Relief, Charcoal, Conté Crayon, Photocopy, Stamp, Torn Edges and Water Paper done (57/57 Photoshop filters); Revolve with automatic smooth vector shading, default-on circular caps and continuous rims, Extrude & Bevel, Inflate and Rotate with one to ten colored directional lights and four original lighting presets; SVG Filters, remaining raster effects and 3D materials and shadows pending | 81–130 | -| M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG ``/PDF export) and live Repeat (radial/grid/mirror) done; interactive selected mirror axis implemented (focused and native checks passed; full CI blocked by an unrelated text test); symbol libraries done (Window › Symbol Libraries, six generated libraries (Basic Shapes, UI Frames, Map Markers, Inventory Icons, Skill Icons, Weather Icons), User Defined, Other Library…, Save Symbols); brush libraries done (Window › Brush Libraries, fourteen generated libraries including Tech Circuit, Engraving, Arrows, Stipple, Pressure Sensitive, Ink and Wash, Bristle Brushes and Dry Media, User Defined, Other Library…, Save Brushes); symbol editing shows draggable 9-slice guides (#5280), with guides outside the artwork still unsupported; brushes/symbols in progress | 23–37 | -| M11 | Artboards & views (selected-set deletion shared by Artboards menu, trash and Properties, retaining artboard 1 when all are selected; Artboard deletion keys keep the first of an all-selected set and protect artwork; history prunes invalid indices while preserving valid multiselection (history tests and full workspace CI pass); click-to-fit objects with the Artboard tool (#1227), artboard escape routing and document setup modal handoff done; artboard panel/tool with Move Artwork for X/Y fields and Artboard Options, Trim View, middle-button pan, print tiling and the status bar's artboard navigator with synchronized Artboard tool selection done; Window › Arrange › Tile and Consolidate All Windows done; multiple windows, presentation polish) (cached canvas reprojection preserves scale during resize, rotation and DPI changes; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) (cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission; regression-tested; estimates unchanged); status-bar pointer coordinates follow the active ruler origin and General units | 🟡; Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting includes all drawn document art across artboards and off-board; artwork bounds are cached by active document and revision, and selection uses the shared bounds cache across artboards | 15–25 | +| M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG ``/PDF export) and live Repeat (radial/grid/mirror) done; interactive selected mirror axis implemented (focused and native checks passed; full CI blocked by an unrelated text test); symbol libraries done (Window › Symbol Libraries, six generated libraries (Basic Shapes, UI Frames, Map Markers, Inventory Icons, Skill Icons, Weather Icons), User Defined, Other Library…, Save Symbols); brush libraries done (Window › Brush Libraries, fifteen generated libraries including Tech Circuit, Decorative, Engraving, Arrows, Stipple, Pressure Sensitive, Ink and Wash, Bristle Brushes and Dry Media, User Defined, Other Library…, Save Brushes); symbol editing shows draggable 9-slice guides (#5280), with guides outside the artwork still unsupported; brushes/symbols in progress | 23–37 | +| M11 | Artboards & views (selected-set deletion shared by Artboards menu, trash and Properties, retaining artboard 1 when all are selected; Artboard deletion keys keep the first of an all-selected set and protect artwork; history prunes invalid indices while preserving valid multiselection (history tests and full workspace CI pass); click-to-fit objects with the Artboard tool (#1227), artboard escape routing and document setup modal handoff done; artboard panel/tool with Move Artwork for X/Y fields and Artboard Options, Trim View (hiding the guides and the grid while it is on, #8363), middle-button pan, print tiling and the status bar's artboard navigator with synchronized Artboard tool selection done; Window › Arrange › Tile and Consolidate All Windows done; multiple windows, presentation polish) (cached canvas reprojection preserves scale during resize, rotation and DPI changes; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) (cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission; regression-tested; estimates unchanged); status-bar pointer coordinates follow the active ruler origin and General units | 🟡; Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting includes all drawn document art across artboards and off-board; artwork bounds are cached by active document and revision, and selection uses the shared bounds cache across artboards | 15–25 | | M12 | Advanced color & art (CMYK/ICC, separations, Gradient Mesh, Live Paint, Image Trace, Graphs) | 🟡 Gradient Mesh, Live Paint, Image Trace (junction-returning pieces retain their positioned boundaries; a simpler contour walk with identical output; an edge's sub-pixel shift is the same from either side; notches read only their own piece; collapsed loops keep few segments; large images trace with a warning; Auto Color keeps rare distinct colours; quick presets trace at once and the Image Trace button opens the adjustment controls; Properties reopens them; tiny fitted contours retain islands and holes; Create Strokes: exact crop EDT, Guo–Hall thinning and maximal-disc graph simplification; 15 presets, the 14 documented ones each with an enhanced version; Ignore Color (manual picker and canvas eyedropper from original pixels, no canvas View change, missed pixels keep the pick armed, Preview/Undo retained; #8068), Shapes, Auto Grouping and Gradients options; measured in `image-trace-quality.md`; closed outlines retain their interior after straightening; the Flat Logo mode places edges to a fraction of a pixel, restores sharp corners, snaps lines and circles, and refuses gradients; live trace result bounds and selection highlights exclude the retained bitmap except in source-image views), Recolor Artwork, colour management (ICC, soft proofing, separations preview), Graphs (all 9 tools, Graph Data/Type, group-selected series colours persist through regenerate/save/open) done; Graph Design and Marker designs, Transpose and Switch x/y, `\|` label line breaks, the pie options, drop shadows, the legend across the top, overlapping widths, First Row/Column in Front, filled lines, kept label formatting and the Graph Data worksheet done; graph Column designs pending; Vector Halftone Preview keeps the selection box without drawing dot selection marks (#6369); Live Paint Bucket fills faces crossed in one drag (#6373) | 6–10 | | M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 MCP `add_text` exposes existing vertical point, area and path type; `script.run` and File › Scripts › Other Script… run JavaScript files, and Window › Script Console shows their output; the script document model and batch work remain | 18–27 | -| M14 | 1.0 polish (preferences, shortcut editor, workspaces, accessibility, packaging for all OSes) (status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates; sample widths cached by language/unit/DPI; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) | 🟡 Icon-strip flyouts resize on their free edges and retain sizes (#5713); interim macOS cursor delivery (#2292) uses existing artwork and host-owned AppKit cursors; headless coverage only, native menu/focus/handback and display validation pending. Dock groups collapse to their tabs by a double-click on a tab (UI.8); Preferences › General › Constrain Angle acts for the arrow keys, Shift drags and new objects (#394, 2026-10-21); numeric-field pointer selection and focus regression-tested (#1326; a release more than 1 pt from the press keeps the caret, a tap within 1 pt selects all, #6659); RPM runtime capabilities and glibc floor checked (#1275; real-distro install/start-up pending), Eyedropper cursor with precise-setting checks (#1269), Preferences, shortcut editor (chords with Shift and a punctuation key fire as typed; other apps' text shortcut sets imported), workspaces (each keeps its layout changes until Reset , UI.7), Window › Help Bar shown or hidden apart from the status bar and kept in saved workspaces, panels docked by dragging into any dock group (as tabs or a top/bottom split) or into the icon column, and closed from a dock tab's context menu (UI.6), a custom title bar on Windows/Linux with a Home button, content-sized dialogs, menus that scroll when longer than the window and macOS native menu dismissal done (M14.8), and native macOS save sheets with a Format menu (#866); titled PDF exports set `DisplayDocTitle` for viewers and accessibility checkers (#3646) and give the document language as the catalog's `/Lang` (#3644); accessibility and broader Windows/Linux packaging/QA pending; floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part), with pointer and native-window regression coverage; estimates unchanged; numeric spinner arrows keep repeating while held with the mouse (#6307); Swatches item context menus tested in all five views and rendered layouts inspected; Linux full CI passed, Windows engine baseline limitations documented (G12); Window > Toolbars > Compact Tools offers optional denser main Tools spacing in one or two columns, with the existing layout still the default (#7234) | 18–28 | +| M14 | 1.0 polish (preferences, shortcut editor, workspaces, accessibility, packaging for all OSes) (status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates; sample widths cached by language/unit/DPI; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) | 🟡 Icon-strip flyouts resize on their free edges and retain sizes (#5713); interim macOS cursor delivery (#2292) uses existing artwork and host-owned AppKit cursors; headless coverage only, native menu/focus/handback and display validation pending. Dock groups collapse to their tabs by a double-click on a tab (UI.8); Preferences › General › Constrain Angle acts for the arrow keys, Shift drags and new objects (#394, 2026-10-21); numeric-field pointer selection and focus regression-tested (#1326; a release more than 1 pt from the press keeps the caret, a tap within 1 pt selects all, #6659); RPM runtime capabilities and glibc floor checked (#1275; real-distro install/start-up pending), Eyedropper cursor with precise-setting checks (#1269), Preferences, shortcut editor (chords with Shift and a punctuation key fire as typed; other apps' text shortcut sets imported), workspaces (each keeps its layout changes until Reset , UI.7), Window › Help Bar shown or hidden apart from the status bar and kept in saved workspaces, panels docked by dragging into any dock group (as tabs or a top/bottom split) or into the icon column, and closed from a dock tab's context menu (UI.6), a custom title bar on Windows/Linux with a Home button, content-sized dialogs, menus that scroll when longer than the window and macOS native menu dismissal done (M14.8), and native macOS save sheets with a Format menu (#866); titled PDF exports set `DisplayDocTitle` for viewers and accessibility checkers (#3646) and give the document language as the catalog's `/Lang` (#3644); accessibility and broader Windows/Linux packaging/QA pending; floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part), with pointer and native-window regression coverage; estimates unchanged; numeric spinner arrows keep repeating while held with the mouse (#6307); Swatches item context menus tested in all five views and rendered layouts inspected; Linux full CI passed, Windows engine baseline limitations documented (G12); Graphic Styles item context menus in thumbnail and list views with Options, Duplicate, Delete, Redefine, Break Link (#8755); Window > Toolbars > Compact Tools offers optional denser main Tools spacing in one or two columns, with the existing layout still the default (#7234) | 18–28 | | — | Interaction fidelity pass (every tool's modifiers, Properties panel per context, isolation, nuance; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed) | ⬜ (new ruler-guide Alt orientation implemented; existing-guide Escape cancellation regression-tested; broader pass remains) | 60–90 | | — | Hardening at scale (big-file corpus, fuzzing, cross-platform + browser QA) | 🟡 PngSuite integrity and bounded fetching verified (#1729); real-world corpus/manual QA remain | 50–80 | | M14 follow-up | Color Picker layout (#2008) | ✅ Compact controls, centered header, stacked actions, aligned fields and screen sampling; narrow windows scroll vertically | Included above | @@ -232,6 +235,9 @@ not take the artwork yet. Overflow-menu drag remains separate. Scores and hours | Date | Change | Summary | |---|---|---| +| 2026-11-19 | minor | M11: View › Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid; a ruler drag or double-click makes no guide meanwhile (#8363). Scores and estimates unchanged | +| 2026-11-19 | minor | Scissors previews its actual anchor or curve cut point with a native point marker while hovering, retaining existing snapping, Alt Add Anchor and cut behavior (#8655). Scores and estimates unchanged. | +| 2026-11-19 | minor | M5: In the web build, an edit while the view of a heavy document moves (a tool drag held at an edge of the canvas, #8551, or a wheel scroll during a drag) draws only the part it changed into the last frame, which stays drawn moved with the view, instead of rendering the whole canvas each frame (an edit that changes more than half of the frame, or a change of more than the view and the document, still renders it whole at once), and edits that go on once the view is still don't put off its render (#8688). Scores and estimates unchanged. | | 2026-11-18 | minor | M10/G5: Media Controls joins Basic Shapes, UI Frames, Map Markers, Inventory Icons, Skill Icons and Weather Icons as a seventh built-in symbol library (Play, Pause, Stop, Skip Next, Shuffle, Repeat; original procedural vector symbols generated in code, no default 9-slice); G5 estimate decremented to 2–12 h, milestone estimates unchanged | | 2026-11-18 | minor | M7/G4: Retype phase 1 (#4934): `type.retype` turns outlined text that exactly matches an available font back into point text. Scores and estimates unchanged | | 2026-11-18 | minor | M1: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538). Scores and estimates unchanged. | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index a8e5bf9537..0616b700f0 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # Parity with Adobe Illustrator -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-18 · **Change:** minor (Artboard tool: Shift held once a move or Alt-copy drag is under way keeps it to the level, upright or 45° line, #8580; scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: G12: Place: show progress window with Cancel for slow placed files exceeding 0.4 s, part of #5930; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: Layers: selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: PDF import: type filled and stroked after a page of type filled only comes in filled and stroked, #8549 follow-up; scores and estimates unchanged; previously: selected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: #8200: `.ai` and EPS import: an Art brush in Tints of a swatch-linked stroke color comes in brushed, its tints linked to the swatch; scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: SVG export preserves document units on root width/height for physical units, #864; G11 estimate 8–15 → 6–13 h; previously: Floating panels keep their window level while focus moves between the app's windows, so a press on one panel's bar no longer hands the keyboard to another, #6986; scores and estimates unchanged; previously minor: #8128: `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths, so the compound clipping path clips its clipping group; scores and estimates unchanged; previously: import: type filled and stroked by a `TJ` whose kerning starts a new line comes in filled and stroked, #8543; PDF Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; Layers panel: an Alt-drag copies a row above or below itself, so the top layer dragged up, the bottom layer dragged down and a lone layer are copied, #8237; scores and estimates unchanged; previously: Twist: a strongly twisted path joins its pieces without kinks, #7069; scores and estimates unchanged; previously: PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; Layers panel: Alt over the list shows the copy cursor while rows or the selection square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Properties panel: the Character section shows the font of the Type tool's selection, not the first run's (#8189); scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Paragraph composers (#4935): the Paragraph panel menu and paragraph styles offer four composers, the Middle Eastern & South Asian Single-line and Every-line (how all type is set, and the default) and a Standard Single-line and Every-line that set Indic, Arabic and Hebrew type glyph by glyph as the font maps it, for legacy fonts that keep a script on Latin character codes; PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; G5: Neon & Glow joins built-in graphic style libraries (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); scores and estimates unchanged; previously: Pencil ignores Smart Guides and Snap to Point and shows no Smart Guides, #7252; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: G5: Weather Icons joins built-in symbol libraries (Sun, Moon, Cloud, Rain, Thunder, Snow); scores and estimates unchanged; previously: a closed Pencil stroke closes with a straight segment; previously: Snap to Point with Smart Guides off draws no Smart Guides labels or lines, #7250; previously: 3D: the seams of Extrude & Bevel, Inflate and Rotate under a white light, and of the faces of Extrude & Bevel (Classic), Revolve (Classic) and Rotate (Classic), went from miter to round joins, so white-light 3D output is expected to differ from the 2026-10-17 comparison at facet corners (not measured: the scenes were not exported again); previously: `.ai` and EPS import: in layers that don't draw as the page, art that differs away from an envelope of type no longer costs it its editable type; it keeps its drawn art where, in the pixels it and its drawn art ink, the layers with it differ from the page more than its own check allows, or past the envelopes' share of the page check, #7141; Character panel: the Set Font Height Reference dropdown shows an icon before each reference, #6304; scores and estimates unchanged; previously: Envelopes: a top object's side whose pieces are all one curve split at anchors follows that curve's parameter, so a top object saved with its sides' curves in pieces draws as its `.ai` drawn art, #7097; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously minor: Object › Rasterize with the Grayscale or Bitmap colour model makes a grayscale image, #6969; scores and estimates unchanged; previously minor: `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, miter tips and moved strokes included, after its glyphs grown by half its strokes' weight (#6824; #6617: Swatches panel menu: Show Recent Colors; scores unchanged; previously minor: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Type tool: kerning at a caret at the start of a line moves the character after it, #5111; scores and estimates unchanged; previously minor: Rulers: the zero point dragged out of the rulers' corner snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Envelopes: with Distort Appearance, type's strokes paint along the bent glyph outlines at their own weight, as users' `.ai` files draw them, which changes how VectorCraft's own envelopes of stroked type draw (#6644; scores and estimates unchanged); previously minor: G5: Energy Beams brush library; bundled content ~44% → ~46%; previously minor: G5: Skill Icons symbol library; bundled content ~42% → ~44%; previously minor: `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art (#6570; scores and estimates unchanged); previously minor: ruler double-click adds a guide at the pointer, #5239; G5: Status Effects graphic style library; bundled content ~40% → ~42%; MCP symbol libraries list UI Frames and Map Markers; previously minor: G5: Inventory Icons built-in symbol library; bundled content ~38% → ~40%; previously minor: `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke (#3179; scores and estimates unchanged); previously minor: `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid where VectorCraft's warp doesn't draw as their drawn art (#3179; scores and estimates unchanged); G5: Game Trails brush library; bundled content ~36% → ~38%; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page (#3179; scores and estimates unchanged); G5: Game HUD graphic style library; bundled content ~34% → ~36%; previously minor: Line Arrow arrowhead (#5421; scores and estimates unchanged); G5: Map Markers built-in symbol library; bundled content ~32% → ~34%; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Canvas: a 3D effect changed on type or a group redraws where its solid was; Fit to Artwork Bounds and per-artboard SVG export build each solid once for all artboards; previously minor: Effect Gallery: a thumbnail for each filter and a preview area inside the dialog, on an original drawing; Raster effects 52% → 55%, hours 1–2 → none; headline numbers unchanged; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: UI Frames built-in symbol library with default 9-slice; bundled content ~32%; previously minor: G5: dynamic symbol part on-canvas opacity/blend/gradient/pattern; strokes remaining no longer lists Overlap/auto corners; symbols ~88%; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: harakat paint fallback clarified; previously minor: current Guides feature-area rows consolidated using existing ruler evidence; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap and Pattern brush auto corners removed from strokes remaining; symbols remaining lists dynamic on-canvas beyond solid and guides outside the art; previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; `.ai` and EPS import: older Art brush objects read; numeric fields step on wheel hover without taking keyboard focus, and a panel wheel turn cannot seed a canvas zoom glide, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; the canvas keeps selection outlines and anchors between frames; Indian-language hyphenation review and license allowlist, #4947; Stroke gradients: an arrowhead aligned to the tip is painted to the corners of its base, #5964; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-20 · **Change:** minor (Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid, #8363; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: G12: Brushes panel: item right-click context menu (Brush Options, Duplicate Brush, Delete Brush) with selection handling; scores and estimates unchanged; previously: Graphic Styles panel: right-click item context menu for tiles and rows with Options, Duplicate, Delete, Redefine, Break Link; scores and estimates unchanged; previously: In the web build, an edit while the view of a heavy document moves (a tool drag held at an edge of the canvas, #8551, or a wheel scroll during a drag) draws only the part it changed into the last frame, which stays drawn moved with the view, instead of rendering the whole canvas each frame, and edits that go on once the view is still don't put off its render (#8688); scores and estimates unchanged; previously: G12: Links panel row context menu (Relink…, Go To Link, Update Link, Edit Original, Show in Folder, Embed Image / Unembed…) with selection handling; scores and estimates unchanged; previously: Artboard tool: Shift held once a move or Alt-copy drag is under way keeps it to the level, upright or 45° line, #8580; scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: G12: Place: show progress window with Cancel for slow placed files exceeding 0.4 s, part of #5930; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: Layers: selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: PDF import: type filled and stroked after a page of type filled only comes in filled and stroked, #8549 follow-up; scores and estimates unchanged; previously: selected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: #8200: `.ai` and EPS import: an Art brush in Tints of a swatch-linked stroke color comes in brushed, its tints linked to the swatch; scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: SVG export preserves document units on root width/height for physical units, #864; G11 estimate 8–15 → 6–13 h; previously: Floating panels keep their window level while focus moves between the app's windows, so a press on one panel's bar no longer hands the keyboard to another, #6986; scores and estimates unchanged; previously minor: #8128: `.ai` and EPS import: clipping paths grouped in a compound path are its subpaths, so the compound clipping path clips its clipping group; scores and estimates unchanged; previously: import: type filled and stroked by a `TJ` whose kerning starts a new line comes in filled and stroked, #8543; PDF Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: PDF export writes the document language as the catalog's `/Lang`, #3644; Layers panel: an Alt-drag copies a row above or below itself, so the top layer dragged up, the bottom layer dragged down and a lone layer are copied, #8237; scores and estimates unchanged; previously: Twist: a strongly twisted path joins its pieces without kinks, #7069; scores and estimates unchanged; previously: PDF import: a glyph filled only after a glyph filled and stroked comes in filled only, not stroked, #8300; PDF import: translucent type filled and stroked comes in as a filled type object and a stroked one, as the file composites them, and an upright glyph is never kept as the outline of its glyph alone, #8015; PDF import: type filled and stroked by one text-showing operator comes in as one type object, filled and stroked, not a stroked copy over a filled one, #8015; Layers panel: Alt over the list shows the copy cursor while rows or the selection square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Properties panel: the Character section shows the font of the Type tool's selection, not the first run's (#8189); scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Paragraph composers (#4935): the Paragraph panel menu and paragraph styles offer four composers, the Middle Eastern & South Asian Single-line and Every-line (how all type is set, and the default) and a Standard Single-line and Every-line that set Indic, Arabic and Hebrew type glyph by glyph as the font maps it, for legacy fonts that keep a script on Latin character codes; PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; G5: Neon & Glow joins built-in graphic style libraries (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); scores and estimates unchanged; previously: Pencil ignores Smart Guides and Snap to Point and shows no Smart Guides, #7252; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: G5: Weather Icons joins built-in symbol libraries (Sun, Moon, Cloud, Rain, Thunder, Snow); scores and estimates unchanged; previously: a closed Pencil stroke closes with a straight segment; previously: Snap to Point with Smart Guides off draws no Smart Guides labels or lines, #7250; previously: 3D: the seams of Extrude & Bevel, Inflate and Rotate under a white light, and of the faces of Extrude & Bevel (Classic), Revolve (Classic) and Rotate (Classic), went from miter to round joins, so white-light 3D output is expected to differ from the 2026-10-17 comparison at facet corners (not measured: the scenes were not exported again); previously: `.ai` and EPS import: in layers that don't draw as the page, art that differs away from an envelope of type no longer costs it its editable type; it keeps its drawn art where, in the pixels it and its drawn art ink, the layers with it differ from the page more than its own check allows, or past the envelopes' share of the page check, #7141; Character panel: the Set Font Height Reference dropdown shows an icon before each reference, #6304; scores and estimates unchanged; previously: Envelopes: a top object's side whose pieces are all one curve split at anchors follows that curve's parameter, so a top object saved with its sides' curves in pieces draws as its `.ai` drawn art, #7097; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously minor: Object › Rasterize with the Grayscale or Bitmap colour model makes a grayscale image, #6969; scores and estimates unchanged; previously minor: `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, miter tips and moved strokes included, after its glyphs grown by half its strokes' weight (#6824; #6617: Swatches panel menu: Show Recent Colors; scores unchanged; previously minor: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Type tool: kerning at a caret at the start of a line moves the character after it, #5111; scores and estimates unchanged; previously minor: Rulers: the zero point dragged out of the rulers' corner snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Envelopes: with Distort Appearance, type's strokes paint along the bent glyph outlines at their own weight, as users' `.ai` files draw them, which changes how VectorCraft's own envelopes of stroked type draw (#6644; scores and estimates unchanged); previously minor: G5: Energy Beams brush library; bundled content ~44% → ~46%; previously minor: G5: Skill Icons symbol library; bundled content ~42% → ~44%; previously minor: `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art (#6570; scores and estimates unchanged); previously minor: ruler double-click adds a guide at the pointer, #5239; G5: Status Effects graphic style library; bundled content ~40% → ~42%; MCP symbol libraries list UI Frames and Map Markers; previously minor: G5: Inventory Icons built-in symbol library; bundled content ~38% → ~40%; previously minor: `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke (#3179; scores and estimates unchanged); previously minor: `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid where VectorCraft's warp doesn't draw as their drawn art (#3179; scores and estimates unchanged); G5: Game Trails brush library; bundled content ~36% → ~38%; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page (#3179; scores and estimates unchanged); G5: Game HUD graphic style library; bundled content ~34% → ~36%; previously minor: Line Arrow arrowhead (#5421; scores and estimates unchanged); G5: Map Markers built-in symbol library; bundled content ~32% → ~34%; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Canvas: a 3D effect changed on type or a group redraws where its solid was; Fit to Artwork Bounds and per-artboard SVG export build each solid once for all artboards; previously minor: Effect Gallery: a thumbnail for each filter and a preview area inside the dialog, on an original drawing; Raster effects 52% → 55%, hours 1–2 → none; headline numbers unchanged; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: UI Frames built-in symbol library with default 9-slice; bundled content ~32%; previously minor: G5: dynamic symbol part on-canvas opacity/blend/gradient/pattern; strokes remaining no longer lists Overlap/auto corners; symbols ~88%; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: harakat paint fallback clarified; previously minor: current Guides feature-area rows consolidated using existing ruler evidence; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap and Pattern brush auto corners removed from strokes remaining; symbols remaining lists dynamic on-canvas beyond solid and guides outside the art; previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; `.ai` and EPS import: older Art brush objects read; numeric fields step on wheel hover without taking keyboard focus, and a panel wheel turn cannot seed a canvas zoom glide, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; the canvas keeps selection outlines and anchors between frames; Indian-language hyphenation review and license allowlist, #4947; Stroke gradients: an arrowhead aligned to the tip is painted to the corners of its base, #5964; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) > > Tech Circuit update (2026-11-14): three original procedural brushes; ten built-in brush libraries (G5). > @@ -30,6 +30,8 @@ ## Feature submission evidence +**Scissors cut-point preview (#8655):** A native point marker shows the anchor or position on a curve that the current Scissors click targets, including the existing snapping rules. Hovering changes no artwork; an ineligible or stale hover has no marker. Existing cut and Alt Add Anchor behavior are retained. Focused tool and Session regressions live in `crates/tools/src/draw2/anchor/tests.rs` and `crates/engine/tests/scissors_snap.rs`. Scores and estimates are unchanged. + `window.panel.float` updates an existing native panel window's supplied position and size (#8391). Positions use the main window's content origin. Omitted coordinates and dimensions keep their current native values, including after an OS window move or resize. Evidence: `panel_docking::native_tests::an_explicit_float_command_updates_an_existing_native_windows_geometry` covers panel, group and column commands. Scores and estimates are unchanged. EPS embedded fonts, 2026-11-09 (#6023–#6067): the fonts an EPS carries draw their glyphs instead of being set as type in an installed font: composite (Type 0) fonts with the 8/8 mapping, plain Type 42 fonts (characters from their glyph names or character map, widths from the font), CID-keyed fonts over CMaps (Type 0 and Type 2 CIDFonts, CIDFonts in a FontSet's Compact Font Format data, base-font CMaps, named CIDFonts over predefined Unicode CMaps set as type) and embedded Type 1 fonts; the show operators' spacing along the baseline is kept as tracking, `kshow` included. Each step is charged to the interpreter's budgets. Hand-written test files only (no corpus file uses these fonts); scores and estimates unchanged. Evidence: `crates/eps/src/import/tests_composite.rs`, `tests_type42.rs`, `tests_cid.rs`, `tests_type1.rs`; details in [file-format-parity.md](file-format-parity.md). @@ -73,6 +75,8 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-11-19 | minor | G12: Brushes panel item right-click context menu offering Brush Options…, Duplicate Brush, and Delete Brush (disabled if the last remaining brush); right-clicking an unselected brush selects it first, and right-clicking within a multi-selection preserves it offering Duplicate Brushes / Delete Brushes; headless tests in `crates/ui-egui/src/panels/brushes/tests.rs`; scores and estimates unchanged. | +| 2026-11-19 | minor | G12: Links panel row context menu (Relink…, Go To Link, Update Link, Edit Original, Show in Folder, Embed Image / Unembed…); right-clicking an unselected link row selects it first, and right-clicking within a multi-selection preserves it; headless tests in `crates/ui-egui/src/panels/tests_links.rs`; scores and estimates unchanged. | | 2026-11-19 | minor | PDF import (#8549 follow-up): type filled and stroked after a page of type filled only came in as a filled object and a stroked one: since #8549 lines filled only are kept for a stroke pass too, and the glyphs of the lines finished past the 64 kept were remembered until the next stroke, so `2 Tr (Title) Tj` after more than 64 lines of type filled only took its first stroke for the start of a stroke pass over them, always once more than 4,096 glyphs had been finished so. Those glyphs are now forgotten when anything else is drawn (a path, an image, a Type 3 glyph's art, a change of blend mode or soft mask: nothing is drawn between an operator's fill pass and its stroke pass), and past the first 4,096 glyphs none are remembered instead of every stroke matching. A `TJ` over more lines than are kept still comes in as a filled object and a stroked one for each part, also when it ends where it began, and when a glyph kept as an outline comes before that (the line it starts keeps the glyphs of the lines finished). Remaining: with nothing drawn between them, type filled and stroked at exactly the place, font, size and text of a glyph filled only on a line finished so still comes in as a filled object and a stroked one, as the device can't tell its stroke pass from the start of one over that glyph. Tests: `type_filled_and_stroked_after_a_dense_page_of_filled_type_is_filled_and_stroked`, `type_filled_and_stroked_over_a_finished_glyph_after_a_path_is_filled_and_stroked`, `an_outline_glyph_in_a_tj_over_more_lines_than_are_kept_leaves_fill_and_stroke_apart`; scores and estimates unchanged. | | 2026-11-18 | minor | Layers: a layer whose art was all added to the selection from its target circle shows as targeted, as an object does (#8646). Scores and estimates unchanged. | | 2026-11-18 | minor | G11: SVG export writes physical unit suffixes on the root for documents with physical units (mm, cm, in, pc), preventing drawings from scaling to 75% in external tools and preserving units across round-trips (#864; general unit preference on restart remains open under #864). Tests: export_physical_units_writes_unit_suffixes (crates/svg/tests/it/import_units.rs) and svg_round_trip_preserves_document_units (crates/engine/src/cmd/fileio/tests_svg.rs). G11 estimate 8–15 → 6–13 h. | @@ -275,10 +279,10 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | Area | Weight | Done | Main gaps | One agent (h) | Kind | |---|---:|---:|---|---:|---| | Selection, transform & align tools | 6 | 85% | Direct Selection segment click/Delete corrected (#1278); deletion splits an ordinary contour into selected sibling objects with bounds-fitted gradients kept in place (#3380, deletion only; `crates/engine/tests/it/delete_path_pieces.rs`); open-path anchor Delete keeps gaps; Select › Start Global Edit finds the paths, compound paths and symbol instances of the selected object's shape (Appearance, Size and artboard options) and gives an edit of one to all of them in proportion, as one undo step (#3521), and on a group the groups like it, an edit inside one reaching the same object in the others (#4939), and a Shift-click on a highlighted match leaves it out; the Align panel menu's Align to Glyph Bounds › Point Text and Area Text measure type by its glyphs' ink for Align and Distribute (#4231); remaining: Free Transform/Scale/Reflect along a rotated box, Global Edit of rotated copies, transform nuances (no-op anchor Align history regression-tested, #1180 follow-up) | 4–6 | estimated; fill-stack selection regression-tested (`crates/engine/tests/path_fill_hits.rs`, #6625); cap/join follow-up CPU regressions passed; Global Edit regression-tested (`crates/engine/src/tests/globaledit.rs`; Quick Action, menu label and Escape in `panels::properties::tests::start_global_edit_quick_action_and_escape`) | -| Drawing tools (Pen, Curvature, Pencil, shapes, Shaper) | 7 | 85% | Shaper construction widget, Pencil/Pen nuances, Blob Brush options, Touch Type, Dimension tool; see [ui-parity.md](ui-parity.md) | 8–13 | estimated; Curvature point display regression-tested (#1236, in part); Polygon/Star exact-size count persistence regression-covered; Live Corners' Relative rounding done (#3091), score unchanged; Copy and Cut with the Pen or Curvature tool take the anchors a Cmd/Ctrl-lent Direct Selection picked (#6123), score and hours unchanged; the Pen, Smart Pen and Curvature tool show the measurement readout with the rubber band off (#7043), score, gaps and hours unchanged; Scissors shares the Pen's path/align/intersect/anchor snaps (#6470), source and headless regressions below; Eraser preserves fill-only open-path area outside fixed and varied tip sweeps and Alt-drag marquees, including compound holes; clipping masks keep their remaining contours and empty-mask role; ordinary Group/Layer paints and evaluated gradient placements are preserved when the stored paint reproduces their appearance; replacement-art effects, plug-ins/Rasterize, along/across-stroke gradients and placements that cannot be reproduced keep their existing fitting; stroked open paths retain main behavior and result structure (#6582; `crates/engine/tests/eraser_open_fill.rs`), score and hours unchanged | +| Drawing tools (Pen, Curvature, Pencil, shapes, Shaper) | 7 | 85% | Shaper construction widget, Pencil/Pen nuances, Blob Brush options, Touch Type, Dimension tool; see [ui-parity.md](ui-parity.md) | 8–13 | estimated; Curvature point display regression-tested (#1236, in part); Polygon/Star exact-size count persistence regression-covered; Live Corners' Relative rounding done (#3091), score unchanged; Copy and Cut with the Pen or Curvature tool take the anchors a Cmd/Ctrl-lent Direct Selection picked (#6123), score and hours unchanged; the Pen, Smart Pen and Curvature tool show the measurement readout with the rubber band off (#7043), score, gaps and hours unchanged; Scissors shares the Pen's path/align/intersect/anchor snaps (#6470), source and headless regressions below; Eraser preserves fill-only open-path area outside fixed and varied tip sweeps and Alt-drag marquees, including compound holes; clipping masks keep their remaining contours and empty-mask role; ordinary Group/Layer paints and evaluated gradient placements are preserved when the stored paint reproduces their appearance; replacement-art effects, plug-ins/Rasterize, along/across-stroke gradients and placements that cannot be reproduced keep their existing fitting; stroked open paths retain main behavior and result structure (#6582; `crates/engine/tests/eraser_open_fill.rs`), score and hours unchanged; Scissors cut-point preview covered in tool and Session regressions (#8655), scores and hours unchanged | | Path operations, Pathfinder, Shape Builder, Live Paint | 5 | 80% | Shape Builder on the reporter's file (#937: art past 4,096 segments is cut by lines again; unconfirmed on the file itself); gap detection shares Live Paint’s finder, with a 72 pt custom cap and the existing options; Live Paint Gap Options | 4–8 | estimated; Shape Builder Gap Detection shares Live Paint’s spatial gap finder and temporary merge bridges (#2526); Custom is capped at 72 pt in the existing options dialog (lowered from 86%: open issues); compound attributes regression-tested (#1197); single-result source names survive SVG export/import (#1293), with [SVG ID semantics](https://www.w3.org/TR/SVG2/struct.html#IDAttribute) and original-shape tests; Simplify component selection and preview regression-tested (#1272); Simplify of a Direct Selection part of a path regression-tested (`tests/simplify_part.rs`); Divide open-cutting-path geometry and appearance regression-tested (#1307); the Shape Builder's edge-source grid is bounded in memory and files a segment once per cell (`planar.rs` test `rect_index_holds_a_bounded_number_of_references`); live compound shapes (Make, Alt-click, member Shape Modes, Release, Expand, saved and exported) regression-tested (#4522); Live Paint Bucket face drags, including narrow faces and one Undo, regression-tested (#6373) | | Colour, swatches, gradients, patterns, mesh, recolor | 7 | 92% | Picker Lab entry, picker libraries and Assign-row menus complete the deferred #4028 UI paths (#8031); scores and estimates unchanged; Eyedropper copies effective character dimensions across text transforms (#6404); 30.0's gradient additions are done (dither, perceptual blending, presets); freeform gradients in SVG/PDF, mixed spot/process gradients in SVG, PDF gradients mixing a spot color with RGB or Lab stops, and dithered spot gradient fills and Perceptual spot gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve, which PDF export writes as images in process colors| 4–7 | estimated; Recolor model selection is available through the engine and MCP (#2520), and the dialog's color sliders (HSB, RGB, CMYK, Lab, Tint for a spot color) edit the selected row's new color in its mode, and the Edit tab's Global Adjust sliders (Saturation, Brightness, Temperature, Luminosity, -100% to 100%) change every recolored color at once (lowered from 96%: target moved); unpainted zero-width stroke restoration fixed (#1253), score and hours unchanged; Eyedropper source reads regression-tested (#1251); screen-bounded Recolor Edit chip list (#3416), score and hours unchanged; a point on a gradient mesh's outline locates on its edge on every side (#7006: `mesh_locate_takes_a_point_on_any_side_of_the_outline`, `mesh_add_line_exactly_on_the_edge_needs_no_tolerance`), score and hours unchanged; Color panel spectrum grows with the resized panel (#8005) | -| Strokes, brushes, width profiles | 5 | 88% | Shift-double-click adjoining adjustment is implemented; brush libraries are done (fourteen generated libraries including Tech Circuit, Engraving, Arrows, Stipple, Pressure Sensitive, Ink and Wash, Bristle Brushes, Game Trails, Energy Beams and Dry Media, User Defined, Other Library…, Save Brushes); Art brush Overlap and Pattern brush auto corners are done; remaining: pen pressure on macOS, Stylus Wheel, more built-in brush libraries, tilt, bearing and rotation for Art, Pattern and Bristle brushes and on native Wayland and the web | 8–15 | estimated; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed; evidence below; finite-arithmetic follow-up regressions and full CI passed (evidence below) | +| Strokes, brushes, width profiles | 5 | 88% | Shift-double-click adjoining adjustment is implemented; brush libraries are done (fifteen generated libraries including Tech Circuit, Decorative, Engraving, Arrows, Stipple, Pressure Sensitive, Ink and Wash, Bristle Brushes, Game Trails, Energy Beams and Dry Media, User Defined, Other Library…, Save Brushes); Art brush Overlap and Pattern brush auto corners are done; remaining: pen pressure on macOS, Stylus Wheel, more built-in brush libraries, tilt, bearing and rotation for Art, Pattern and Bristle brushes and on native Wayland and the web | 8–15 | estimated; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed; evidence below; finite-arithmetic follow-up regressions and full CI passed (evidence below) | | Appearance, transparency, graphic styles, masks | 5 | 97% | raster effect reach in preview bounds | 1–2 | estimated; Transform typing, sliders, preview, and undo are covered in `crates/ui-egui/src/panels/tests_appearance.rs` | | 3D and Materials (and Turntable) | 4 | ~25% | live Revolve with automatic smooth vector shading and default-on continuous circular caps, Extrude & Bevel (twist, taper, caps, five bevel shapes), Inflate and Rotate with Position presets (colored Inflate uses smooth membrane lighting; white-light Inflate retains its existing shading; Extrude & Bevel and Rotate retain planar shading; one to ten colored lights, shared neutral ambient, painter visibility); materials, light presets, shadows, ray tracing, Turntable views, textures, map art and shading in 3D export | 30–55 | estimated (Extrude & Bevel, Inflate and Rotate added 2026-10-12); Map Art on Extrude & Bevel (Classic) and Revolve (Classic) is covered by `crates/effects/src/solids/tests_map_art.rs` and `crates/engine/src/cmd/effectcmd/map_art_tests.rs` (score and hours unchanged); every 3D seam has round joins (2026-11-12, [three-d.md](three-d.md#seams)), score, gaps and hours unchanged | | Type core | 9 | 80% | Auto-leading style resets are implemented; Hyphenation… and Justification… options are done (#2310, #2755), and a paragraph's Auto Leading also sets the Character panel's Leading, the Alt+↑/↓ leading nudge and Fill with Placeholder Text; remaining: Optical Margin Alignment, Middle Eastern features beyond bidi layout (the Middle Eastern & South Asian and Standard composers are done per paragraph, #4935; `.ai`/EPS/PDF files carry no composer), optional group font-size preservation; transformed character controls fixed (#1034), see [type-parity.md](type-parity.md) | 14–19 | estimated; eleven-language pattern hyphenation in both composers, with grapheme and shaping-cluster protection (#4947, `hyphen::tests` and `layout::wrapping_tests`); Sanskrit patterns pending an allowlisted source; recent-font groups in font pickers (#3515); full-name font matches regression-tested (#1258); mixed paragraph alignment indication implemented; headless regressions, full integration CI and visual review pass; localized legacy family-name fallback with loaded/catalog regressions (#2208); Fractional Widths per type object regression-tested; color emoji fonts with bitmap glyphs (`sbix`, `CBDT`) draw and export; threading ports: every selected area type and type on a path shows its in and out ports (empty, arrow, red "+"), and the Selection tool threads from either, the in port into a frame before it, and a double-click on a threaded port breaks the thread there (`threads::tests::break_splits_the_thread_and_the_story_flows_into_the_first_part`, `select::tests::a_double_click_on_a_threaded_port_breaks_the_thread`, `canvas::tests::a_double_click_on_a_threaded_out_port_breaks_the_thread`) (#2572; `select::tests::a_click_on_the_in_port_threads_into_a_frame_before_it`, `text::tests::selected_type_shows_its_ports_in_each_state`, `threads::tests::add_before_threads_the_story_from_the_new_frame_into_the_clicked_one`, live screenshot); the Glyphs panel highlights and scrolls to the character selected with the Type tool (#4908, `panels::glyphs` tests); the OpenType panel lists only `ss01`–`ss20` sets present in the selected font and uses its custom names when supplied; Type-range desktop Copy publishes styled art and keeps font family, size and color on canvas Paste after editing (#5636); paint-only Arabic harakat keep joining with conditional GDEF-mark ownership and Insert Kashidas base-letter paint (`tests::harakat`) | @@ -550,7 +554,7 @@ about 1–1.5 agent-hours each, so the other rows (estimated on the older scale) | Drawing tools | 7 | 86% | Eraser preserves fill when cutting fill-only open paths with fixed or varied tips or Alt-drag marquees; painted-stroke paths retain main behavior and clipping masks keep their remaining contours or empty geometry, with reproducible evaluated gradient placement preserved on ordinary paths, compounds, groups and layers (#6582); replacement-art effects, plug-ins/Rasterize, along/across strokes and placements that cannot be reproduced retain fitting; rough-square Shaper recognition and orientation steps corrected; editable Shaper Groups landed; Pencil: Alt key toggles to Smooth Tool (#2001); remaining: Shaper construction widget/gesture refinements, pencil and the remaining pen modifier nuances, Blob Brush Merge Only with Selection, Touch Type, Live Corners' Relative rounding | 7–12 | | Path operations, Pathfinder, Shape Builder, Live Paint | 5 | 86% | Live Paint gap options, Shape Builder gap detection, options (Tool Options dialog, clicking a stroke in merge mode) and Shift-drag marquee | 3–6 | | Colour, swatches, gradients, patterns, mesh, recolor | 7 | 96% | Picker Lab entry, picker libraries and Assign-row menus complete the deferred #4028 UI paths (#8031); scores and estimates unchanged; Library panels' lists (swatch, Color Book, brush, symbol and graphic style libraries) fill a taller panel above its footer (#2992; scores and estimates unchanged); Swatches list fills a taller panel above its footer (#1638; `the_list_fills_a_tall_panel_above_its_footer`; scores and estimates unchanged); freeform gradients in SVG/PDF and mixed spot/process gradients in SVG (exported as stops; PDF export keeps the spot inks in a DeviceN shading, except next to RGB or Lab stops; dithered fills and Perceptual gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve are written as images in process colors), pattern fills in Expand | 2–4; Eyedropper source reads regression-tested (#1251) | -| Strokes, brushes, width profiles | 5 | 90% | more built-in brush libraries (fourteen generated in code including Tech Circuit, Engraving, Arrows, Stipple, Pressure Sensitive, Ink and Wash, Bristle Brushes, Game Trails, Energy Beams and Dry Media are done; Art brush Overlap and Pattern brush auto corners are done), pen pressure on macOS (the windowing layer reports none there), Stylus Wheel, tilt, bearing and rotation for Art, Pattern and Bristle brushes and on native Wayland and the web | 8–15 | +| Strokes, brushes, width profiles | 5 | 90% | more built-in brush libraries (fifteen generated in code including Tech Circuit, Decorative, Engraving, Arrows, Stipple, Pressure Sensitive, Ink and Wash, Bristle Brushes, Game Trails, Energy Beams and Dry Media are done; Art brush Overlap and Pattern brush auto corners are done), pen pressure on macOS (the windowing layer reports none there), Stylus Wheel, tilt, bearing and rotation for Art, Pattern and Bristle brushes and on native Wayland and the web | 8–15 | | Appearance, transparency, graphic styles, masks | 5 | 98% | Graphic Styles list fills a taller panel above its footer (#2992; scores and estimates unchanged); raster effect reach in preview bounds (flattener presets apply in PDF, EPS and print) | 1–2 | | Live vector effects | 5 | 85% | Outline Object, Pathfinder Hard/Soft Mix and Trap (since done: #3061, #3063, #3785), SVG Filters, Transform Patterns and Scale Strokes & Effects on a fill's or stroke's own Transform effect | 6–10 | | 3D and Materials | 4 | ~25% | Initial Revolve, Extrude & Bevel, Inflate and Rotate, with simple lighting; materials, light presets, shadows, ray tracing, Rotate (Classic), Map Art and more complete visibility remain | 25–45 | @@ -602,7 +606,7 @@ since 2026-10-01. | **Interaction fidelity:** modifiers, cursors, small behaviours | ~30–40% | The dedicated pass hasn't started, and there has been no side-by-side session with Illustrator yet. A power user notices this first | | **Look & feel** | ~75–80% | Measured against Illustrator 2026 screenshots (2026-10-02); the panels added since haven't been re-measured | | **File interop** | ~85% | SVG/SVGZ, PDF and PDF-compatible `.ai` (and legacy version 7 `.ai` out, keeping layers, groups and type as text), EPS, DXF, EMF/WMF, raster formats, PSD export and PSD/PSB placement (merged image), Place and Links, Package, Print, clipboard flavours. Affinity documents (Affinity 1–3) open natively as editable art, checked against 51 pinned public files (33 current `.af`), with selected saved-thumbnail comparisons and every-board native/SVG/PDF/PSD checks for current files; Affinity export is missing and effects, adjustments and brushes don't import. Affinity isn't an Illustrator feature, so this doesn't raise the parity score. The editing copy inside an Illustrator EPS or `.ai` is read for its structure: layers, groups, names, hidden objects and type, colours, gradients, transparency, images and every artboard (see Out of scope for what it doesn't read yet); DWG has no open spec | -| **Bundled content:** brush, symbol, style and swatch libraries | ~46% | Ours are original and generated in code, and far fewer than Illustrator ships; symbol libraries have six (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons, Skill Icons, Weather Icons), graphic style libraries eleven (including Game HUD, Status Effects and Neon & Glow) and brush libraries fourteen (Art Ribbons, Ink and Wash, Calligraphic Nibs, Pressure Sensitive, Bristle Brushes, Pattern Borders, Scatter Shapes, Stipple, Game Trails, Energy Beams, Dry Media, Tech Circuit, Engraving, Arrows) beside User Defined and Other Library… | +| **Bundled content:** brush, symbol, style and swatch libraries | ~46% | Ours are original and generated in code, and far fewer than Illustrator ships; symbol libraries have six (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons, Skill Icons, Weather Icons), graphic style libraries eleven (including Game HUD, Status Effects and Neon & Glow) and brush libraries fifteen (Art Ribbons, Ink and Wash, Calligraphic Nibs, Pressure Sensitive, Bristle Brushes, Pattern Borders, Decorative, Scatter Shapes, Stipple, Game Trails, Energy Beams, Dry Media, Tech Circuit, Engraving, Arrows) beside User Defined and Other Library… | | **Performance** | unverified | Multithreaded, off-thread rendering and caches are in place. The last budget run (2026-10-01, loaded machine) measured 290 ms for a 50k-path fit against a 16 ms budget. Re-run `vectorcraft-cli perf` on an idle machine | | **Robustness** | good, new | ~2,840 tests, property tests, no panics in shipped code (lints, the `guard` safety net, import fuzzing), Data Recovery. Missing: a corpus of real-world files, Windows/Linux/browser QA | | **Platforms and 1.0 polish** | ~60% | The macOS app and the web build work, and Finder opens every readable format with the macOS app (#295, #354); on macOS the menus are in the system menu bar, laid out as a Mac app's, with the in-window menus as a fallback (`--in-window-menus`; verified on Windows and by cross-compilation, not yet by hand on a Mac); hybrid-graphics laptops render on the power-saving GPU by default on Windows and macOS (#306), and Windows starts on Direct3D 12, falling back to OpenGL, and loads no Vulkan driver unless `WGPU_BACKEND` asks for it (#545: Vulkan flickered black on an Intel GPU, DX12 and OpenGL didn't; #806: a faulty Vulkan driver crashed the app before its window appeared; verified by unit tests and the reporter's runs with `WGPU_BACKEND`), and Linux on the GPU the desktop runs on, since a Wayland compositor may refuse frames from the other one; a window that fails on its GPU while starting up starts again on the next one instead of crashing (#502; the dual-GPU Wayland case is verified by unit tests and cross-compilation, not on such hardware); web drops land in the document they were dropped on (#359); desktop drops carry no pointer position (winit 0.30), so a dropped document opens as a tab of its own and a picture or text is placed in the middle of the view, while the web places anything dropped on the canvas and opens what is dropped off it, as Illustrator does (#472); a web page that loses its WebGPU device or WebGL context restarts its graphics with the same documents (#369); on Linux/Wayland the clipboard reads the compositor's own (data-control) and copied image files paste, but files can't be dropped on the window under native Wayland until eframe moves to winit 0.31 (#398; the Wayland side is verified by compilation only), so Preferences › Performance › Linux Display Server › X11 (XWayland) opens the window through XWayland, where drops work (#1151; verified by unit tests and cross-compilation, not on a Wayland desktop); on Linux the Paste menu checks the system clipboard on a background thread, so a clipboard owner that never answers no longer freezes the window, while Windows and macOS keep their quick in-line check (#510; the X11 hang verified by the contributor, here by headless tests); on KDE Plasma 6.3+ under Wayland, pens and pen displays reach the app only under XWayland (`WAYLAND_DISPLAY=`) or with KWin's `KWIN_WAYLAND_EMULATE_TABLET=1`, since winit 0.30 has no Wayland tablet input (#491, not verified on hardware); Windows/Linux packaging and accessibility are pending | @@ -626,9 +630,10 @@ since 2026-10-01. - **Blend redraw bounds (#5179):** renderer bounds include the reach of keys and steps rotated along a curved spine, so changed pixels remain inside the advertised redraw area. The original straight-blend control and curved Replace Spine, move and Undo regressions are in `crates/engine/tests/blend_render_consistency.rs`; both focused CPU cases pass. This is a redraw-bounds correction. Scores and hours unchanged. - **Guide row highlight (#7344):** `guide_row_highlight_stays_selected_without_hover` in `crates/ui-egui/src/panels/layers/tests.rs` checks selected guide background after the pointer leaves, with unselected guide and ordinary row controls. Guide selection, dragging and deletion are unchanged. Scores and estimates unchanged. +- **Trim View hides guides and the grid (#8363):** while View › Trim View is on, the canvas and tiled panes draw no ruler guides, no guide paths and no grid, the guides are neither snapped to nor picked, and Show/Hide Guides and Show/Hide Grid are greyed out (menu bar, canvas context menu, Properties) and refuse to run; the stored choices come back when it is turned off, and the rulers stay ([trim view hides guides](https://community.adobe.com/t5/illustrator-discussions/trim-view-hides-guides/td-p/14066140), [guides greyed out](https://community.adobe.com/t5/illustrator-discussions/guides-greyed-out/m-p/11132728)). A drag or double-click on a ruler makes no guide while it is on (no preview, no undo step, a status message). `trim_view_hides_the_guides_and_the_grid`, `trim_view_deselects_selected_guide_paths`, `trim_view_makes_no_guide_from_the_rulers` in `crates/ui-egui/src/canvas/tests.rs`; `trim_view_greys_out_show_guides_and_show_grid` in `crates/ui-egui/src/menus/tests.rs`. - **Recolor picker follow-up (#8031/#4028):** native Lab numeric entry, document/loaded-library swatches in the Color Picker, and Assign-row Pick from Swatches / Limit to Library menus. #4090 provided the double-click picker and #5113 the Assign sliders. Regression tests `native_lab_entry_in_color_picker` and `row_context_menu_pick_from_swatches_and_limit_to_library` exercise the fields and menu callbacks rather than writing their result state. Area score and hours unchanged. -- **Quick Pen tool (#2660, in part):** a tool in the Pen tool's group (Alt+P, Option+P on macOS) draws straight lines, continuous arcs and sharp-corner arcs, one undo step per piece; Alt pressed and let go on its own switches the action, C flips the last sharp-corner arc, `[` and `]` change the arc size by 15°, a click on the first point closes the path, a click on an open end continues it, and Escape or Enter ends it (`path.quickPen`), as [Draw with the Quick Pen tool](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/draw-with-quick-pen-tool.html) and [Quick Pen tool keyboard shortcuts](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/quick-pen-tool-keyboard-shortcuts.html) describe. The 180° default arc, its 15° steps and the side an arc bulges to are VectorCraft's own rules. Tests: tools `quickpen::tests`, engine `tests::quickpen`, ui-egui `shortcuts::alt_tap::tests` and `alt_p_chooses_the_quick_pen_and_an_alt_tap_switches_its_action`. Score and hours unchanged. +- **Quick Pen tool (#2660, in part):** a tool in the Pen tool's group (Alt+P, Option+P on macOS) draws straight lines, continuous arcs and sharp-corner arcs, one undo step per piece; Alt pressed and let go on its own switches the action, C flips the last sharp-corner arc, `[` and `]` change the arc size by 15°, a click on the first point closes the path, a click on an open end continues it, and Escape or Enter ends it (`path.quickPen`), as [Draw with the Quick Pen tool](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/draw-with-quick-pen-tool.html) and [Quick Pen tool keyboard shortcuts](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/quick-pen-tool-keyboard-shortcuts.html) describe. The 180° default arc, its 15° steps, the side an arc bulges to, a dragged piece ending where the press is let go, and C, `[` and `]` changing the arc being dragged are VectorCraft's own rules. Tests: tools `quickpen::tests`, engine `tests::quickpen`, ui-egui `shortcuts::alt_tap::tests`, `alt_p_chooses_the_quick_pen_and_an_alt_tap_switches_its_action` and `brackets_size_the_quick_pen_arc_being_dragged`. Score and hours unchanged. - **Optional compact Tools (#7234):** Window > Toolbars > Compact Tools reduces row and column spacing and the main panel's allocated width in one or two columns, docked or floating. The setting is saved with the UI state and applies to Basic, Advanced and edited main Tools layouts; the selected tool, icon size, footer controls and tool-flyout behavior are retained. Turning it off restores the existing layout, which remains the default. Named custom toolbars and flyout spacing are unchanged. Public regressions in `crates/ui-egui/tests/toolbar_compact.rs` cover the actual toolbar layout against the default control, the command and saved-state roundtrip, tool selection, flyouts, footer controls and short-window reachability. This is an optional layout choice, without a styling-parity or score claim; hours are unchanged. @@ -745,6 +750,7 @@ since 2026-10-01. - **Clipping paths on their outline (G1):** the selection tools (Selection, Direct Selection, Group Selection), Object Highlighting and a right-click take a clipping path on its outline before the art it clips; Select Behind lists the same; the eyedropper, the tools that act on what is drawn and the selection tools' double-clicks, loaded text and guide release take the art. Doc and tool regression tests; score unchanged. - **Link cursor for loaded text:** with text loaded from a port, the Selection tool's pointer adds a link badge over a closed path, area type or type on a path that a click threads the text into, and keeps the loaded text elsewhere; a click on a frame already in a thread or a path inside a compound path makes a new frame instead of a `text.thread.add` error (`select::tests::loaded_text_shows_the_link_cursor_where_a_click_threads_it_into_the_object`, `cursors::tests::loaded_text_link_cursor_is_the_loaded_text_with_a_link_badge`); score unchanged. - **Copy and Cut of anchors picked with a lent Direct Selection (#6123):** with the Pen or the Curvature tool, Cmd/Ctrl held lends Direct Selection for the gesture; the anchors and segments it picks are what Edit › Copy and Cut take once the key is let go, as with Direct Selection chosen, while the last anchor the Pen leaves selected as it draws still makes Copy take the whole path (#2122). A Cmd gesture that leaves the selection as it was (a Shift marquee over nothing) picks nothing. Regression test: `tests::draw2::pen_cmd_selected_anchors_are_what_copy_and_cut_take`. +- **Mirrored handles in a Direct Selection drag (#7842):** Cmd/Ctrl added after a handle drag begins puts the anchor's other handle opposite the dragged one at the same length, on paths, type on a path and blend spines, and the anchor keeps its kind; Shift constrains the dragged handle first, and Alt keeps the handles independent. At an open end, where no segment leaves the anchor on the other side, the handle moves as it does without Cmd/Ctrl. When Cmd/Ctrl lends Direct Selection for the gesture while another tool, such as the Pen, is chosen, that press does not mirror; letting it go and pressing it again during the drag does. This is VectorCraft's own behavior. Regression tests: `crates/engine/tests/direct_handle_mirror.rs`. - **Cut of picked anchors (#6361):** Edit › Cut removes direct-selected anchors from their path and from a compound path's member, with the segments attached to them, as Clear does. Picked segments still lose only those segments. When a path also has a picked segment, Cut removes and copies only its picked segments and ignores its picked anchors, on every contour, as Clear does; an anchor left without a surviving segment is removed with them. Regression tests: `cut_*_anchors_*` and `cut_of_an_anchor_with_a_segment_on_another_contour_leaves_the_source_as_clear_does` in `crates/engine/tests/it/copy_direct_selection.rs`. - **Escape in Selection tool drags:** Escape during a Selection tool move or Alt-drag copy, a bounding-box scale or rotation, a marquee, or a corner widget, pie widget or bracket drag cancels it: the art returns to its state at the press, no copy is left, no undo step is added, the release does nothing, and the tool stays chosen. This is VectorCraft's own behavior. Regression tests: `escape_cancels_*` in `select/tests.rs` and `pie.rs`, and `escape_cancels_a_selection_tool_move_copy_scale_or_rotation` in `tests/selectescape.rs`. - **Large Shift-marquee selections and Select › Inverse:** `select.toggle` and `select.add` with many ids (a Shift-drag marquee sends them together) go through the selection once instead of once per id, and Select › Inverse looks each object up in a set of the selected ones. The resulting selection, its order and the reply are the same as before. With 50,000 objects the selection step of toggling every object off took 528 to 655 ms before and 2.5 to 4.6 ms after in 7 runs, wall clock on a machine that was running other builds (`cargo run --release -p vectorcraft-engine --example selection_bench`). Regression tests: `add_all_does_what_adding_each_does` and `toggle_all_does_what_toggling_each_does` in `crates/doc/src/selection/tests.rs`, and `toggle_and_add_handle_each_listed_id_in_order` in `crates/engine/tests/it/selection_commands.rs`. @@ -869,6 +875,9 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Preferences › General describes its settings:** the line under the Preferences fields shows a sentence for each of the 32 General settings, Enable Contextual Task Bar included, when the pointer is over the setting's row or its control has the keyboard focus, and a screen reader gets the same sentence. The sentences are VectorCraft's own and state what the app does with each setting. Sentences: `crates/ui-egui/src/prefs_dialog/descriptions.rs`. Tests: `crates/ui-egui/src/prefs_dialog/tests.rs`. - **Preferences › Selection & Anchor Display describes its settings:** the line under the Preferences fields shows a sentence for each of the 14 Selection & Anchor Display settings, from Tolerance to the Curvature Tool rubber band, on hover and on keyboard focus, and a screen reader gets the same sentence. The Snap to Point sentence states that the Smart Guides Snapping Tolerance applies while Smart Guides is on. Sentences: `crates/ui-egui/src/prefs_dialog/descriptions.rs`. Tests: `crates/ui-egui/src/prefs_dialog/tests.rs`. - **Preferences › Guides & Grid describes its settings:** the line under the Preferences fields shows a sentence for each of the 12 Guides & Grid settings, from Snap to Grid to Pattern Editing's Tile Edge Color, on hover and on keyboard focus, and a screen reader gets the same sentence. The Show Pixel Grid sentence states that the pixel grid shows from 600% zoom. Sentences: `crates/ui-egui/src/prefs_dialog/descriptions.rs`. Tests: `crates/ui-egui/src/prefs_dialog/tests.rs`. +- **Preferences › Plug-ins & Scratch Disks describes its settings:** the line under the Preferences fields shows a sentence for Additional Plug-ins Folder, Plug-in Instruction Budget, Primary and Secondary on hover and on keyboard focus, and a screen reader gets the same sentence. The sentences state VectorCraft's own behavior: on the desktop the folder's `.wasm` plug-ins load at startup and when OK sets a new folder, except in Safe Mode, and the web version does not load them; the larger Plug-in Instruction Budget gives each object filter run five times the base instructions with the same allowance for each byte of input, and heavy filters, live effects, exporters and importers keep their own limits; Primary and Secondary take Startup, None or a folder path and are stored, but no scratch disk is used yet (G12 stays open). Sentences: `crates/ui-egui/src/prefs_dialog/descriptions.rs`. Tests: `crates/ui-egui/src/prefs_dialog/tests.rs`. +- **Preferences › User Interface describes its settings:** the line under the Preferences fields shows a sentence for each of the 13 User Interface settings, from Brightness to Language, System Title Bar and VectorCraft Title Bar on Every Desktop included where the platform shows them, on hover and on keyboard focus, and a screen reader gets the same sentence. The sentences state VectorCraft's own behavior: Accent Color is dimmed while the color scheme has its own accent; Outline view shows the canvas white whatever Canvas Color says; with Auto-Collapse Iconic Panels on, a panel opened from its icon closes on Esc or a click outside it; Open Documents As Tabs applies to documents opened or created afterwards; both title bar settings apply from the next start; UI Scaling leaves the size of art at a given zoom alone; Scale Cursor Proportional to UI sizes only the pointers VectorCraft draws; the dialog shows a chosen language before OK. Sentences: `crates/ui-egui/src/prefs_dialog/descriptions.rs`. Tests: `crates/ui-egui/src/prefs_dialog/tests.rs`. +- **Preferences › Performance describes its settings:** the line under the Preferences fields shows a sentence for each of the 8 Performance settings, from GPU Performance to Use Monitor Profile for Canvas, Linux Display Server included on Linux, on hover and on keyboard focus, and a screen reader gets the same sentence. The sentences state VectorCraft's own behavior: GPU Performance only allows Animated Zoom; Animated Zoom makes wheel zooms glide and the Zoom tool zoom as it is dragged or held; Graphics Processor applies to the desktop version from the next start, and Automatic prefers the processor that drives the display; History States caps each document's undo steps, and the memory budget can drop older steps sooner; with Real-time Drawing and Editing off, outlines follow a drag and the art changes on release, while a ruler guide still moves; Render Threads sets the canvas rasterizer's workers, and the web version uses none; Linux Display Server's X11 choice always uses XWayland on a Wayland desktop and the others only with a pen attached; Use Monitor Profile for Canvas converts the canvas to the display's profile unless the system does so, and off draws it in sRGB. Units, General, Selection & Anchor Display, Guides & Grid, Smart Guides, Slices, Hyphenation, Plug-ins & Scratch Disks, User Interface, Performance and Type have sentences, and the other categories leave the line empty. Sentences: `crates/ui-egui/src/prefs_dialog/descriptions.rs`. Tests: `crates/ui-egui/src/prefs_dialog/tests.rs`. - **Preferences › Hyphenation describes its settings:** the line under the Preferences fields shows a sentence for Default Language and for Exceptions (comma separated) on hover and on keyboard focus, and a screen reader gets the same sentence. The sentences state VectorCraft's own behavior: new type takes the Default Language while Document Setup's language is English: USA and [Normal Character Style] sets no language, and type already in a document keeps its own; in paragraphs with Hyphenate on, a listed word breaks only at the hyphens typed in it, or nowhere without one, in any case, except that Korean words take no hyphen and Indian-language words do not break inside a character cluster. Units, General, Selection & Anchor Display, Guides & Grid, Smart Guides, Slices, Hyphenation and Type have sentences, and the other categories leave the line empty. Sentences: `crates/ui-egui/src/prefs_dialog/descriptions.rs`. Tests: `crates/ui-egui/src/prefs_dialog/tests.rs`. - **Preferences › Smart Guides describes its settings:** the line under the Preferences fields shows a sentence for the Smart Guides box and for each of the 14 Smart Guides settings, from Color to Snap to Perpendicular, on hover and on keyboard focus, and a screen reader gets the same sentence. The sentences state VectorCraft's own behavior: Pixel Preview turns Smart Guides off and Snap to Grid snaps instead; with Alignment Guides off, art still lines up without the line; Object Highlighting outlines only an unselected object while a selection tool is not dragging; Snapping Tolerance is a distance on screen at every zoom; Snap to Last Location does not return a copy. Units, General, Selection & Anchor Display, Guides & Grid, Smart Guides, Slices, Hyphenation and Type have sentences, and the other categories leave the line empty. Sentences: `crates/ui-egui/src/prefs_dialog/descriptions.rs`. Tests: `crates/ui-egui/src/prefs_dialog/tests.rs`. - **Preferences › Slices describes its settings:** the line under the Preferences fields shows a sentence for Show Slice Numbers and for Line Color on hover and on keyboard focus, and a screen reader gets the same sentence. The sentences state VectorCraft's own behavior: each slice's number shows in a box at its top left on the canvas, the slice outlines still show with numbers off, and auto slices use a dimmer shade of the line color. Units, General, Selection & Anchor Display, Guides & Grid, Smart Guides, Slices, Hyphenation and Type have sentences, and the other categories leave the line empty. Sentences: `crates/ui-egui/src/prefs_dialog/descriptions.rs`. Tests: `crates/ui-egui/src/prefs_dialog/tests.rs`. @@ -1074,6 +1083,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The contextual task bar offers more next steps by selection (): an open path Join and Edit Path (the Direct Selection tool), a closed path Edit Path, a compound path Edit Path and Release Compound Path, a clipping group Edit Clipping Path and Release Clipping Mask instead of Ungroup and Isolate, an image selected with vector art Make Clipping Mask instead of Unite, point or area type Convert To Area Type or Convert To Point Type beside Create Outlines, and type on a path, for which the overview names an item to add an effect and rearrange the text, Type on a Path Options (`type.pathOptions`; its options: ) beside Create Outlines. Evidence: `crates/ui-egui/src/tests/taskbar.rs`. - While a Type tool (Type, Area Type, Type on a Path and their vertical versions) adds or edits type, the contextual task bar shows the font family menu, the font style menu, the Font Size combo and the Fill chip (); the Touch Type tool shows no bar, as the same page describes. Type selected with a selection tool shows the same three font controls beside its Create Outlines, conversion and Type on a Path items (). The controls act as the Character panel's do: on the characters a Type tool selects, else on every selected type object, with the size left blank where the sizes differ. VectorCraft's own rules: a Type tool's bar leaves out the object actions, the Stroke chip, Recolor Artwork and Lock; a Type tool shows no bar before it adds type or with other art selected; type selected with other art shows no font controls; the font controls go on a second row when one row would be wider than the canvas, and narrow to fit a canvas narrower than they are; while a Type tool edits type, the Fill chip shows the edited characters' fill ("?" where it differs). Evidence: `the_type_tools_show_font_and_fill_controls`, `the_type_tools_show_no_bar_without_type`, `selected_type_shows_font_controls_beside_its_actions`, `the_task_bars_font_size_sets_what_the_character_panel_would`, `the_type_tools_fill_chip_activates_the_fill`, `the_type_tools_bar_is_named_and_stays_on_the_canvas`, `selected_types_font_controls_take_a_second_row_on_a_narrow_canvas` and `the_type_tools_fill_chip_shows_the_edited_characters_fill` in `crates/ui-egui/src/tests/taskbar.rs`. - The help page describes the contextual task bar as one horizontal row () and gives no rule for a canvas narrower than that row. VectorCraft's own rule: the bar stays whole on the canvas. When its actions don't fit in one row, they wrap, in order, onto rows under the row with the handle, the chips and More Options; an action wider than any row, or one that would need a row past the canvas's height, is listed in More Options instead; when the chips don't fit beside the handle and More Options, they take rows after the actions; with no row to spare for the font controls, the bar leaves them out; a canvas too small for the handle and More Options shows no bar. Evidence: `a_task_bars_actions_wrap_on_a_narrow_canvas` and `a_task_bar_action_wider_than_the_canvas_goes_in_more_options` in `crates/ui-egui/src/tests/taskbar.rs`. + - The contextual task bar's More Options menu has Bar Actions, which lists the actions and the Fill, Stroke, Recolor Artwork, Lock or Shape Properties chips the bar offers for the current selection or tool, each checked while it is on, and Reset Bar Actions, which turns every one on again (`window.taskBar.actions`, `window.taskBar.resetActions`). An action that is off stays out of the bar and out of More Options wherever the bar would offer it; turning one off changes only the bar. With all of them off, the bar still shows its handle and More Options. The type font controls are not in Bar Actions. Which actions are off is kept with the preferences and with the workspace. Choosing the bar's actions is VectorCraft's own. Evidence: `an_action_turned_off_leaves_the_bar_and_stays_in_its_menu`, `an_action_turned_off_is_not_listed_in_more_options`, `every_action_the_bar_offers_can_be_turned_off`, `a_chip_turned_off_leaves_the_bar`, `reset_bar_actions_shows_every_action_again`, `bar_actions_are_kept_with_the_preferences`, `bar_actions_list_names_without_a_colon_or_an_ellipsis` and `more_options_bar_actions_turns_an_action_off_and_on` in `crates/ui-egui/src/tests/taskbar.rs`, and `saved_workspaces_restore_the_task_bar_actions` in `crates/ui-egui/src/workspaces.rs`. - With a live rectangle, rounded rectangle, ellipse or polygon selected with the Selection tool, the contextual task bar shows a Shape Properties button in place of Lock. It opens a popup with the shape's rows from the Transform panel (corner radius, pie angles, or sides, angle, corner and radius), which edit it through `object.setLiveShape`. The overview describes this: when a shape drawn with a shape tool (Rectangle, Star) is selected, the bar offers to change its properties where Lock Object would be ([Contextual Task Bar overview](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/contextual-task-bar-overview.html)). Object › Lock and ⌘2 still lock the shape. Not done: stars, which the app draws as plain paths. Evidence: `a_basic_shape_shows_its_properties_in_place_of_lock`, `the_shape_properties_popup_edits_the_shape` and `other_selections_keep_lock` in `crates/ui-egui/src/tests/taskbar.rs`. - Rectangle Properties and Ellipse Properties in the Transform panel, the Properties panel and the task bar's Shape Properties popup have an Angle field, as Polygon Properties does: the help page lists Rectangle Angle and Ellipse Angle as the shape's rotation on the canvas from 0° to 360° (). A typed angle turns the shape through `object.setLiveShape {rectangleAngle, ellipseAngle}`. VectorCraft's own rules: degrees counterclockwise, 0 for a shape drawn level; each selected shape of that kind turns about its own center and keeps its size, corners and pie; the field is blank when the selected shapes of that kind differ, as the Polygon Properties angle now is too; the shape keeps its angle after Reset Bounding Box squares the Rotate field's box to the page; the angle a shape already has records no undo step. Evidence: `a_rectangle_and_an_ellipse_take_their_angle` in `crates/engine/src/tests/livecorners.rs` and `a_rectangle_and_an_ellipse_show_their_angle` in `crates/ui-egui/src/panels/transform/tests.rs`. - While the Rectangle, Rounded Rectangle, Ellipse, Polygon or Star tool is in use, the contextual task bar offers Edit Path (the Direct Selection tool), the Fill and Stroke chips, and Shape Properties for the shape it draws, as the help page lists for those five tools (). VectorCraft's own rules: the bar shows while one of those tools has one closed path selected whole, as right after it draws one, and not with nothing selected, several objects, a group, an open path, type or picked-out anchors; it shows nothing during the drag that draws the shape; it leaves out the selection tools' Duplicate, Offset Path, Simplify, Recolor Artwork and Lock; the Line Segment tool shows no bar. Not done: Shape Properties for a star, which the app draws as a plain path, and Gen Shape Fill and Generate Vectors, which the app doesn't have. Evidence: `shape_tools_show_edit_path_paint_and_properties_after_drawing`, `shape_tools_have_no_shape_bar_without_a_single_shape` and `shape_tool_bar_retargets_after_another_shape_and_undo` in `crates/ui-egui/src/tests/taskbar.rs`. @@ -1169,10 +1179,12 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - After a rotation the Scale and Reflect tools, the Scale and Reflect dialogs, `object.scale`, `object.reflect` with a named axis and the Transform and Properties panels' flips act along the selection's turned bounding box until Reset Bounding Box: the horizontal and vertical scale stretch along its own width and height, and the vertical and horizontal reflection axes are its own. The Reflect tool's default axis and its Shift steps start from the box's axes, and an axis drawn with the tool is the line drawn on the page. `basis: "page"` keeps the page's axes (VectorCraft's own rules; `bboxrotate::scale_and_reflect_follow_the_turned_box`, tools `xform::transform::tests::scale_and_reflect_drags_follow_a_turned_bounding_box`). - The Reflect tool sets an axis with two clicks: a click sets the first point (and the reference point), and a second click reflects the selection across the line through both points as one undo step; Alt/Option on the second click reflects a copy, and a drag after the first click draws the axis from it ([the help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/reflect-or-flip-objects.html)). A dashed line runs from the first point to the pointer until the second click. VectorCraft's own rules: an Alt-click opens the dialog and sets no axis; a second click whose snapped point is within 3 screen pixels of the first point's snapped point does nothing and the axis keeps waiting; Shift does not constrain a plain second click; Escape, Enter, a changed selection, an edit made outside the tool or another tool drops the waiting axis. A double-click arrives as two clicks: its first click is the second point, so a double-click away from the first point reflects the selection, and the double-click then opens the dialog with no axis waiting (tools `xform::transform::tests::a_second_reflect_click_reflects_across_the_line_through_both_points` and the four tests after it; engine `xform::two_reflect_clicks_reflect_across_their_line_as_one_undo_step`). - Perspective Distort and Free Distort (`object.distort`) turn each warped object's bounding box as the warp turns the object at its own center, the objects inside groups, compound paths and clip groups and the art of linked opacity masks included, so the next Selection or Free Transform drag uses the tilted box; Object › Transform › Reset Bounding Box squares it again, and corners left where they are add no undo step (VectorCraft's own rule; `bboxrotate::distort_turns_an_upright_box_with_the_warp_at_its_center`, `distort_turns_each_member_and_linked_mask_by_its_own_warp`, `mirrored_and_collapsing_distorts_keep_valid_angles`, `distort_angles_undo_redo_and_reopen_together`, `xform::unchanged_distort_records_no_history`). + - Perspective Distort and Free Distort (`object.distort`) move an image's four corners exactly onto the handles when the image is distorted alone; with other objects the handles stand for the whole selection, and the image's corners follow the same warp without necessarily landing on them. The image's pixels are drawn in perspective between its corners on the canvas, in print and in every export that holds images, as a mesh of affine image pieces (DXF and WMF write the nearest parallelogram and warn; HP-GL plots leave images out); the native file saves the corners; bounds, clicks, blends, the Eyedropper, Outline view, the Color Theme Picker and Weed Box and Lines follow them; Image info and Link Info measure the image at its middle; and corners that would fold the image over, fall on one line, cross the warp's horizon or lie too close together for a perspective map are refused. Crop Image, Image Trace, Relink, Embed, Unembed, Create Object Mosaic, Create Gradient Mesh and Place with Replace refuse a distorted image (Place with Replace refuses only when the object it measures is the distorted image, so it does not refuse when the placed file is text or the replaced object is a DCS file's plates); Update Links puts a changed file's pixels between its corners; Rasterize makes a plain image of it. All of this is VectorCraft's own rule (doc `image_quad::tests`, `blend::tests::steps_between_distorted_images_have_corners_between_theirs`; engine `xform::distort_puts_an_images_corners_on_the_handles`, `distort_moves_an_image_and_a_path_as_one`, `distort_refuses_a_folded_image_and_crop_and_trace_refuse_a_distorted_one`, `distort_names_the_horizon_and_an_unchanged_distort_of_a_distorted_image_records_nothing`, `distort_of_a_blend_holding_an_image_is_not_refused`, `free_transform_distort_drag_on_an_image_is_one_undo_step`, `mask_on_a_distorted_image_follows_its_corners`, `a_transform_effect_moves_a_distorted_images_corners`, `a_transform_after_a_warp_moves_a_distorted_image_once`, `baked_raster_effect_pixels_replace_a_distortion`, `rasterize_draws_a_distorted_image_between_its_corners`, `image_info_measures_a_distorted_image_at_its_middle`, `a_distorted_image_saves_and_reads_back`, `links::update_links_keeps_a_distorted_images_corners`, `recolor::theme_picker_reads_a_distorted_image_where_it_is_drawn`, `addons::cutting::weed::tests::a_distorted_image_is_measured_by_the_frame_through_its_corners`; render `outline_mode_draws_a_distorted_images_frame_through_its_corners`, `meshwarp::outline_mode_paints_a_distorted_images_pixels_once_where_its_pieces_overlap`, `meshwarp::the_canvas_cuts_a_distorted_images_mesh_for_the_zoom`, `objectfx::a_distorted_image_is_opaque_between_its_corners_and_its_shadow_follows_them`, `objectfx::a_distorted_image_is_opaque_inside_its_corners_at_every_zoom`; svg `warp_pieces::a_distorted_image_is_written_between_its_corners`; pdf `compression::a_distorted_image_is_written_with_its_corners_on_its_quad`; eps `a_distorted_image_is_written_with_its_corners_on_its_quad`; cad `a_distorted_image_is_written_as_its_nearest_parallelogram_with_a_warning`; metafile `a_distorted_image_is_its_mesh_with_clips_and_its_nearest_parallelogram_without`; tools `xform::eyedropper::tests::clicking_an_image_samples_its_pixels`; plugins `objects::tests::a_distorted_image_comes_with_its_corners`; ui-egui `i18n::tests::distorted_image_messages_are_in_complete_catalogs`). - The Free Transform widget's Constrain works in Free Distort as well as in Free Transform ([the help page](https://helpx.adobe.com/illustrator/using/tool-techniques/free-transform-tool.html)). With Constrain on, or Shift held, a corner dragged in Free Distort moves only along the line through the opposite corner, in the box's own proportions, and the other three corners stay in place; on a turned box the line runs through the box's own corners. The line is VectorCraft's own rule. Cmd/Ctrl+Alt+Shift on a corner still drags in Perspective Distort, where Constrain stays unavailable (tools `xform::free::tests::free_distort_corner_keeps_to_its_diagonal_with_shift_or_constrain`, `shift_pressed_during_a_free_distort_drag_constrains_it`, `a_turned_box_is_constrained_along_its_own_diagonal`, `along_diagonal_of_a_degenerate_box`; engine `xform::free_transform_constrained_distort_keeps_the_corner_on_its_diagonal`; ui-egui `free_transform::tests::the_widget_sets_the_mode_and_a_corner_drag_then_distorts`). - With Smart Guides › Transform Tools on, a Free Transform shear (Cmd/Ctrl on a side handle) shows its angle next to the pointer, as the Shear tool does, and a handle drag that turns from a scale into a shear and back shows only the current operation's value ([the help page](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/smart-guides-options.html)). The angle's sign and its one decimal place are VectorCraft's own rule, the same as the Shear tool's label (tools `xform::free::tests::shear_drag_shows_its_angle_with_transform_tools_guides`, `a_handle_drag_that_changes_operation_relabels_it`). - Native macOS menu bar, vector tool cursors, a command palette (Help › Search Commands…), middle-button panning with any tool. Native menus explicitly end tracking on command selection, outside window presses and Escape; menu updates wait until tracking ends, and a dismissing press never starts a canvas gesture (M14.8). - Help › Search Commands… is the first item of the Help menu in the window, with its shortcut and a separator after it; in the native macOS menu bar it is the first item below the system's search field. This is VectorCraft's own order and does not raise a score (`menus::tests::help_starts_with_search_commands`, `tests::nativemenu::the_mac_help_menu_starts_with_search_commands`). + - Clear Recent Commands (`help.clearRecentCommands`), found through Help › Search Commands…, empties the Recent Commands list, the list an empty search shows, the saved list and the pick counts that rank the results. A pick of it is not kept as a recent pick or counted, and it is enabled while a pick or a count is saved. This is VectorCraft's own behavior (`palette` tests `clear_recent_commands_empties_the_recent_picks`, `clear_recent_commands_also_clears_the_pick_counts`). - A Recent Commands button beside the Help › Search Commands field lists the last eight commands, tools, panels and effects picked from the palette, most recent first, with a command picked again moved to the top. A pick is recorded when it runs or opens a dialog, even if the dialog is then canceled; a pick that is refused because its menu item is dimmed, its tool can't be chosen or its panel can't be shown is not recorded, unless it opened a dialog. Choosing a row closes the palette and runs it as a pick of the same result does; with no picks yet the list shows a dimmed No recent commands row, and a command that is not available now, such as a filter of a plug-in that is not loaded, is left out until it comes back. The ids are saved with the UI state. While the list is open, Up and Down move through its rows, wrapping at the ends, and Escape closes the list before the palette. This is VectorCraft's own addition and does not raise a score (#6376; `palette` tests `recent_commands_*`, `a_recent_command_runs_what_its_pick_runs`, `the_keys_wrap_within_recent_commands`, `escape_closes_recent_commands_before_the_palette`). - With an empty search, or one of spaces only, the Help › Search Commands field lists the picks of the Recent Commands list (at most eight, leaving out a filter of a plug-in that is not loaded) under a Recent heading, most recent first, with the first highlighted and no result count, so opening the palette and pressing Enter picks the last pick again; when no callout can point at the highlighted pick's home, the line under the list still says where it is. A pick that is dimmed now shows why in the status line, as from a search, and keeps its place in the list. With no picks yet it lists no results and shows a dimmed Type to search commands, tools, panels and effects line. A pick of Search Commands… itself is not recorded. The palette opens with its first result highlighted and its list scrolled to the top. This is VectorCraft's own behavior (`palette` tests `an_empty_search_lists_the_recent_picks_most_recent_first`, `an_empty_search_without_picks_says_what_to_type`, `enter_on_an_empty_search_runs_the_last_pick_again`, `the_palette_opens_again_with_its_first_row_highlighted`, `the_palette_toggle_is_not_a_recent_pick`, `a_click_on_a_recent_pick_runs_it_and_moves_it_first`, `a_pick_says_whether_it_ran_opened_a_dialog_or_was_refused`, `a_refused_pick_is_not_recorded`, `a_pick_that_opens_a_dialog_is_recorded_even_when_canceled`, `under_the_recent_picks_the_footer_names_a_home_out_of_view`). - The app bar's search control is a field showing a magnifier, "Search commands" and the Help › Search Commands… shortcut. The field shows no shortcut when the shortcut is cleared or too long to fit beside the text; the tooltip and the screen-reader name still give it. A click on the field, or Enter or Space while it has the keyboard focus, toggles the command palette as the shortcut does, and the palette's popup holds the text field. While the field has the focus, the app's existing rule for a focused control keeps the app's own keys off, so Enter does not open Move and Tab moves the focus on. While a dialog is open the field and the icon are drawn disabled and do nothing, as the shortcut does. Screen readers name the field and the icon Search commands, with the shortcut. As the bar narrows, the community button goes first, then Explore tutorials, then the field becomes the magnifier icon, then the workspace switcher narrows to 64 points, then the icon goes; Safe Mode's label keeps its room first. The field is wider than the icon, so the community button and Explore tutorials go at wider bars than they did beside the icon. This is VectorCraft's own addition and does not raise a score (`chrome::tests`: `the_app_bar_gives_up_its_right_hand_controls_in_order`, `a_wide_app_bar_shows_a_search_field_with_the_palette_shortcut`, `the_search_field_follows_the_palettes_shortcut`, `a_long_shortcut_leaves_the_search_hint_readable`, `a_click_on_the_search_field_opens_the_palette`, `the_search_icon_has_the_fields_name_and_both_are_disabled_under_a_dialog`, `the_keyboard_opens_the_palette_from_the_search_field`, `a_narrowing_app_bar_turns_the_search_field_into_the_icon`). @@ -1228,17 +1240,21 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **The Symbols panel reads its current symbol from the document:** the Symbols panel and its panel menu read the current symbol on each frame without running `symbol.list`, which counts every symbol's instances by walking the whole document. The current symbol they show and act on is the one `symbol.list` reports, and an idle frame of the panel or its menu runs no command, so on macOS the native menu is not brought up to date on every frame while the panel is open. In a document with 200 symbols and 50,000 objects, the read takes 0.035 µs instead of 48.5 ms in a release build (thread CPU time on Linux, median of 7 runs); in a small document the difference is too small to notice. Tests: `tests::brushsym::current_symbol_is_the_current_symbol_list_answers`, `panels::symbols::tests::current_is_the_current_symbol_list_answers`, `panels::symbols::tests::idle_frames_of_the_panel_and_its_menu_run_no_command`; the timing probe is `panels::symbols::tests::current_symbol_read_timing`. - **Expand of symbol instances:** Object › Expand turns selected symbol instances (without effects, not in perspective, in groups or placed documents too) into their art as Break Link to Symbol places it, one level deep, as one undo step; the Expand dialog's Fill and Stroke reach that art (`object.expand`, `crates/engine/src/tests/expand_symbols.rs`; estimated, score unchanged). - **Reset Transformation** ([Transform symbols](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/transform-symbols.html), [Symbols panel options](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html)): the Symbols panel menu's Reset Transformation and the Control bar's Reset, shown while symbol instances are selected, give the selected instances their symbol's own scale again, without rotation or shear, as one undo step (`symbol.instance.resetTransform`); an instance in perspective is left as it is. VectorCraft's own rules: each instance keeps the center of its bounding box in place, reflection is removed too, and the menu item and the button are enabled only while a selected instance would change. Tests: `tests::brushsym::reset_transformation_restores_the_symbols_scale_and_keeps_the_center`, `reset_transformation_keeps_the_center_of_art_away_from_the_origin`, `reset_transformation_ignores_a_stored_size_that_is_not_positive`, `reset_transformation_leaves_unchanged_instances_and_refuses_bad_ids`, `panels::symbols::tests::reset_transformation_is_enabled_for_a_transformed_instance_and_resets_it`. - - **Symbolism Tools Options** ([Symbolism tool options](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbolism-tool-options.html), [the archived manual](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=118)): the dialog a double-click on a symbolism tool opens has, besides Diameter, Intensity and Symbol Set Density, Use Pressure Pen (a pen's pressure is the intensity), Method (User Defined, Average or Random) for the Scruncher, Sizer, Spinner, Stainer, Screener and Styler, Show Brush Size and Intensity, the Symbol Sprayer's Scrunch, Size, Spin, Screen, Stain and Style (each Average or User Defined), and the Symbol Sizer's Proportional Resizing and Resizing Affects Density; a new Symbol Set Density spaces the instances of the selected symbol sets (`symbol.setDensity`). VectorCraft's own rules: a Tool row lists the eight tools by name and shows the chosen one's options; Random gives each instance its own share of the change for the whole stroke; Average moves each value toward the mean of the instances under the brush; the starting values are Method User Defined, the Sprayer's six options Average, Proportional Resizing on and Resizing Affects Density off, so only a Sprayer stroke over instances of the selected set changes from before (its new instances take their mean values); the brush shows the intensity as a dashed ring. The Symbol Sprayer does not use Intensity or pen pressure. Tests: `crates/engine/src/tests/symbolism_options.rs`, `symbolism::tests` in `crates/tools`, `dialogs::symbolism_options::tests`. + - **Symbolism Tools Options** ([Symbolism tool options](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbolism-tool-options.html), [the archived manual](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=118)): the dialog a double-click on a symbolism tool opens has, besides Diameter, Intensity and Symbol Set Density, Use Pressure Pen (a pen's pressure is the intensity), Method (User Defined, Average or Random) for the Scruncher, Sizer, Spinner, Stainer, Screener and Styler, Show Brush Size and Intensity, the Symbol Sprayer's Scrunch, Size, Spin, Screen, Stain and Style (each Average or User Defined), and the Symbol Sizer's Proportional Resizing and Resizing Affects Density; a new Symbol Set Density spaces the instances of the selected symbol sets (`symbol.setDensity`). VectorCraft's own rules: a Tool row lists the eight tools by name and shows the chosen one's options; Random gives each instance its own share of the change for the whole stroke; Average moves each value toward the mean of the instances under the brush; the starting values are Method User Defined, the Sprayer's six options Average, Proportional Resizing on and Resizing Affects Density off; with them, two strokes change from before: a Sprayer stroke over instances of the selected set gives its new instances their mean values, and the Symbol Styler applies the style by the brush's strength, so a click at the brush's center at the default intensity 5 applies it at half opacity instead of in full, and a stroke's samples add up; the brush shows the intensity as a dashed ring. The Symbol Sprayer does not use Intensity or pen pressure. Tests: `crates/engine/src/tests/symbolism_options.rs`, `symbolism::tests` in `crates/tools`, `dialogs::symbolism_options::tests`. + - **Symbolism tools with Shift** ([the manual](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=199), [the CS6 reference](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=136)): a Shift-click with the Symbol Shifter brings the instances under the brush forward in the stacking order and Alt+Shift-click sends them backward; the Symbol Sizer with Shift keeps the set's density while it resizes; the Symbol Stainer and the Symbol Styler with Shift keep the amount of stain or style and move the color or style toward the current fill or the selected style (`symbol.adjust {shift}`). VectorCraft's own rules: the Shifter moves each instance one place among its siblings, once per stroke, without moving it on the canvas; the Sizer keeps each instance's center, even with Resizing Affects Density; a stain or style with no form between it and the new paint (a solid color and a pattern) takes the new paint at once; an instance without a stain or style is left as it is, and Alt has no effect on the Stainer or the Styler with Shift. The selected style is the one last clicked into the Graphic Styles panel's selection. Tests: `crates/engine/src/tests/symbolism_shift.rs`, `symbolism::tests::shift_reaches_the_tools_that_have_a_shift_form`, `panels::graphic_styles::tests::shift_click_selects_a_range_and_cmd_click_adds_or_removes_one_style`. - **The Symbols and Properties panels find selected symbol instances once per revision:** whether the selection or its groups hold a symbol instance (Break Link to Symbol), one with appearance changes of its own (Reset Symbol Instance and the Properties panel's Reset), or one Reset Transformation would change is worked out in one walk of the selected objects for each document revision, and later frames reuse it. The buttons and menu items are enabled as before. With one selected group of 300,000 paths, the two panels' reads took a median 5.1 to 5.7 ms of thread CPU time per frame; the first read after a change now takes about 3 ms and later frames about 5 ns (Linux, opt-level 3, median of 7 runs). In a small document the difference is too small to notice. Tests: `panels::symbols::tests::instance_flags_are_found_once_per_revision_and_match_a_walk_of_the_selection`, `properties_and_symbols_panels_walk_the_selection_once_per_revision`. - **Expand of dimensions:** Object › Expand, Expand Appearance, Create Outlines and Outline Stroke turn a dimension whose art they change into a plain group of that art, which stays as it is through later moves, scales and edits of what it measured; undo gives the live dimension back (`crates/engine/tests/it/dimensions.rs`; VectorCraft's own rule; estimated, score unchanged). - **Brush libraries** ([public source](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/create-new-brush-libraries.html), [import](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/import-brushes-from-brush-libraries-or-other-files.html), [Brushes panel](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/brushes-panel-overview.html)): Window › Brush Libraries, the Brushes panel's Brush Libraries Menu and its menu's Open Brush Library open each library in a library panel of its own, as swatch, graphic style and symbol libraries do. The built-in libraries (Art Ribbons, Ink and Wash, Calligraphic Nibs, Pressure Sensitive, Bristle Brushes, Pattern Borders, Scatter Shapes, Stipple, Game Trails, Energy Beams, Dry Media, Tech Circuit, Engraving, Arrows) are original brushes generated in code (`crates/engine/src/cmd/brushlib.rs`); Striped Ribbon's art is filled with the library's own pattern and Sparkles scatters the library's own symbol; Ink and Wash adds ink and wash brushes (the [help page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html) lists an Ink brush library of strokes with varied thickness and texture; the names, shapes and opacities are VectorCraft's own): Tapered Ink, an art brush broad near its start that thins to a fine tip; Brush Pen, a calligraphic brush whose size follows the pen pressure; and Soft Wash and Pooling Wash, art brushes of translucent gray layers that take the stroke color as tints; Game Trails adds motion art brushes (Speed Line, Dash Trail, Burst Ray, Zigzag); Energy Beams adds laser and plasma art brushes (Laser Bolt, Plasma Arc, Charge Wave, Spark Trail); Dry Media adds grainy art brushes (Chalk Grain, Graphite Pencil, Wax Crayon, Charcoal Dust); Engraving adds fine-line hatching art brushes (Fine Hatching, Dense Hatching, Tapered Hatching, Broken Hatching). A click on a brush adds it to the document's Brushes as one undo step with every resource its art uses (patterns, symbols, swatches, graphic styles, images), makes it the current brush and, with paths selected, applies it to them in the same step; a brush the document already has is not added again and a different brush of the same name comes in numbered ("Wave 2"). Shift/Cmd-clicks select brushes for Add to Brushes; a brush dragged onto a path is added and applied to it, and one dragged onto the Brushes panel is added. Save Brushes… / the Brushes panel's Save Brush Library… write the document's brushes (or the selected ones) as a `.vectorcraft` library into the `Brushes` folder next to the preferences, listed under User Defined, or to a file; Other Library… reads the brushes of any document VectorCraft opens. Thumbnails, in the library panels, the Brushes panel and Brush Options, render brush art with the patterns and symbols it uses. Copying brushed art now carries the patterns and symbols its brush's art uses too. Tests: `crates/engine/src/tests/brushlib.rs`, `crates/ui-egui/src/panels/tests_brush_libraries.rs`, `panels::brushes::tests::library_brush_previews_show_the_patterns_their_art_uses`, `canvas::tests::a_library_brush_dropped_on_a_path_is_added_and_applied_in_one_step`. + - **Brushes panel item context menu:** right-clicking a brush row or thumbnail opens an item context menu offering "Brush Options…", "Duplicate Brush", and "Delete Brush" (disabled when the brush cannot be removed or is the last remaining default brush in the library). Right-clicking an unselected brush selects it before displaying the menu (matching the Symbols/Swatches pattern). Right-clicking within a multi-selection preserves the selection and offers "Duplicate Brushes" and "Delete Brushes". One undo step is recorded on delete or duplicate. Tests: `panels::brushes::tests::right_click_context_menu_in_brushes_panel`. - **Bristle Brushes library** ([What's new](https://helpx.adobe.com/illustrator/desktop/new-features/whats-new.html), [About brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html)): Window › Brush Libraries › Bristle Brushes holds ten bristle brushes, one for each tip shape (Fine Liner, Pointed Flat, Stubby Round, Dry Scrub, Soft Dome, Filbert, Angled Round, Angled Flat, Fan Blender, Grass Fan). The brushes, their names and their values are VectorCraft's own, and every value lies inside the range the bristle brush keeps (`brush.libraries`, `brush.addFromLibrary`; `the_bristle_brushes_library_covers_every_tip_shape_within_the_bristle_ranges`). - **Stipple library** ([About brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html)): Window › Brush Libraries › Stipple holds Fine Stipple, Dense Stipple, Soft Stipple and Bold Stipple. These original scatter brushes place filled vector dots or small dot clusters along a path, with varied size, spacing and spread; Soft Stipple uses translucent dots. Their art and settings are VectorCraft's own. Evidence: `stipple_library_draws_dot_textures_and_survives_save` in `crates/engine/src/tests/brushlib.rs` covers listing, finite drawn geometry, dots that take the stroke color with only Soft Stipple's translucent, add and apply, and saved-library reopening. - **Bristle strokes follow recorded pen input** ([brush documentation](https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=201)): a Bristle brush in VectorCraft widens its strand spread and thickness with pressure along the stroke; pen tilt changes the spread, and bearing and barrel rotation turn it in the path's local frame. Missing pen channels use neutral values, and mouse strokes keep their existing appearance. This is VectorCraft's own rendering model; hardware-specific output has not been verified. `bristle_pen_pressure_changes_its_footprint`, `bristle_pen_pressure_is_sampled_along_the_stroke`, `trimmed_bristle_strands_read_pressure_where_they_begin` and `bristle_pen_orientation_changes_its_footprint` cover the geometry in `crates/brush/src/tests.rs`; `bristle_path_keeps_and_draws_its_pen_pose` covers saving and export in `crates/engine/src/tests/brushsym.rs`; area scores unchanged. - **Tech Circuit library:** Circuit Trace is a chamfered art brush with 45-degree elbows and terminal pads; Bus Lines repeats three parallel conductor lanes; Terminal Nodes repeats solder pads, circular test points and connecting leads. Original vector geometry generated in code, with Tints colorization and continuous pattern tile edges. Evidence: `the_tech_circuit_library_constructs_adds_and_applies_each_brush` in `crates/engine/src/tests/brushlib.rs` covers listing, finite geometry on straight, curved, short and closed paths, add/apply, undo/redo, deduplication and saved-library round trips. G5 remaining estimate 3–13 h (estimated); area scores unchanged. - **Engraving library** ([About brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html)): Fine Hatching, Dense Hatching, Tapered Hatching and Broken Hatching make fine parallel-line textures along paths. These four 100 pt art brushes are original VectorCraft geometry, with Tints colorization; they can be added, applied and saved through the existing library controls. - **Image Brush library** ([About brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html)): Window › Brush Libraries › Image Brush offers Soft Bloom, Halftone Field, Solar Grain and Color Flecks as original image stamp designs. Each preset places copies of its embedded, transparent PNG along a path as a scatter brush; adding a brush carries its image resource into the document, and saving a library keeps the pixels. The public page names the category but not these presets. Evidence: `image_brush_stamps_draw_and_carry_their_pixels_when_added_and_saved` in `crates/engine/src/tests/brushlib.rs` covers stamps, add/apply and reopening; `the_window_menu_and_the_brushes_panel_open_brush_libraries` covers the UI. + - **Vector Packs library** ([About brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html)): Window › Brush Libraries › Vector Packs offers Compass Rose, Botanical Sprig, Facet Diamond and Tide Crest. Each is an original editable vector mark repeated along a path as a scatter brush and tinted by the stroke color. The public page names the category but does not specify its presets. Evidence: `vector_packs_marks_are_editable_and_survive_a_saved_library` in `crates/engine/src/tests/brushlib.rs` covers geometry, repetition, add/apply, undo and saving; `the_window_menu_and_the_brushes_panel_open_brush_libraries` covers the menu and panel. - **Pressure Sensitive library** ([About brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html)): Window › Brush Libraries › Pressure Sensitive offers Flex Ribbon, Pulse Stroke, Round Flow and Chisel Flow. The first two are art brushes whose width follows recorded pen pressure; the other two are calligraphic nibs whose size follows it. They use the engine's existing pressure input where the device and platform deliver it, and a neutral width for a mouse path. These presets and names are VectorCraft's own. Evidence: `pressure_sensitive_brushes_widen_with_pen_pressure_and_survive_a_saved_library` in `crates/engine/src/tests/brushlib.rs` checks light and heavy pressure, short and curved paths, add/apply and saved-library reopening; `the_window_menu_and_the_brushes_panel_open_brush_libraries` covers opening and clicking from the UI. + - **Decorative library** ([About brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html)): Window › Brush Libraries › Decorative offers Leaf Vine, Blossom Chain, Pennant Garland and Lantern String. The four original vector pattern brushes repeat plant, flower and hanging ornament tiles along paths and take the stroke color as tints. The public source identifies Decorative as a classic brush library; these preset designs are VectorCraft's own. Evidence: `decorative_brushes_repeat_distinct_art_and_survive_a_saved_library` in `crates/engine/src/tests/brushlib.rs` covers distinct finite output, add/apply and saved-library reopening, and `the_window_menu_and_the_brushes_panel_open_brush_libraries` covers opening and clicking from the UI. - **Paint library** ([About brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html)): Window › Brush Libraries › Paint offers Flat Sweep, Dry Drag, Loaded Stroke and Fan Sweep. These original art brushes stretch broad, broken, loaded and fanned vector marks along a path and take the stroke color as tints. The public source describes the Paint category's varied thickness, textured edges and natural effects; the preset designs and names are VectorCraft's own. Evidence: `paint_brushes_draw_distinct_marks_and_survive_a_saved_library` in `crates/engine/src/tests/brushlib.rs` covers finite output on short, long and curved paths, add/apply and saved-library reopening; `the_window_menu_and_the_brushes_panel_open_brush_libraries` covers opening and clicking from the UI. - **Dry Media library** ([help page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html)): Window › Brush Libraries › Dry Media holds four art brushes with textured strokes like dry drawing materials, each 100 pt long: Chalk Grain (about 8 pt high), Graphite Pencil (about 2.3 pt), Wax Crayon (about 5.5 pt) and Charcoal Dust (about 7 pt). The brushes, their names, sizes and art are VectorCraft's own: each is filled vector paths from a fixed seed, at most 80 paths and 500 anchors, stretched along the path with Tints colorization, and the chalk and crayon art has even-odd gaps where the paper shows (`brush.libraries`, `brush.addFromLibrary`; `the_dry_media_library_holds_grainy_art_brushes_with_bounded_art`). - **Arrows library:** Window › Brush Libraries › Arrows holds five art brushes, each 100 pt long: Solid Arrow, Open Arrow (an outlined head), Double Arrow (a head at each end), Chevron Arrow (a second chevron on the shaft) and Dashed Arrow (five separate dashes and a head). Each brush stretches only the part between its guides, so the shaft follows the path's length and the heads keep their proportions, with Tints colorization. The brushes, their names and their art are VectorCraft's own, generated in code (`brush.libraries`, `brush.addFromLibrary`; `arrows_library_lists_renders_and_applies_original_brushes`, `dashed_arrow_keeps_separate_dashes_and_survives_library_save`). @@ -1355,6 +1371,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Polygonal Lasso selects anchor points (and gradient mesh points) inside a straight-edged loop, with the Lasso's rule for which points are inside, and is listed under Object › Plug-ins and under its own heading in All Tools. It has no default shortcut or Basic toolbar slot. Each click sets a vertex. A double-click, Enter or a click on the first vertex closes the loop, Backspace or Delete removes the last vertex, Escape drops the loop, and Shift keeps the next segment to 45° steps. Shift or Alt held at the first click adds to or subtracts from the selection. This is a VectorCraft addition; scores and estimates are unchanged. Select by Artboards (Object › Plug-ins › Selection Tools, a VectorCraft addition: #5525, #5548, #5549) selects the objects overlapping, fully inside or fully outside one or more chosen artboards (`addon.select.byArtboards {artboards, relation}`). Overlapping is All on Active Artboard's test, shared as `select::on_artboard`; Fully inside means within one artboard, edges included; Fully outside means on none. It looks at what Select All takes, so hidden, locked and locked-artboard art stays out. Its dialog lists each artboard's number, name and size in the document's units, filters by name, chooses rows with click, Shift-click and Cmd/Ctrl-click, and fits a row's artboard in the window on double-click (`view.goToArtboard`). Tests: `crates/engine/src/cmd/addons/select/tests.rs`, `crates/ui-egui/src/addons/select/tests.rs`, `crates/engine/tests/command_sweep.rs`. Select by Link Status (Object › Plug-ins › Selection Tools and the Links panel menu, a VectorCraft addition: #5526) selects the image objects and placed documents whose link is linked (its file found unchanged), embedded, missing or modified, as `links.list` reports it (`addon.select.byLinkStatus {status, ids?, add?, zoom?}`); Select Linked, Embedded, Missing and Modified are off when no image has that status and add to the selection with Shift. Objects that are hidden or locked, inside a hidden or locked object or layer, on a template layer, on a locked artboard, or outside the isolated group are left out (the `select::is_selectable` test) and returned with the reason, and the status bar says how many, in plural forms of every catalog. Select by Link Status… lists each image and placed document with its name, status and format, searches by name, filters by status, picks rows with checkboxes and All / None, and zooms to the selection with the existing Zoom to Selection (`addon.arrange.zoomSelection`). Missing-link markers on the canvas are #5547. Tests: `crates/engine/src/cmd/addons/select/tests.rs` (`by_link_status`), `crates/ui-egui/src/addons/select/link_status/tests.rs`, `crates/engine/tests/command_sweep.rs`. + The Links panel provides an item right-click context menu on link rows offering Relink…, Go To Link, Update Link, Edit Original, Show in Folder, Separator, and Embed Image / Unembed…. Right-clicking an unselected row selects that row first; right-clicking a row that is already part of a multi-selection preserves the multi-selection. Tests: `panels::tests_links::right_click_context_menu_in_links_panel`. A marquee selects a clip group, or an object on a layer with a clipping mask, only when it reaches the area inside the clipping path, and it measures the art only within that path's bounds. Within the bounds of a mask that is not a rectangle, it can still select art that the mask hides. Direct Selection's marquee still selects the hidden anchor points inside it (#2345). When a clip group, a layer with a clipping mask or a single object in one is isolated, the Selection, Direct Selection and Group Selection tools also select the art that the mask hides, by a click or a marquee, and a drag from that art moves it (#3748). In isolation mode the canvas Unlock submenu also lists that art when it is locked. Outside isolation mode a click selects clipped art only inside the mask. A marquee selects a Shaper Group only when it reaches the art the group shows, not the original shapes kept under it, and Direct Selection's clicks and marquee do not select those shapes' anchor points. In Construction mode a marquee selects the original shapes, and Direct Selection selects their anchor points. @@ -1460,6 +1477,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur With Direct Selection, Shift pressed during the drag of a curved segment keeps both of its handles at right angles to the line between its anchors, on the same side and at the same length (`path.reshapeSegment {perpendicular}`). Shift held while any segment is dragged with the Anchor Point tool or the Pen with Alt does the same. With the Anchor Point tool, Shift held at the press on an anchor (or a selected blend's spine point) moves it, handles and all, instead of pulling out handles; Shift kept down keeps the move at 45° steps, and a Shift-click that doesn't move leaves the anchor as it was (`path.moveAnchor`). A selected blend spine's segment dragged with the Anchor Point tool, or a curved one dragged with Direct Selection, bends the same way (`object.blend.spine.reshapeSegment`). - **Live Corners:** drag a live rectangle's corner widgets (Selection or Direct Selection) to round all corners, with a radius readout; with Direct Selection, select corner anchors to show and round just those corners (#381). Each corner keeps its own radius and kind (Round, Inverted Round, Chamfer): Alt-click a widget to cycle the kind, double-click it for the Corners dialog, and the Properties and Transform radius fields set the selected corners (`object.setLiveShape {corners, radius, kind}`). A link toggle behind Corner Radius (the `singleCornerRadius` preference) switches the panels to a field for each corner of a live rectangle: Top Left, Top Right, Bottom Right and Bottom Left. Corners stay circular when the rectangle is scaled unevenly or along its own sides when rotated (the radius keeps its size, or scales by the mean scale with Scale Corners on); only a shear distorts them. On a rectangle that isn't square every corner is the same circle: a radius past half the shorter side stops there for all of them, the widgets sit on the corners as drawn and turn the edited corners red at that limit, CSS export writes the drawn radii, and rectangles saved stretched by older versions get circular corners when their corners are next set (#442). Live Corners work on any path's corners too, as on a rectangle's (#511): a star's, a live polygon's (which also shows them to the Selection tool, has a Corner Radius field in the Properties and Transform panels and keeps its radius as its sides change) and a pen path's, wherever two sides meet at an angle at an anchor that isn't smooth: curved sides too, trimmed to what the cut leaves of them (#1144). Direct Selection shows the widgets of every corner, or of the corners holding selected anchors; each corner is a circle tangent to both sides, drawn no larger than takes its cut halfway along its shorter side; a path keeps its uncut outline so its corners stay editable, and the same command, dialog, angle preference and View › Hide Corner Widget apply. With Direct Selection a click on a widget (no drag) selects its corner, as a click on the corner's anchor does, so the next drag on it rounds that corner alone; Shift-click toggles it (#1239). While a corner widget is dragged with the Selection tool the bounding box hides, so the rounding shows against the path alone (#1229). A round corner next to a curved side curves smoothly instead of sticking out of the shape (#1547, fixes #1512). View › Hide Edges hides the Live Corners widgets, the bounding box and the type widget, and the selection tools then do not answer a press on them or change the cursor over them. + - **Rectangle Properties corner type:** a live rectangle's Rectangle Properties (Transform panel, the Properties panel's Transform section and the Contextual Task Bar's Shape Properties) have a Corner menu with Round, Inverted Round and Chamfer. With Corner Radius linked, one menu sets the kind of every corner of each selected rectangle, also corners with no radius, and shows blank when the shown rectangle's kinds differ; unlinked, each corner's row has its own menu beside its radius field, or under it in a panel too narrow for both; the unlinked radius fields and menus leave other selected paths and polygons as they are. A pick is one undo step, and picking the kind the corners already have adds none (`object.setLiveShape {kind, rectanglesOnly, corners}`); an action that records them acts on the rectangles selected when it plays. The help page says a rectangle's corner type can be set for each corner or for all of them at once ([the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/live-shape-properties.html)); tying the number of menus to the Corner Radius link, the blank value and the undo steps are VectorCraft's own rules (`a_rectangle_shows_linked_and_unlinked_corner_types`, `the_shape_properties_popup_changes_a_rectangle_corner_type`, `the_linked_corner_menu_sets_every_selected_rectangle`, `the_unlinked_corner_menus_fit_a_narrow_panel`, `an_unlinked_corner_radius_leaves_other_selected_shapes`, `a_rectangle_corner_kind_without_a_selected_rectangle_changes_nothing`, `rectangle_kind_menu_targets_all_or_one_corner_and_skips_noop_undo`, `rectangles_only_sets_the_selected_rectangles_when_an_action_plays`, `a_radius_reaches_a_rectangle_that_already_draws_it`). - **Polygon side widget:** a selected live polygon shows a small diamond beside the middle of the right side of its bounding box, with the Selection tool and with the Rectangle, Rounded Rectangle, Ellipse, Polygon and Star tools, while the bounding box and the edges are shown. Dragging the widget sets the polygon's side count, from 3 to 11, as [the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/add-or-remove-sides-from-polygons.html) describes; typed counts in the Transform panel and `object.setLiveShape` still go from 3 to 1000. A drag down adds one side and a drag up removes one for every 12 screen pixels along the box's own vertical axis, and the pointer shows the count while measurement labels are on. A polygon of more than 11 sides keeps its count until the drag goes up, which gives it 11. The drag sends `object.setLiveShape {sides}`, so the polygon keeps its center, radius and rotation; the release adds one undo step when the count changed and none when it ends where it began, and Escape puts the count back. The widget's look and place, the drag direction, the step and the rule for more than 11 sides are VectorCraft's own (`crates/tools/src/sidewidget.rs`). - **Hide/Show Shape Widgets:** with the Rectangle, Rounded Rectangle, Ellipse, Polygon or Star tool, the Control bar shows a Hide Shape Widgets button, which reads Show Shape Widgets while the widgets are hidden (`view.shapeWidgets {on?}`). [The help page](https://helpx.adobe.com/illustrator/using/live-shapes.html) describes this Control panel button, offered with any live shape drawing tool, as switching the on-canvas widgets of selected shapes off and on. While they are hidden, a selected live rectangle's or polygon's corner widgets, a live ellipse's pie widgets and a live polygon's side widget are not drawn, and the Selection tool and those shape tools do not answer a press, a double-click or the cursor on their place (a shape tool draws from there). The bounding box and its handles, the center point and Direct Selection's corner widgets (View › Hide Corner Widget) stay as they are. The setting is on by default, kept with the interface state across sessions and tool switches, and adds no undo step. Its scope beyond the shape tools, its default and what it leaves shown are VectorCraft's own rules (tests `hidden_shape_widgets_leave_the_bounding_box`, `the_shape_tools_control_bar_hides_and_shows_the_shape_widgets`, `shape_widgets_command_toggles_and_takes_on`, `hidden_shape_widgets_do_not_answer_a_shape_tool` and `hidden_shape_widgets_leave_direct_selections_corners`). - **Blend spine Anchor Point tool (#2544):** on a selected blend, dragging a spine corner makes symmetric Smooth handles; the tool displays and picks existing spine handles when switched to, drags one independently or retracts it on click, and clicking a point with handles retracts both. The spine is edited live without moving its key objects. Windows native canvas checks and screenshots reviewed: symmetric and independent handles, corner/retraction, Shift constraints and perpendicular reshaping, tool switching, key preservation, Undo/Redo, save/reopen, hidden handles and overlapping Path/Blend priority (PR #2643). Behaviour reference: [public path-editing documentation](https://helpx.adobe.com/illustrator/using/adjust-path-segments.html). @@ -1476,6 +1494,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Type in a column design that holds a `%` followed by two digits shows each column's value in place of the `%` and the digits: the first digit is the least number of places before the decimal point (zeros are added in front; 0 gives as many as the value needs), and the second digit sets the places after it, rounded. Unless it is inside a group that clips or has its own opacity or appearance, or inside a blend, compound shape, envelope, repeat or intertwined objects, the type keeps its size and is drawn once per column in a repeating design. The legend swatch leaves it out. The transparency, paint, stroke, gradient and overprint commands and Expand Appearance also leave the art of a column or marker design inside a series unchanged. The graph draws that art again from the design (`docs/mcp.md`). When that art is given first with `aligned: true`, the paint, stroke and gradient commands read the `item` as a row of the art's stack, and each other object edits its equal row. + - **Graph designs from another document** ([Import a column or marker design](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=486)): a document opened with Window › Swatch Libraries › Other Library… adds its graph designs to the Column and Marker dialogs, listed under the library's name after the document's own. OK on one of them copies the design into the document with the swatches, patterns, symbols and styles its art uses, in the same undo step as the graph change (`graph.column` and `graph.marker` with `library`; `graph.design {library, add}` copies designs without applying them). A graph that is copied and pasted into another document brings the designs its series draw with. A design the document already has under the same name stays as it is, and a pasted graph is drawn again with that design when it would draw the graph otherwise, a VectorCraft rule. Tests: `designs_of_a_document_loaded_as_a_swatch_library_come_in_when_applied`, `a_design_the_document_has_under_the_same_name_stays_as_it_is`, `a_pasted_graph_brings_the_designs_its_series_draw_with` in `crates/engine/src/cmd/graph/tests.rs`. - **Other:** Eyedropper, Gradient annotator, Artboard (Alt-drag duplicates an artboard, and its art with Move/Copy Artwork with Artboard on; Copy, Cut and Paste take the artboard with its art, Paste right of the last artboard, Paste in Place where it was, into this or another document, #446; Object › Artboards › Rearrange All Artboards lays them out in a grid by row or by column, in one row or one column, left to right or right to left, from the menu, the Artboards panel or Properties' Rearrange All, #681; Scale Artwork with Artboard, in the Control bar and Properties beside Move Artwork with Artboard, resizes the artboard proportionally with the art fully inside it and its guides, strokes and corners per the Scale preferences, #602), Measure, Type, Hand, Zoom, Rotate View. While a drag rotates the view, a dial at the center of the canvas shows the angle. - **Editing type:** double-clicking type with a selection tool (Selection or Direct Selection) switches to the Type tool with the caret where it was clicked; pressing Escape finishes editing and switches back to the selection tool used before double-clicking it (when in isolation mode, the first Escape exits text editing while preserving isolation mode, and a second Escape exits isolation). @@ -1555,8 +1574,10 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur A Command Palette query word in an English plural or verb form finds a result whose English name or menu path holds the base word: "rounded corners" lists Effect › Stylize › Round Corners… first, and "scaling" finds Object › Transform › Scale…. The search drops `'s`; `es` after `s`, `x`, `z`, `ch` or `sh` (also trying the word with only its `s` dropped, so "rasterizes" finds Rasterize…); a final `s` in words of more than 3 letters, except after `ss`, `us` or `is`; `ing` in words of more than 5 letters and `ed` in words of more than 4. After `ing` or `ed`, a doubled `b`, `d`, `g`, `m`, `n`, `p`, `r` or `t` is tried both single and doubled, the single letter only when at least 3 letters are left ("cutting" meets Cut, "added" meets Add); otherwise the word is also tried with an `e` ("scaling" meets Scale…). It turns `ies` into `y` or `ie` in words of more than 5 letters and `sses` into `ss`, and leaves `series` and `species` as they are. Among results that the whole query matches the same way (as an id, as a label, at the start of a label, as initials, or none of these), a result whose name holds the base word of a query word ranks below one that holds the query word whole and above one where the query word only starts a word of the name, so "scale zz" lists a name with "Zz Scaling" above one with "Zz Scalers". "scale" alone still lists "Scalers" above "Scaling", because "Scalers" starts with the query. A partly typed word that is not itself a word of any result ("scal") does not meet a base word. Names shown in other languages and ids are not changed this way, and every result found before is still found (`palette::search` tests `plurals_and_verb_forms_meet_their_base_word`, `a_plural_or_verb_form_finds_the_result`, `a_better_word_grade_ranks_first`, `a_partly_typed_word_does_not_lift_a_verb_form`, `a_whole_query_tier_comes_before_a_stem_form`, `results_matched_without_a_stem_keep_their_order`). A Command Palette query word with a typo still finds the result: "gruop" lists Object › Group first, and "eyedroper", "rectange" and "elipse" list the same first results as the words spelled right, the Eyedropper, Rectangle and Ellipse tools among them. When a query word of 4 or more letters is not a word, a base word or the start of a word of any result's name, menu path or id, the search compares it (also when another result matches it through a word with the same meaning, so "spin" finds Span as well as Rotate) with the words of result names and menu paths, and a word 1 edit away (2 for a query word of 8 or more letters) matches; a letter added, left out or changed, or two letters next to each other swapped, is one edit. A query word meets at most the 32 nearest such words. Results matched through a typo come after every result the query matches in its name, menu path or id without one, and before every result the query matches only through its description; among them the query is read with the misspelled word replaced by the word it meets, so they come in the order the word spelled right gives; then a result whose label holds the word comes before one whose menu path holds it. Ids, and query words and result words with Chinese, Japanese or Korean letters, are not compared this way, and matching through a typo does not change the order of the results matched without one (`palette::search` tests `edits_are_counted_up_to_a_bound`, `a_word_with_a_typo_finds_the_result`, `a_typo_meets_at_most_32_words`, `a_word_with_the_same_meaning_elsewhere_still_finds_a_typo`, `a_description_match_ranks_below_a_typo`, `misspelled_words_find_the_command`). A Command Palette query word also finds a result whose name or menu path holds a word with the same meaning: "remove bg" lists Remove Background… first, "outline text" lists Type › Create Outlines first, and "flip", "combine", "vectorize" and "colour" list Reflect…, Unite, an Image Trace command and the Color panel among the first 3 results. The words come from VectorCraft's own table of 21 groups of English words (`palette/words.rs`, at most 60 groups of at most 6 words); a word that is the whole label of another command, such as Merge or Mirror, is in no group, and neither is Insert. A word or its English base word that is in a group meets the other words of its group in labels and menu paths, and their base words, but not ids or word starts. A result whose label holds the word itself ranks above one whose label holds a word with the same meaning, which ranks above one whose menu path holds the word, so "type" now lists Scale Text Attributes above Type › Orientation › Vertical. A catalog may add a group's words in its language with a row in the `search` context (the group's English words joined by ", ", then that language's words), used while that language is the UI language; no catalog has to have these rows (`palette::search` tests `a_word_with_the_same_meaning_finds_the_result`, `a_catalog_row_adds_words_to_a_group`, `words_with_the_same_meaning_find_the_command`; `palette::words` tests; `i18n` test `search_rows_name_a_group_and_add_single_words`). - The Command Palette ranks the commands listed in Recent Commands first among the results that match a query as well as they do, the most recent first, and below every result that matches it better: after a pick of Effect › Convert to Shape › Rectangle…, "rect" lists it above the Rectangle Tool, so Enter runs it again. A recent pick ranks after the whole-query match, the word grades and the matches through a typo, a description or a word with the same meaning, and before the kind of result and the name's length. The ranking uses the list Recent Commands shows. This is VectorCraft's own behavior (`palette::search` test `a_recent_pick_ranks_first_within_its_grades`; `palette` tests `a_recent_pick_ranks_first_among_results_that_match_as_well`, `the_kept_ranking_follows_the_recent_picks`). + The Command Palette ranks the commands listed in Recent Commands first among the results that match a query as well as they do and have the same use grade (described below), the most recent first, and below every result that matches it better: after a pick of Effect › Convert to Shape › Rectangle…, "rect" lists it above the Rectangle Tool unless the Rectangle Tool has the higher use grade, so Enter runs it again. A recent pick ranks after the whole-query match, the word grades, the matches through a typo, a description or a word with the same meaning, and the use grade, and before the kind of result and the name's length. The ranking uses the list Recent Commands shows. This is VectorCraft's own behavior (`palette::search` test `a_recent_pick_ranks_first_within_its_grades`; `palette` tests `a_recent_pick_ranks_first_among_results_that_match_as_well`, `the_kept_ranking_follows_the_recent_picks`). + The Command Palette also counts how many times each command is picked and ranks the commands picked most often first among the results that match a query as well as they do, also after they leave Recent Commands, and below every result that matches it better. A pick is counted only when Recent Commands records it, so a refused pick and a pick of Search Commands… are not counted. Counts are compared in grades that double: grade 1 starts at 1 pick, grade 2 at 3, grade 3 at 7, and so on up to grade 9, and a command picked once ranks above the commands never picked. The grade ranks after the word grades and the typo, description and same-meaning matches, and before the place among the recent picks. The count is kept for at most 200 commands: a new command then removes, of the half of the commands picked longest ago, the one with the fewest picks, of those the one picked longest ago. When a count reaches 1,000, every count is halved and commands left at 0 are dropped. The counts are saved with the other interface settings (`command_uses` in `ui.json`); a count above 999 loads as 999 and an unreadable entry is dropped. The web build keeps them for the session. This is VectorCraft's own behavior (`palette::search` test `a_command_picked_often_ranks_first_within_its_grades`; `palette` tests `a_command_picked_often_ranks_first_among_results_that_match_as_well`, `the_kept_ranking_follows_the_pick_counts`, `a_count_does_not_pass_a_better_match`, `pick_counts_rank_in_grades_that_double`, `the_201st_command_removes_the_least_used_and_keeps_itself`, `new_commands_build_up_counts_when_every_counted_one_has_more_picks`, `counts_are_halved_at_one_thousand`, `saved_pick_counts_load_what_is_readable`, `only_a_pick_recorded_in_recent_commands_is_counted`). A Command Palette query word also finds a command by what the command's description says: "transparent background" lists Remove Background… among the first 3 results, and "png" lists it after every result with "png" in its name or menu path. The description is the command's params text (an engine or plug-in command's, a UI command's, or an effect's) without each `{…}` group that is not inside a `{`, `[` or `(` group, without each such `[…]` or `(…)` group just after a `→`, and without the `→` before a removed group, cut to its first 300 characters at the end of a word. The words of a schema ("corners" for Remove Background…) and of a result written as a group do not find the command; a result written as words after a `→` stays in the description. Words of 2 characters or fewer, words with no letter, and "the", "and", "ids", "true", "false" and "null" are left out. A query word that is a word of a description, shares an English base word with one, starts one or has the same meaning as one finds the result, and such a result ranks below every result that the query matches in its name, menu path or id, as text inside a word or through a typo. Descriptions are English only, and a typo does not match them. Tools, panels and filter plug-ins have no description (`palette::search` tests `a_description_leaves_out_the_schema_and_the_result`, `a_word_of_the_description_finds_the_result`, `a_description_match_ranks_below_a_typo`, `words_of_a_description_find_the_command`). + A Command Palette result that cannot run now stays in its place in the list and is drawn dimmed: an engine command whose engine check fails (Ungroup with nothing selected, Paste with an empty clipboard and nothing to paste from the system clipboard), a UI command the menus dim, a filter plug-in or an effect whose menu item is dimmed, and a panel in Presentation Mode. Tools are never dimmed. The reason shows on hover, in the row's screen-reader description, on a second line of the search field's screen-reader description and in the footer while the row is highlighted, beside the count or, under the recent picks of an empty search, on a line of its own. The reason is the status line a pick of the dimmed menu item gives, with the result's name in place of the command's id: "command `Object › Ungroup` is not available right now: nothing selected", or without the engine's reason when it gives none. The Recent Commands list beside the search field draws such a pick dimmed too, with the same reason on hover and for screen readers. Only the drawn rows are checked, each once for as long as the state it was checked in lasts: a command run, an edit, a change of selection, document, history, clipboard, language, screen mode or open dialog, a save that marks the document saved, or a background save, export, file read, plug-in run or trace that starts, ends or shows its progress window checks them again on the next frame, and a frame with a click checks them again on that frame only. Typing in the search field does not check them again, and the palette checks them again each time it opens. The check never changes the ranking. A pick of a dimmed result does what it did before (`palette` tests `a_result_that_cannot_run_now_is_dimmed_and_says_why`, `hovering_a_result_that_cannot_run_now_says_why`, `paste_is_dimmed_only_while_nothing_can_be_pasted`, `tools_are_never_dimmed_and_panels_are_in_presentation_mode`, `a_result_without_an_engine_reason_says_it_is_not_available`, `no_reason_shows_a_command_id`, `a_recent_pick_that_cannot_run_now_says_why`, `a_recent_command_that_cannot_run_now_is_dimmed_in_the_list`, `availability_is_asked_again_when_what_it_depends_on_changes`, `availability_is_read_once_per_state`, `the_palette_asks_again_when_it_opens_again`). Each Command Palette row starts with an icon for its kind (a tool's own icon, or one for a panel, an effect, a filter plug-in or a command) and shows where the result lives after its label, in smaller dim text: the menu path of the menu bar item that runs it, with that item's label when it differs from the result's ("File › Exit" for Quit VectorCraft), and "No menu item" for a command no item runs. A panel's row shows "Window". A row with a home shows its label without the menu path in front of it. A path that keeps two results' names apart stays in the label, unless the row's home shows the same path; a tool's row drops the "Tools" in front of its name. A tool's row names the toolbar it is on: "Toolbar" for its button on the Tools panel, or the name of a toolbar made with New Toolbar, followed by ", in the group" when the tool is hidden in the group of a slot whose button shows another tool ("Toolbar, in the Direct Selection Tool group" for the Group Selection Tool), and "All Tools" when no toolbar holds it. A toolbar shown now comes first (the Tools panel, then the toolbars made with New Toolbar), then a hidden Tools panel, then hidden toolbars made with New Toolbar; toolbars count as hidden in Presentation Mode and while Tab hides the panels. The Learn command (`window.learn`), which Window › Learn runs, takes the Window menu as its home, so a search reads its menu path like any other result's, and among results that tie on everything else it ranks as a command of the menu bar, before panels and after tools. The home is cut short with "…" before the label, and a label too long for the row keeps the id it shows after its name unless the id alone is wider than the row. A cut row shows all its text while the pointer rests on it, and screen readers read the kind, the label, the home and the shortcut. The row height is unchanged (`palette` tests `rows_show_where_each_result_lives`, `no_two_rows_read_alike`, `a_tool_row_names_its_toolbar_slot`, `a_narrow_row_cuts_the_home_first_and_keeps_the_id`, `screen_readers_hear_the_kind_and_home`, `catalogs_translate_the_kind_and_home_words`). While the Command Palette is open, the highlighted result points to where it lives, in the same frame the arrow keys or the pointer move the highlight. A result with an item of the in-window menu bar has that menu's title outlined, with the item's whole path in a box under it ("Effect › Stylize › Round Corners…"); a panel points at the Window menu. A tool has its slot's button outlined on the toolbar the row names, or its own button on a strip torn off its group, with a box on the canvas side of the toolbar that names the tool, or says "In the Direct Selection Tool group: press and hold to open it" for a tool hidden in a group; screen readers hear that sentence with the search field's description. The box stays inside the window and off the button and the palette's popup: beside a button, its text wraps to up to three rows to fit before the popup or the window's edge, and where it still does not fit, the footer shows the text and only the outline is drawn; when the popup covers the control, nothing is drawn and the footer names the home. Nothing opens or shows: no menu, flyout, toolbar or All Tools drawer, and the chosen tool stays. With the system's menu bar, the footer reads "In the menu bar:" and the path instead; when no control in view shows the home (Presentation Mode, toolbars hidden by Window › Tools or Tab, a button scrolled out of view or under a floating panel or another toolbar) the footer names the home followed by "not shown now", and a command with no menu item reads "No menu item" with its shortcut. The menu bar and the toolbars note where they drew their controls only while the palette is open, and the palette uses only what this pass drew in its own window (`palette` tests `the_highlighted_result_outlines_its_menu_title`, `with_a_native_menu_bar_the_footer_names_the_path`, `a_tool_result_outlines_its_toolbar_slot`, `a_tool_on_a_toolbar_made_with_new_toolbar_is_outlined_there`, `a_strip_torn_off_the_tools_panel_is_pointed_at`, `a_box_beside_a_button_wraps_to_fit_beside_the_popup`, `the_box_keeps_off_its_button`, `the_callout_stays_off_the_palette`, `the_callout_keeps_off_a_popup_that_grew_in_the_same_pass`, `a_home_out_of_view_is_named_in_the_footer`, `the_pass_that_opens_the_palette_names_no_home_as_hidden`, `the_callout_follows_the_pointer`, `the_callout_follows_the_highlight_and_reveals_nothing`, `only_a_control_in_view_in_this_pass_is_pointed_at`, `a_control_under_a_window_is_not_pointed_at`, `the_noted_controls_hold_one_pass_per_viewport`, `catalogs_translate_the_callout_words`). `object.setProps` with `visible: false` or `locked: true` deselects every selected object that is then hidden or locked, the key object included, as the eye and lock columns do. @@ -1844,6 +1865,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Image Trace, a trace started before File › Revert does not apply after it:** the reverted document keeps its tab, but a trace prepared before the revert no longer applies, even when the restored image, object and settings are the same. A background trace that finishes after the revert changes nothing and the status bar says the document was reverted; a result handed to `imageTrace.make` or `imageTrace.makeAndExpand` is dropped and the restored image is traced again, as one undo step. Reverting another document, or a revert that fails, does not affect the trace (VectorCraft's own rule). Tests: `a_trace_run_prepared_before_a_revert_does_not_apply_after_it` in `crates/engine`, `a_trace_started_before_a_revert_does_not_apply` in `crates/ui-egui`. Scores and hours unchanged. - **Image Trace small contours:** closed fits too small to form an editable subpath retain their positioned outline, including holes. Source-generated island, hole/winding and stepped-region regressions cover Corners and Noise; defaults, parity scores and estimates are unchanged. - **Image Trace, custom presets:** Manage Presets next to the Image Trace panel's Preset dropdown saves the panel's settings as a new preset under a name (Save as New Preset…) and renames or deletes the saved preset shown; built-in presets don't change. Saved presets are kept with the preferences and follow the built-in ones in the panel, Control bar and Properties preset lists. `imageTrace.presets.save` and `imageTrace.presets.delete` save, rename and delete them, `imageTrace.presets` lists them, and `imageTrace.make {preset}` traces with one by name. +- **Image Trace, Edit › Tracing Presets…:** the menu item opens a manager for the same presets, as the [help page](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=106) describes: New… makes a preset from the selected one, Edit… and Delete change saved presets only (built-in presets, in brackets, don't change), and Import… and Export… exchange the saved presets through a `.vctracepresets` file (`imageTrace.presets.import` / `.export`, `ui.tracingPresetsDialog`). The file layout, the question before an import replaces saved presets of the same names (Cancel keeps them), the selection after Delete and the editor's Cancel are VectorCraft's own. - **Image Trace, preset buttons:** six buttons above the Image Trace panel's Preset dropdown choose a preset as the dropdown does, for the options the [help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/image-trace-panel-options.html) lists before Preset. The presets each button chooses are VectorCraft's own: Auto Color chooses Auto Color, High Color chooses High Fidelity Photo, Low Color chooses Low Fidelity Photo, Grayscale chooses Shades of Gray, Black and White chooses Black and White Logo, and Outline chooses Outline. With Preview on, a click traces the selected Image Trace object again as one undo step; with nothing traced selected, it changes the panel's settings only. The button of the panel's preset shows as selected. - **Create Strokes baseline (2026-10-17, measured):** the ignored centre-lines class covers 23 exact code-drawn scenes in aa and hard variants, including junctions, crossings, fills meeting strokes and varying widths. [Baseline and metric definitions](image-trace-quality.md#centre-lines). Topology is recovered from emitted geometry; width-profile metrics remain unavailable. No behaviour change or score increase. - **Image Trace, collapsed loops keep few segments:** a loop whose fit collapses to one cubic keeps the fewest segments that hold its area and course, so a higher Paths gives no fewer segments; a code-drawn Paths sweep in `crates/trace` (see [quality notes](image-trace-quality.md#collapsed-loops-keep-few-segments)). @@ -1908,7 +1930,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur As VectorCraft's own rule, OK in Live Paint Selection Tool Options, Live Paint Bucket Options, Gap Options and Tile Edge Color gives an error for a color with an alpha part (`#rrggbbaa` or `#rgba`) and changes nothing. As VectorCraft's own rule, a Live Paint edit that changes nothing records no undo step, keeps the redo steps and leaves a saved document saved: a Live Paint Bucket click or drag over faces that already have the fill, a stroke on an edge that already has the paint and weight, Gap Options OK with the options the groups have and no gap to close, and Make or Merge with one Live Paint group alone. Such a fill or stroke also leaves the recent colors as they are. Regression tests: `live_paint_fill_same_paint_is_no_op`, `live_paint_bucket_click_with_the_face_paint_is_no_op`, `live_paint_stroke_edge_same_paint_and_width_is_no_op`, `live_paint_gap_options_same_values_are_no_op`, `live_paint_gap_options_close_without_gaps_is_no_op`, `live_paint_make_existing_group_is_no_op` and `live_paint_merge_single_group_is_no_op` in `crates/engine/src/tests/build.rs`, and `ok_on_unchanged_options_records_no_undo_step` in `crates/ui-egui/src/dialogs/live_paint_gaps.rs`. As VectorCraft's own rule, the Live Paint Bucket replaces all of a face's fills, or all of an edge's strokes, with one fill or stroke of the paint, shown, fully opaque and blending normally, so a lower fill or stroke no longer draws under the new paint and a fill or stroke of none leaves nothing of that kind drawing; the face's strokes, the edge's fills, the part's own opacity and the topmost shown stroke's dashes, caps and arrowheads stay as they are, and a part that already has only that one fill or stroke records no undo step. [The help page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/paint-with-the-live-paint-bucket-tool.html) says the tool paints faces with the current fill and edges with the current stroke. Regression tests: `live_paint_bucket_replaces_every_fill_row`, `live_paint_stroke_edge_replaces_every_stroke_row` and `live_paint_stroke_edge_paints_the_shown_stroke` in `crates/engine/src/tests/build.rs`. - As VectorCraft's own rule, with a tool other than the Live Paint Bucket, a fill given to a whole selected Live Paint group paints its faces only and a stroke paints its edges only, and the hidden source paths keep their paint. Swap Fill and Stroke trades the fill the faces share with the stroke the edges share, and Default Fill and Stroke leaves the faces with no fill and gives the edges a 0.5 pt black stroke (`docs/mcp.md`). Evidence: `tests::build::{live_paint_group_fill_goes_to_faces_and_stroke_to_edges, live_paint_group_swap_trades_the_faces_fill_and_the_edges_stroke, live_paint_group_default_clears_the_faces_and_gives_the_edges_a_thin_black_stroke, live_paint_group_invert_recolors_the_faces_fill, live_paint_group_gradient_vector_and_freeform_edits_change_its_faces, live_paint_group_stroke_panel_edits_change_its_edges, live_paint_group_rules_stop_where_paint_commands_stop, live_paint_group_without_parts_of_the_edited_kind_leaves_new_art_alone}`. + As VectorCraft's own rule, with a tool other than the Live Paint Bucket, a fill given to a whole selected Live Paint group paints its faces only and a stroke paints its edges only, and the hidden source paths keep their paint. Swap Fill and Stroke trades the fill the faces share with the stroke the edges share, and Default Fill and Stroke leaves the faces with no fill and gives the edges a 0.5 pt black stroke (`docs/mcp.md`). The Eyedropper gives the picked fill attributes to the faces and the picked stroke attributes to the edges, and picks up a whole group as its first face's fills with its first edge's strokes. Overprint Fill goes to the faces and Overprint Stroke goes to the edges. The proxies show the same paint whatever the order of a selection that holds the group and one of its parts. Appearance panel edits of the group's contents leave the hidden source paths as they are, a new fill goes on the faces, and a new stroke goes on the edges. Evidence: `tests::build::{live_paint_group_fill_goes_to_faces_and_stroke_to_edges, live_paint_group_swap_trades_the_faces_fill_and_the_edges_stroke, live_paint_group_default_clears_the_faces_and_gives_the_edges_a_thin_black_stroke, live_paint_group_invert_recolors_the_faces_fill, live_paint_group_gradient_vector_and_freeform_edits_change_its_faces, live_paint_group_stroke_panel_edits_change_its_edges, live_paint_group_rules_stop_where_paint_commands_stop, live_paint_group_without_parts_of_the_edited_kind_leaves_new_art_alone, live_paint_group_proxies_do_not_depend_on_the_selection_order, live_paint_group_eyedropper_gives_the_fill_to_faces_and_the_stroke_to_edges, live_paint_group_eyedropper_gives_every_fill_and_stroke_row, live_paint_group_contents_edits_follow_the_group_rule, live_paint_group_item_edits_and_overprint_follow_the_group_rule, live_paint_group_inside_a_selected_group_keeps_the_proxies_independent_of_order, live_paint_group_eyedropper_picks_up_the_group_and_appends_without_effects}`. As VectorCraft's own rule, `tool.setOption` for the Live Paint Bucket and the Live Paint Selection tool, chosen or not, checks every value before it sets any: a switch that is not `true` or `false`, a `color` that is not an RGB color or a layer color's name, or that has an alpha part, a `width` that is not a number and an option the tool does not have give an error naming the option, and nothing is set or saved. A `width` outside 1 to 20 px is still set to the nearest end of that range. Saved settings that hold an invalid value still load, and the tool keeps its default for that option. Evidence: `tests::build::{live_paint_tool_options_refuse_invalid_values_and_change_nothing, live_paint_tool_options_take_rgb_colors_and_clamp_the_width, live_paint_tools_load_saved_settings_with_invalid_values}`. As VectorCraft's own rule, `tool.setOption` for the Shape Builder, chosen or not, checks every value the same way: a switch that is not `true` or `false`, a `pickColorFrom` or `selection` that is not one of its names, a `gapLength` that is not a number, a `highlightColor` that is not an RGB color or a layer color's name, or that has an alpha part, and an option the tool does not have give an error naming the option, and nothing is set or saved. A `gapLength` outside 0 to 72 pt is still set to the nearest end of that range. Evidence: `tests::build::{shape_builder_tool_options_refuse_invalid_values_and_change_nothing, shape_builder_tool_options_take_valid_values_and_clamp_the_gap}`. A drag of 3 screen pixels or more with the Live Paint Selection tool draws a marquee and selects the faces and edges it touches, partly enclosed ones included, and a Shift-drag adds them to the selection or removes them from it ([Modify Live Paint groups](https://web.archive.org/web/20261006115247/https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/modify-live-paint-groups.html)). A click and a marquee change the selection on release, and Escape before the release leaves the selection as it was. Locked Live Paint groups, those on a locked layer or artboard, and in isolation mode those outside the isolated art are not highlighted or selected. @@ -1945,7 +1967,10 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Colorized images (#1466):** a fill color applied to a selected grayscale or 1-bit image (`paint.setFill`) colorizes it with black, white, a process color or a spot color, and refuses a process color when the image has an alpha channel ([Convert color modes](https://web.archive.org/web/20251220223850/https://helpx.adobe.com/illustrator/desktop/manage-colors/select-and-adjust-colors/convert-color-modes.html), "Colorize Grayscale or 1-bit images"); black and white are accepted there too. The canvas draws each pixel in the color as far as the pixel is dark, with white pixels transparent; PDF export writes the image in the color (a spot color as its ink, Registration in every ink) with the image as its soft mask; Separations Preview and printed separations show it on its color's plates; native files keep the color. EPS and SVG write the image's own pixels. - **Missing library files:** a persistent swatch or graphic style library panel whose file is gone at startup reopens and stays in the preferences, showing the file's path with Locate Library… (`ui.libraryPanel.locate`), which reads the file from where it is now into the same panel. - **Swatch library and Recolor Artwork parameters:** the `swatch.library.*` commands, `swatch.resetDefaults`, the graphic style library save, load and add, the `recolor.*` commands and `color.harmony`'s `limitTo` refuse parameters of the wrong form, such as `names: "Grays"`, `limitTo: 5` or `includeImages: "false"`. Errors name the parameter, except that a `limitTo` that is not a string, such as `5`, gets an unknown-library error. A `null` counts as left out except for `recolor.apply`'s `model`, which must be a string when given. - - **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. 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. + - **OKLCH Sliders (Color Wheel panel):** as VectorCraft's own addition, the Color Wheel panel's menu item OKLCH Sliders (`ui.colorWheel {sliders: "oklch"}`, kept with the preferences) shows L, C and H rows under the wheel or the box that edit the color by the OKLCH lightness (0 to 100 %), chroma (0 to 100 % of 0.4) and hue (0 to 360°) of its display sRGB, as CSS Color 4 defines them (https://www.w3.org/TR/css-color-4/#specifying-oklab-oklch). Each track dims the colors outside sRGB, and a tick on the C track marks the largest chroma sRGB holds at the row's L and H; a color outside sRGB keeps L and H and takes the largest chroma that fits, and the C row keeps the chroma asked for. The rows take the arrow keys after a click and report their names, values, ranges and adjust actions to screen readers. While the active document's RGB space (its assigned profile, else the working RGB space of Edit › Color Settings) is not sRGB, the unchecked item is gray and `ui.colorWheel {sliders: "oklch"}` answers an error; rows shown before the space changed are gray, and the checked item still hides them. `color.convert {color, to: "oklch"}` answers the same L, C and H for a color inside sRGB. For a color outside sRGB, it clips the display RGB to 0 to 1 first, so its L, C and H can differ from the rows' values. Evidence: `crates/color/src/oklab.rs` tests; `convert_to_oklch_answers_lightness_chroma_and_hue` in `crates/engine/src/tests/colormgmt.rs`; the OKLCH tests in `crates/ui-egui/src/panels/tests_color_wheel.rs`, `the_oklch_tracks_dim_the_colors_outside_srgb_and_the_tick_marks_the_largest_chroma` and `oklch_sliders_are_gray_after_the_working_space_changes` among them. Scores and estimates are unchanged. + - **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. - **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}`). **Color panel spectrum mode tooltip (part of #7235):** hovering the spectrum names the displayed mode (Grayscale, RGB, HSB, CMYK, Web Safe RGB or Lab), including after Shift-clicking to switch modes and with Show Options or Hide Options. Hovering changes no paint or undo history. Spectrum rendering and vertical resizing remain open. Evidence: `spectrum_tooltip_names_its_displayed_mode` and `spectrum_tooltip_follows_shift_cycle_without_painting` in `crates/ui-egui/tests/color_working_components.rs`. Scores and estimates unchanged. @@ -2085,6 +2110,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur The Appearance panel's thumbnail dropped on a graphic style with Alt held replaces that style with the look of the object the panel shows; the style keeps its name and the art that uses it takes the new look, as the help page describes ([the help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=568)). VectorCraft's own rules: art dragged off the canvas does the same with its first object; the style keeps its place in the list, is outlined while one is held over it with Alt, and the replacement is one undo step; an object already linked to the style with its look changes nothing; without Alt the drop makes a new style (`art_or_an_appearance_dropped_on_a_style_with_alt_replaces_that_style` in `crates/ui-egui/src/panels/graphic_styles.rs`). A graphic style dragged onto another style in the Graphic Styles panel with Alt held gives that style the dragged style's look; the replaced style keeps its name and the art that uses it takes the new look, as the help page describes ([the help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=568)). VectorCraft's own rules: the dragged style and the art linked to it stay as they are; the replaced style keeps its place in the list and is outlined while a style is held over it with Alt; the replacement is one undo step; a style dropped on itself, or on a style with the same look, changes nothing and records no undo step; without Alt the style moves (`graphicStyle.redefine {name, from}`, `a_style_dropped_on_another_with_alt_replaces_that_style` in `crates/ui-egui/src/panels/graphic_styles.rs`, `tests::styles::redefine_from_a_style_gives_the_style_that_look`). In the Graphic Styles panel's thumbnail and list views, a style with no fill and no stroke, one with only effects or transparency included, shows its preview shape with a black outline, a white fill and a red slash, as the help page describes for the panel's thumbnails ([Graphic styles](https://helpx.adobe.com/illustrator/using/graphic-styles.html)); its effects still draw on that shape. The Control bar's Style picker and chip, graphic style library panels and the large preview on the selected object show the same marker. A fill or stroke row that paints None does not count as a fill or stroke, and a hidden row or one with zero opacity does; these rules, the marker outside the panel's thumbnails and the slash's direction and size are VectorCraft's own (`a_style_with_no_fill_and_no_stroke_shows_an_outlined_shape_and_a_red_slash` in `crates/ui-egui/src/panels/graphic_styles.rs`). + In the Graphic Styles panel's thumbnail and list views, right-clicking a style item opens its context menu offering Graphic Style Options…, Duplicate Graphic Style (or Duplicate Graphic Styles when multiple styles are selected), Delete Graphic Style (or Delete Graphic Styles), Redefine Graphic Style (enabled when canvas art is selected), and Break Link to Graphic Style (enabled when the selection is linked to this style). Right-clicking an unselected style selects it first, while right-clicking an item in an existing multi-selection preserves the multi-selection. Default Graphic Style disables Options and Delete. Secondary button hold still triggers large preview on tiles/rows. Tests: `right_click_context_menu_in_graphic_styles_panel`, `right_click_context_menu_default_style_disables_options_and_delete`, and `right_click_context_menu_preserves_multiselection_and_works_in_list_view` in `crates/ui-egui/src/panels/graphic_styles.rs`. Applying a style to several objects, and Redefine Graphic Style, give the objects one shared copy of the style's appearance instead of a copy each; an object that is edited later gets its own copy, and an object whose placed gradients are fitted to its own bounds gets its own. The undo history's memory estimate counts a shared appearance once. Saved files are unchanged (`crates/engine/src/tests/styles.rs`). - **Several text styles at once:** in the Character Styles and Paragraph Styles panels, Shift-click highlights a range of styles and Ctrl/Cmd-click adds or removes one, without applying them; the panel menu's Select All Unused (`charStyle.unused`, `paraStyle.unused`) highlights the styles no type uses (in the layers, opacity masks, symbols, graph designs, pattern tiles and the art of brushes), never the Normal style; Delete, the button or the menu item, deletes every highlighted style but Normal in one undo step (`charStyle.delete {names}`, `paraStyle.delete {names}`). The menu's Duplicate copies every highlighted style in one undo step and highlights the copies. A highlighted row dragged onto Create New Style or Delete carries every highlighted style: dropped on Create New Style it copies them all and highlights the copies, and dropped on Delete it deletes them all but Normal and clears the highlight; a row from outside the highlight carries only its own style. Public reference: [Character and paragraph styles](https://web.archive.org/web/20261015081534/https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html). - **Load text styles from another document:** the Character Styles and Paragraph Styles panel menus have Load Character Styles… or Load Paragraph Styles… and Load All Styles…, which copy the styles of a document picked in an open dialog, with the swatches and patterns they paint with, in one undo step (`charStyle.load`, `paraStyle.load`, `textStyle.loadAll`); a style the document already has, under its name or a numbered one, is not added again, any other whose name is taken gets a number, and the file's Normal styles are not loaded. Public reference: [Character and paragraph styles](https://web.archive.org/web/20261015081534/https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html). @@ -2318,6 +2344,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Placed documents' bitmaps on screen: when a bitmap made in the background is ready, the desktop app renders the canvas again only where the objects that show its file are, when the frame shown was rendered on the UI thread and that part is at most half the canvas. Bitmaps drawn or made since a frame began are kept for that frame past the 512 MiB budget, up to 2 GiB, so a view showing more than the budget does not make them again in every frame. A bitmap that would take them past 2 GiB is not kept, and its file draws exactly at that zoom. A bitmap that can't be made (the file can't be read and there is no preview) shows the light placeholder and is not asked for again. Each ready bitmap used to render the whole canvas again, and bitmaps past the budget and bitmaps that could not be made were asked for again in every frame (`crates/render/src/tests/placed_document.rs`). - Linked PDF and `.ai` pages: File › Place with Link (the default) places a page of a PDF, `.ai` or `.ait` file read as PDF pages as a placed document, as it links an image, the page and its box (`crop`) kept with the link: Links check, update and relink it, Break Link and Object › Expand give the group placing it without Link gives, every output draws the page's vectors, and Package copies the file. Without Link, or with a password or `textAs: "outlines"`, the page is embedded. An EPS file, a PostScript file or a PostScript `.ai` placed from a file with Link is a placed document the same way, showing the art placing it without Link gives (clipped to its bounding box, or its art's bounds with `crop: "bounding"`); Links lists it as `EPS` or `PostScript`, and a save, Package, Break Link and Object › Expand treat it as they treat a placed PDF page. Package also copies the files that the native document of an EPS file written by VectorCraft links, beside the EPS file's copy, which finds them there by name. Placing one keeps the file linked rather than embedding it, as [the help page](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-other-file-types/eps-and-dcs-file-import-in-illustrator.html) describes; a DCS file stays a linked image (`crates/engine/src/tests/placed_document.rs`, `crates/engine/src/tests/package.rs`). - File › Open's Import PDF dialog checks Import PDF pages as links when All is picked and clears it when Range is picked: every page of a PDF opened from its file opens linked unless the box is cleared, and a range of pages opens as art unless the box is checked ([the help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=444)). A box checked or cleared by hand keeps that state until the other of All and Range is picked; picking the one already picked, or editing the range, does not change it, and `ui.dialog.set` of `allPages` changes it as the buttons do (VectorCraft's own rules). A file opened without its path, with a password or over the 256 MB that linked pages take still opens its pages as art. The box used to start cleared for All as well (`crates/ui-egui/src/dialogs/tests_import_pdf.rs`). + - The Import PDF and Place PDF dialogs have a Text choice, Editable or Outlines (VectorCraft's own option): Outlines opens or embeds a PDF's text as the glyph outlines the file draws, so it looks the same on a computer without its fonts. The choice is kept as Preferences › File Handling › PDF Text (`pdfTextAs`, Editable by default), which also applies to a PDF that opens or is placed embedded without the dialog. Outlines clears Import PDF pages as links, and a linked place dims the choice (`crates/ui-egui/src/dialogs/tests_import_pdf.rs`). - The place cursor keeps an encrypted PDF, `.ai` or `.ait` file, at a letter page's size (VectorCraft's own size) and without a thumbnail, and a click or drag on it asks for its password, with the Place dialog's Show Import Options on or off; such a file was left out of the cursor before (`crates/engine/src/tests/place.rs`, `crates/ui-egui/src/tests/place.rs`). - File › Place with Bounding Box (`file.place {crop: "bounding"}`) measures the art that shows, with its strokes and effects, as an export does: hidden objects, guides and template layers do not count, a group whose only part on the page or artboard is hidden is not placed, and symbol instances are measured by their art, for `at`, `rect`, the place cursor and `file.place.info` (`crates/engine/src/tests/place.rs`). - The Place dialog has a Show Import Options checkbox after Link, Template and Replace ([Place multiple files in a document](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-other-file-types/place-multiple-files-in-a-document.html)). On (VectorCraft's default, saved with the preferences), each PDF, DXF or text file asks for its import options before it is placed, also in the place cursor; off (`file.place {showImportOptions: false}`), it is placed with the options last confirmed for its format, and only an encrypted PDF asks, for its password. Text Import Options now starts from the options confirmed last (`crates/ui-egui/src/tests/place.rs`). @@ -2476,6 +2503,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur When the Layers or Links panel shows another document's rows, the thumbnail thread drops the row thumbnails it has not started for the documents not shown, and it drops all of them when the Layers or Links panel is open after the last document closes. Those rows ask for their thumbnails again when their document shows again, and the thumbnails already made are kept. With 150 rows of 20,000-anchor paths waiting for another document, the 8 rows of such paths of the document shown get their thumbnails in 153 ms instead of 3,265 ms (debug test build, median of three runs). The Links panel keeps its `links.list` rows and Link Info in one shared cache, and a frame that fetches nothing new reads that cache without copying the rows. The cache is replaced when the document or its revision changes, the Show, Sort or Show DCS Transparency Interactions option changes, or the files are looked at again every 2 seconds, and, while an image is selected, when Link Info opens or closes or the first selected image changes. With 2,001 images a frame's cache step takes 0.2 µs instead of 1.79 ms, and with 10,001 images 0.2 µs instead of 12.2 ms (test build, median of 7 wall-clock runs of 1,000 frames, measured while other builds were running). In the web build, while a pan, zoom or rotation changes the view of a document whose last canvas render took more than 8 ms, the canvas draws the last frame moved with the view, and it renders the art again once the view has been still for 0.2 s. + In the web build, an edit while that view moves (a tool drag held near an edge of the canvas, which scrolls the view, or a wheel scroll during a drag) draws only the part of the last frame that the edit changed, at the view that frame was rendered for, and the frame stays drawn moved with the view until the view has been still for 0.2 s (#8688). The part of the canvas a pan uncovers shows the pasteboard and the artboards' paper until then, as for a pan without an edit. Edits that go on after the view stops don't start that 0.2 s again: the whole canvas renders 0.2 s after the view stopped. An edit that changes more than half of the frame, or one while more than the view and the document change, renders the whole canvas at once as before. Tests: `canvas::tests::without_a_worker_a_heavy_canvas_is_reprojected_until_the_view_is_still`, `canvas::tests::without_a_worker_edits_while_the_view_is_still_do_not_hold_off_the_render`. An Alt-drag with the Selection, Direct Selection, Group Selection, Rotate, Scale, Reflect or Shear tool copies the selection on its first move, and the moves after it transform those copies; the previews of the Move, Rotate, Scale, Reflect and Shear dialogs with Copy and Preview on copy the selection once in the same way (#1429). An Alt-drag of objects in perspective with the Perspective Selection tool, and an Alt-drag of a plane widget with that tool or the Perspective Grid tool, copy the objects on the first move, and the moves after it move those copies (#1429). With the Perspective Selection tool, Ctrl+Alt-drag (Command+Option-drag on macOS) also copies objects on their perspective plane; Alt/Option-drag continues to do so. @@ -3039,6 +3067,14 @@ The public pages describe Retype finding the fonts that match selected outlined The identify-fonts page has the Retype panel list ten matching fonts ordered by closeness, with five more on request, previews in one of three text sizes and the user's own sample text ([identify fonts](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/identify-fonts-using-retype.html)). Window › Retype shows the Retype panel. Find Matching Fonts (`retype.find`, on `type.retypeFonts`) lists the fonts whose glyphs the selected shapes exactly match, comparing up to 96 loaded fonts with those of the document's live type first, so a matching font past that limit is not listed; Find more font matches adds five. The 96-font limit is VectorCraft's own. The order is VectorCraft's own: by how many shapes each font matches, then by how closely. The sample sizes (Small, Medium, Large) and the 100-character sample text limit are VectorCraft's own too. Each row shows a sample in the font, in the size the panel menu sets and with the text typed in the panel, and a click on a row sets the font on the selected live type. Tested in `crates/engine/src/cmd/retype_fonts_tests.rs` and `crates/ui-egui/src/panels/retype/tests.rs`. Opening the panel from the Type menu, the context menu and the Properties panel's Quick Actions, filtering the list by font source and favorites, near matches, installed fonts not yet loaded and images remain. +## Retype tracking (2026-11-19) + +#4934 asks Retype to match the tracking of outlined text. `type.retype` now sets a line whose glyphs most gaps space evenly apart with that spacing as tracking, keeps gaps one space wide as word spaces when untracked type draws them, and sets negative tracking only on opaque, Normal lines with a solid fill or none and no stroke. These rules are VectorCraft's own. Each line is laid out and compared with the outlines before it is kept; a line its tracked type would move a glyph of is checked again untracked, and the glyphs after a split take the tracking their own gaps give. Tested by round trips through Create Outlines (a tracked line with a word space; uneven, tight and fractional tracking; kerned pairs in tight tracking; spaced letters that need no tracking; translucent overlapping glyphs) and by the measure's layout budget, in `crates/engine/src/cmd/retype_tests.rs`. + +## Retype several lines (2026-11-19) + +#4934 asks for area text when outlined text has several lines, with its line spacing. `type.retype` now turns lines that follow each other, stack at one leading and line up at their starts, ends or centers into one area type object with that leading and left, right or center alignment. These rules are VectorCraft's own. Each object is laid out and compared with the outlines before it is kept; when area type would move a glyph, the lines become multi-line point type, and when that also would, the block ends at the line of that glyph and the lines after it join again. Tested by round trips through Create Outlines (three lines with Auto leading; set leading with left, center and right alignment; long blocks at leadings finer than a thousandth of a point; a line tracked apart from the others; tracked lines with word spaces; lines far apart or askew; a shape painted between two lines; translucent, blended, gradient and stroked lines; lines under a Text Wrap object) in `crates/engine/src/cmd/retype_tests.rs`. + ## Control bar: Paragraph section while type is selected (2026-11-06) With type selected, the Control bar shows a Paragraph: link and the Align left, Align center and Align right buttons after its Character controls, as the public documentation has the Control panel format paragraphs while the Type tool is in use, with a way to the Paragraph panel ([Paragraph panel overview](https://helpx.adobe.com/illustrator/using/formatting-paragraphs.html)), and its alignment buttons align text as the Paragraph panel's do ([Align text](https://helpx.adobe.com/illustrator/using/align-text.html)). A button aligns the selected type (`text.setStyle {justify}`, one undo step) and the shared alignment shows selected; the link opens the Paragraph panel in a popover under it, as Character: opens the Character panel. Keeping to the three alignments that don't justify is our choice, for the bar's room; the popover has all seven. Short of room the bar leaves controls out from its right end: the inline X/Y/W/H fields, the Distribute and Align buttons, area type's vertical alignment, then these buttons and last the link, keeping room for the Transform link; on a 1536 pt bar with one point type object, the buttons show (pinned by a headless test, #5372). @@ -3103,6 +3139,9 @@ Edit › Copy and Cut put the selected ruler guides on the clipboard, with the s | Date | Change | Summary | |---|---|---| +| 2026-11-19 | minor | Guides, grids, smart guides, snapping, rulers: View › Trim View hides the ruler guides, guide paths and the grid while it is on and greys out their Show/Hide items; a ruler drag or double-click makes no guide meanwhile (#8363). Scores and estimates unchanged. | +| 2026-11-19 | minor | Scissors previews its actual anchor or curve cut point with a native point marker while hovering, retaining existing snapping, Alt Add Anchor and cut behavior (#8655). Scores and estimates unchanged. | +| 2026-11-19 | minor | Performance: In the web build, an edit while the view of a heavy document moves (a tool drag held at an edge of the canvas, #8551, or a wheel scroll during a drag) draws only the part it changed into the last frame, which stays drawn moved with the view, instead of rendering the whole canvas each frame, and edits that go on once the view is still don't put off its render (#8688). Evidence added; scores and estimates unchanged. | | 2026-11-19 | minor | Artboard tool: Shift held once a move or an Alt-drag copy of an artboard is under way keeps it to the level, upright or 45° line from General › Constrain Angle, and snaps slide it along that line; a Shift-press still draws an artboard inside another or marquee-selects (#2497), #8580. Scores and estimates unchanged. | | 2026-11-18 | minor | Layers panel: context menu on guide rows (Release Guide, Duplicate, Delete Guide, Lock/Unlock, Hide/Show) with one-step undo; regression tests in `crates/ui-egui/src/panels/layers/tests.rs`; scores and estimates unchanged. | | 2026-11-18 | minor | Type advanced: Retype phase 1 (`type.retype`, #4934), exact matches of available fonts become point text again; evidence added; near matches, the ranked font list and images remain; score and hours unchanged | diff --git a/docs/three-d.md b/docs/three-d.md index 2c2a713cd8..2327eb1c24 100644 --- a/docs/three-d.md +++ b/docs/three-d.md @@ -106,7 +106,7 @@ object is where the art was. | Twist | 0° to 360°: the back face turned against the front, the walls following in slices. | | Taper | 1–100 %: the back face's size against the front's. Without a twist, each wall (and each bevel band) stays flat, so it is one face, not cut into slices. | | Cap | **Solid** closes the front and back; **Hollow** leaves them open, showing the insides of the walls. | -| Bevel Shape | **None**, **Classic** (a straight chamfer), **Rounded** (convex quarter round), **Cove** (concave), **Step** (two steps) or **Ogee** (an S curve). Our own cross-sections. | +| Bevel Shape | **None**, **Classic** (a straight chamfer), **Rounded** (convex quarter round), **Cove** (concave), **Step** (two steps) or **Ogee** (an S curve). Our own cross-sections. After them come the custom bevels ([Custom bevels](#custom-bevels)). | | Width, Height | How far the bevel reaches across the face and along the depth (0–1,000 pt each). The height is limited to the depth (half of it on each side with Bevel both sides). | | Repeat, Space | The cross-section repeated 1–32 times across the width, with a share (0–90 %) of the width flat between repeats. | | Bevel Inside | The bevel carved into the shape (the front face shrinks) instead of added around it (the walls stand outside the art). | @@ -118,6 +118,28 @@ sharp point with the bevel outside, a narrow notch with it inside) whose miter w cut square across instead; at the other corners the miter is limited to four times the width. A bevel wider than a narrow part of the shape folds over itself. Each facet has a seam ([Seams](#seams)). +### Custom bevels + +The public [Add custom bevel paths](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/add-custom-bevel-paths.html) +page describes a custom bevel as one open path saved as a symbol in a bevels document, then listed in the Bevel menu. +VectorCraft keeps its custom bevels in `Bevels.vectorcraft`, a native document next to the preferences (none on the +web or in runs with `VECTORCRAFT_NO_PREFS`). The layout below is VectorCraft's own. + +- **Edit Bevels…** under Bevel Shape in the 3D and Materials panel (`threeD.bevels.edit`) opens the file, and first + creates it with one example bevel when it is missing. +- Each symbol whose art is one open path (alone or in groups of one member) is one bevel, named after the symbol and + listed after the built-in shapes in the Bevel Shape menus of Extrude & Bevel and Extrude & Bevel (Classic). +- The path runs from its first anchor, at the cap's edge, to its last, at the side wall. Across the page is across + the bevel's width and down the page is along its height, whichever way the path is drawn. Points past its ends are + held to them, curves are cut into straight lines, and a path is simplified to at most 64 points. +- A custom bevel takes Width, Height, Repeat, Space, Bevel Inside and Bevel both sides like the built-in shapes. +- The file is read when the app starts and again each time VectorCraft saves it; `threeD.bevels.reload` reads it + again. A file larger than 64 MB is not read, at most 256 symbols are read, and a symbol that is not one open path, + has more than 4,096 anchors, is cut into more than 8,192 straight lines, has ends that are not apart both across and down, or repeats an earlier name is listed + in `skipped` by `threeD.bevels.list`. +- An effect that uses a custom bevel keeps its name and a copy of its points, so the document draws it the same way + without the bevels file. + ## Inflate The shape puffed out like a cushion: its outline stays where the art is and the surface rises towards the @@ -619,7 +641,7 @@ is VectorCraft's own. ## Parameters (`effect.apply`, `effect.setParams`) `threeD.extrude`: `depth`, `twist`, `taper` (%), `cap`, `bevel` (`none`, `classic`, `rounded`, `cove`, `step`, -`ogee`), `bevelWidth`, `bevelHeight`, `bevelRepeat`, `bevelSpace` (%), `bevelInside`, `bevelBothSides`. +`ogee`, or `custom` with `bevelName` and `bevelProfile`; `{custom: name}` takes a bevel of the bevels file), `bevelWidth`, `bevelHeight`, `bevelRepeat`, `bevelSpace` (%), `bevelInside`, `bevelBothSides`. `threeD.inflate`: `depth`, `volume` (%), `bothSides`. All three take the view and lighting parameters Revolve uses: `rotationX`, `rotationY`, `rotationZ`, `perspectiveAngle` (degrees), `shade`, `lightColor` (`#rrggbb`, default `#ffffff`), `lightIntensity` (%), `lightRotation`, `lightHeight` (degrees), `lightSoftness` (%), `ambient` (%, to 200), `lightBehind`. Lengths are points and scale with the object (Scale Strokes & Effects). @@ -639,12 +661,13 @@ and [Create 3D objects](https://helpx.adobe.com/illustrator/desktop/special-effe pages, and the archived Extrude & Bevel option list (depth 0–2,000, cap on/off, bevel height, bevel extent in or out, perspective). No Adobe software, assets, presets or bevel shapes were used. -- **Materials** (base and Adobe Substance), shadows of lights after the first, and **ray-traced rendering** are not - built: shading uses directional lights, in the paint of the fill or stroke the solid is built for - ([Fills and strokes](#fills-and-strokes)), and only the first light casts a shadow ([Shadows](#shadows)). - Graphics map onto planar faces, Extrude & Bevel's side as one surface unrolled flat, Revolve's side and Inflate's - puffed faces only ([Graphics](#graphics)). -- The bevel shapes and their names are our own; custom bevel paths are not supported. +- **Materials** (base and Adobe Substance), graphics on Inflate, shadows of lights after the first, and + **ray-traced rendering** are not built: shading uses directional lights, in the paint of the fill or stroke the + solid is built for ([Fills and strokes](#fills-and-strokes)), and only the first light casts a shadow + ([Shadows](#shadows)). Graphics map onto planar faces, Extrude & Bevel's side as one surface unrolled flat, and + Revolve's side only ([Graphics](#graphics)). +- The bevel shapes and their names are our own. Custom bevels come from VectorCraft's own bevels file + ([Custom bevels](#custom-bevels)) and are cut into straight lines. - Visibility is a painter's algorithm: faces of a closed solid turned away are left out, and the rest are drawn back to front, with a flat cap or flat back turned toward the viewer drawn after all of them. Concave solids seen at steep angles can overlap wrongly; open (hollow) solids show both sides. Twisted walls and bevels are diff --git a/docs/type-parity.md b/docs/type-parity.md index d97f5bc105..111ee5d838 100644 --- a/docs/type-parity.md +++ b/docs/type-parity.md @@ -56,7 +56,7 @@ against Illustrator's public documentation; **estimated** unless noted. | Alt + numeric-keypad codes while typing (Windows: `Alt+0176` → °) | partial | #5108: on Windows the character Windows posts when Alt comes up after keypad digits is typed at the caret like any other, in the typing's undo step, and the keypad digits typed with Alt run no shortcut. With NumLock off the keypad keys (Insert, End, arrows, Clear, Home, Page Up/Down without the extended-key flag) count as digits too and don't move the caret (`windows_alt_codes` unit tests; neither NumLock on nor off has been tried on a Windows machine yet). `type.insert {code}` (Windows Alt+0 code, Windows-1252 for 128–159) and `{unicode}` (hex code point) insert a character by its code (`menucmds::insert_a_character_by_its_code`). macOS and Linux have no such system convention and egui reports a keypad digit as the top-row digit, so there it does nothing; a floating panel window doesn't receive the character | | Caret: the arrows and Delete step over whole clusters (Thai consonant with its marks, combining accents, emoji); Backspace removes one character | done | in text with right-to-left characters the arrows move in visual order and stop on both sides of a character drawn with no width, such as a zero width non-joiner | | Touch Type tool | done | moves, scales and rotates one character through its kerning, baseline shift, scales and rotation (`text.touchType`); a character with a preceding logical character on the same line can move along the line in either reading direction; the first logical character moves only up and down. Positive `dx` follows reading order. These direction rules are VectorCraft's choices. | -| Retype (identify fonts in outlines/images) | partial | Phase 1 (#4934): Type › Retype (`type.retype`) turns outlined glyphs back into point text when each shape is exactly a glyph of a loaded font, a font the document uses or a family named in `fonts` (the same up to uniform scale, rotation and translation): one object per line, in that font and size, at the same baseline and turn, with the first glyph's fill and stroke, in one undo step; shapes that match no font stay as they are and are reported. Window › Retype shows the Retype panel, which lists the fonts whose glyphs exactly match at least one selected outlined shape, comparing up to 96 loaded fonts with those of the document's live type first, ranked by how many shapes each matches, with samples, and sets a listed font on selected live type (`retype.find`, `type.retypeFonts`). Missing (phase 2): near or fuzzy matches (another version of the font, simplified outlines, glyphs merged into one path), opening the panel from the Type menu, the context menu and the Properties panel's Quick Actions, filtering the list by font source and favorites, installed fonts not yet loaded, area text for several lines, tracking, text in images. Public behaviour: [identify fonts](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/identify-fonts-using-retype.html), [apply to live text](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/apply-retype-suggested-fonts-to-live-text.html) | +| Retype (identify fonts in outlines/images) | partial | Phase 1 (#4934): Type › Retype (`type.retype`) turns outlined glyphs back into type when each shape is exactly a glyph of a loaded font, a font the document uses or a family named in `fonts` (the same up to uniform scale, rotation and translation): one object per line unless lines stack into one object as described below, in that font and size, at the same baseline and turn, with the first glyph's fill and stroke, in one undo step; shapes that match no font stay as they are and are reported. Evenly spaced glyphs keep their spacing as tracking (gaps one space wide stay word spaces when type draws them), and lines stacked at one leading and lined up at their starts, ends or centers become one area type object with that leading and alignment (VectorCraft's own rules, checked against the layout). Window › Retype shows the Retype panel, which lists the fonts whose glyphs exactly match at least one selected outlined shape, comparing up to 96 loaded fonts with those of the document's live type first, ranked by how many shapes each matches, with samples, and sets a listed font on selected live type (`retype.find`, `type.retypeFonts`). Missing (phase 2): near or fuzzy matches (another version of the font, simplified outlines, glyphs merged into one path), opening the panel from the Type menu, the context menu and the Properties panel's Quick Actions, filtering the list by font source and favorites, installed fonts not yet loaded, text in images. Public behaviour: [identify fonts](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/identify-fonts-using-retype.html), [apply to live text](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/apply-retype-suggested-fonts-to-live-text.html) | | Snap to Glyph | done | View › Snap to Glyph (`view.snapToGlyph`): with Smart Guides on, new point type and drawing tools snap to live-text baselines and glyph bounds, the corners of each glyph's box included, turning with rotated type (#5112; `guides::tests::a_drawn_point_lands_on_a_corner_of_a_glyphs_bounds`, `Targets::for_drawing`, `tools::text_tests::snap_to_glyph_lines_up_new_point_type_with_a_baseline`). With Alignment Guides on as well, and Snap to Grid and Snap to Pixel off, both ends of a Measure or Measure & Inspect drag snap to those guides and show them during the drag (`Targets::for_measure`, `xform::measure::tests::its_ends_land_on_glyph_guides_with_snap_to_glyph`). That the Measure tools take the guides is VectorCraft's choice; they leave out Anchor Point, which [the help page](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/snap-to-glyph.html) limits to the Pen tool and objects moved with the Selection tool. Character panel menu › Show Snap to Glyph Options: Baseline, x-height, Glyph Bounds, Proximity Guides, Angular Guides and Anchor Point each turn their guides on or off (`view.snapToGlyph.options`, all on by default; #4232), after a Snap to Glyph checkbox for View › Snap to Glyph; showing them scrolls the panel to them (#5273) | | Thai, Lao, Khmer, Myanmar: shaping (marks, reordering), lines broken between words, word-by-word caret and double-click | done | words found by ICU4X's line segmenter: dictionaries on the desktop, LSTM models on the web | | Middle Eastern: bidirectional layout, Paragraph Direction | done | PDF export keeps harakat and zero-advance Noto Arabic dot glyphs in one compatible batch per layout line, with per-glyph vertical offsets (#6309). `crates/pdf/src/tests/realtext.rs` (`mark_text_*`) checks decoded cluster mappings, mixed Arabic/Latin/digits, contour placement against outline export, vertical columns, differing path rotations and PDF/X-1a/3/4. Editable-text import still needs ActualText support (#6165); separately styled or differently rotated clusters and external viewer search/copy remain outside this export-only evidence. | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 1418ed4cf8..7d1d61416e 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-19 · **Change:** minor (Artboard tool: Shift held once a move or Alt-copy drag is under way keeps it to the level, upright or 45° line, #8580; scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); Canvas context menu: a right-click on a path offers Simplify… next to Smooth…, opening the Simplify slider, or the Simplify dialog kept for next time, as Object › Path › Simplify… does, #8344; scores and estimates unchanged; previously: a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: G12: Place: show progress window with Cancel for slow placed files exceeding 0.4 s, part of #5930; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: : selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: Layersselected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: Floating panels keep their window level while focus moves between the app's windows, so a press on one panel's bar no longer hands the keyboard to another, #6986; scores and estimates unchanged; previously minor: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); scores and estimates unchanged; previously: Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: Layers panel: an Alt-drag copies a row above or below itself, so the top layer dragged up, the bottom layer dragged down and a lone layer are copied, #8237; scores and estimates unchanged; previously: Layers panel: Alt over the list shows the copy cursor while rows or the selected-art square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Remove Background in the Contextual Task Bar, Properties › Quick Actions and the Control bar; previously minor: Ruler origin: the corner drag snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Outline view: images and gradient meshes are picked on what Outline draws, so a click inside them reaches the path behind, #6437; previously minor: a middle-click on a document tab closes it, #6506; previously minor: Blob Brush: a round tip's preview is the outline of the area it adds, round at both ends, as the stroke it commits (#4343); scores and estimates unchanged; previously:; ruler double-click adds a guide at the pointer, #5239; G5: Inventory Icons built-in symbol library (four built-ins); previously minor: files that record no units open in Preferences › Units › General, #5820; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Layers: Rename (`ui.rename`) opens the name field of the selected layer, group or object, #5324; Properties in Edit Artboards: Transform section above the Artboards section, #5219; scrubby labels: the Control bar's Stroke: and Opacity: links and the Properties panel's Stroke link scrub their fields, #4088; Properties: Quick Actions has Repeat Options for one selected repeat, #5181; Direct Selection: Shift-click picks several blend spine points, which drag together, #5285; Direct Selection: Cmd/Ctrl held lends the Selection tool and shows its bounding box, #3901; Join tool trims two crossing open paths and joins them at the crossing, #5844; Control bar: Paragraph: link and Align left/center/right while type is selected, #5372; shape tools: a press on the selection's centre point moves it and one in the rotate zone outside a box corner turns it, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-20 · **Change:** minor (Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid, #8363; scores and estimates unchanged; previously: Scissors shows the actual proposed cut point while hovering, using its existing snapping and cut target (#8655); scores and estimates unchanged; previously: Graphic Styles panel: right-click item context menu for tiles and rows with Options, Duplicate, Delete, Redefine, Break Link; scores and estimates unchanged; previously: Artboard tool: Shift held once a move or Alt-copy drag is under way keeps it to the level, upright or 45° line, #8580; scores and estimates unchanged; previously: Image Trace Ignore Color keeps the canvas View and stays armed on a missed pixel (#8068); Canvas context menu: a right-click on a path offers Simplify… next to Smooth…, opening the Simplify slider, or the Simplify dialog kept for next time, as Object › Path › Simplify… does, #8344; scores and estimates unchanged; previously: a tool drag held near an edge of the canvas scrolls the view, #8551; scores and estimates unchanged; previously: G12: Place: show progress window with Cancel for slow placed files exceeding 0.4 s, part of #5930; scores and estimates unchanged; previously: All Tools drawer: a tool the toolbar holds is dimmed in the readable dim text colour, not the disabled colour that was unreadable against the panel, and a hovered dimmed row takes the panel's darker fill so it stays readable, #8294; scores and estimates unchanged; previously: : selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged; previously: Layersselected Dimension extension-line color and weight in Properties (#7078; four focused UI regressions passed); scores and estimates unchanged; previously: Brush Options Key Color: restore canvas input for the existing one-shot pick, then resume the retained draft and previous tool (#8284; six full-app input regressions passed); scores and estimates unchanged; previously: Ellipse: Up/Down changes Anchors while drawing (#7840); scores and estimates unchanged; previously: Windows/Linux menu access keys and localized cues (#6596); previously: Backquote/~ arrow pattern nudges (#7717); scores and estimates unchanged; previously: Window > Toolbars > Compact Tools offers optional denser main Tools spacing (#7234); default layout, scores and estimates unchanged; previously: Direct Selection: Space during an ordinary path's handle drag repositions its anchor and handles, including a Pen loan (#7237, request 3 only; scores and estimates unchanged); previously: Floating panels keep their window level while focus moves between the app's windows, so a press on one panel's bar no longer hands the keyboard to another, #6986; scores and estimates unchanged; previously minor: Lock Guides: a selection marquee (Selection, Direct Selection, Group Selection, Enclosing Lasso) leaves out paths made into guides inside groups and compound paths too, as clicks do (#3074), so a group is no longer selected by a locked guide in it; an enclosing marquee measures a group without its locked or hidden guides, and Direct Selection takes no anchor or segment of a guide that can't be picked; a guide in a group still moves with its group (#8538); scores and estimates unchanged; previously: Production Preflight: output-aware fonts, text overflow, linked files and effective image resolution, clickable findings and automatic rechecking; scores and estimates unchanged; previously: Layers panel: an Alt-drag copies a row above or below itself, so the top layer dragged up, the bottom layer dragged down and a lone layer are copied, #8237; scores and estimates unchanged; previously: Layers panel: Alt over the list shows the copy cursor while rows or the selected-art square are dragged, #8217; scores and estimates unchanged; previously: Gradient panel: the add-stop strip under the ramp shows the white arrow with a plus on Windows and X11, #8241; scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: Eraser review: hidden Rasterize and Along/Across stroke rows do not block preserving visible gradients; scores and estimates unchanged; previously: Eraser review: ordinary Group/Layer paints and reproducible evaluated gradient placements are preserved; other placements retain existing fitting; scores and estimates unchanged; previously: Eraser: shared fill-only area cutting for fixed and varied tips and the Alt-drag marquee, #6582; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Remove Background in the Contextual Task Bar, Properties › Quick Actions and the Control bar; previously minor: Ruler origin: the corner drag snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Outline view: images and gradient meshes are picked on what Outline draws, so a click inside them reaches the path behind, #6437; previously minor: a middle-click on a document tab closes it, #6506; previously minor: Blob Brush: a round tip's preview is the outline of the area it adds, round at both ends, as the stroke it commits (#4343); scores and estimates unchanged; previously:; ruler double-click adds a guide at the pointer, #5239; G5: Inventory Icons built-in symbol library (four built-ins); previously minor: files that record no units open in Preferences › Units › General, #5820; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; numeric fields step on wheel hover without taking keyboard focus, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Selection QoL: marquee modes and visible feedback, #5313; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Layers: Rename (`ui.rename`) opens the name field of the selected layer, group or object, #5324; Properties in Edit Artboards: Transform section above the Artboards section, #5219; scrubby labels: the Control bar's Stroke: and Opacity: links and the Properties panel's Stroke link scrub their fields, #4088; Properties: Quick Actions has Repeat Options for one selected repeat, #5181; Direct Selection: Shift-click picks several blend spine points, which drag together, #5285; Direct Selection: Cmd/Ctrl held lends the Selection tool and shows its bounding box, #3901; Join tool trims two crossing open paths and joins them at the crossing, #5844; Control bar: Paragraph: link and Align left/center/right while type is selected, #5372; shape tools: a press on the selection's centre point moves it and one in the rotate zone outside a box corner turns it, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) > > Tech Circuit update (2026-11-14): three original procedural brushes; ten built-in brush libraries (G5). > @@ -20,6 +20,8 @@ ## Feature submission evidence +**Scissors cut-point preview (#8655):** A native point marker shows the anchor or position on a curve that the current Scissors click targets, including the existing snapping rules. Hovering changes no artwork; an ineligible or stale hover has no marker. Existing cut and Alt Add Anchor behavior are retained. Focused tool and Session regressions live in `crates/tools/src/draw2/anchor/tests.rs` and `crates/engine/tests/scissors_snap.rs`. Scores and estimates are unchanged. + Draft enhancement #5804: Preferences › File Handling can select a raster editor through the native picker, with a private draft outside engine preferences and generic dialog fields. OK saves it, Cancel discards it, and Reset restores PhotoCraft. With Use System Defaults off, a missing chosen editor falls back to PhotoCraft, then the system default; validation and launch failures are reported. Control/MCP and synthetic input cannot choose an application or run external Edit Original. Web behavior, parity scores and estimates are unchanged; macOS/Linux smoke tests remain pending. **2026-11-09 revision:** draft implementation and regression coverage for #5804; no parity rescore. @@ -79,6 +81,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | 2026-11-16 | minor | Gradient panel: the strip under the ramp, where a click adds a stop, shows the white arrow with a plus on Windows and X11, where the system copy cursor showed as the plain arrow (#8241). Scores and estimates unchanged. | | 2026-11-13 | minor | Layers: selected guide rows stay highlighted after the pointer leaves (#7344); scores and estimates unchanged. | | 2026-11-13 | minor | Pencil cursors: the continuation cursor (a short rising line) shows over an open end of a selected path before any press, freehand too, and while a continuing stroke nears another selected path's open end it connects to; the straight-line cursor is a short level line; a continued path, a straight line too, shows the closing cursor and closes within Close Paths When Ends Are Within of its other end, and with Alt at the release. Scores and estimates unchanged. | +| 2026-11-19 | minor | Graphic Styles: right-click item context menus for tiles and rows (Options…, Duplicate, Delete, Redefine, Break Link); regression tests in crates/ui-egui/src/panels/graphic_styles.rs; scores and estimates unchanged. | | 2026-11-15 | minor | G12: Swatches item menus validated in all five views: 39 focused tests passed, regression fails without the menu hooks, rendered list/thumbnail layouts inspected, and fresh local deep CodeRabbit review found zero issues. Full workspace CI passed on Linux/WSL on the merged branch (all 13 gates), including the test-helper correction for the upstream compile error tracked in #7727; native Windows full CI has two unchanged engine-test failures. Scores and estimates unchanged. | | 2026-11-13 | minor | Graphic Styles: in a panel made taller the list fills the space above the footer instead of stopping at 220 pt (#2992; `the_list_fills_a_tall_panel_above_its_footer` in `crates/ui-egui/src/panels/graphic_styles.rs`). Scores and estimates unchanged. | | 2026-11-13 | minor | Library panels (swatch, Color Book, brush, symbol and graphic style libraries): in a panel made taller the list fills the space above the footer instead of scrolling inside 220 or 280 pt (#2992; `the_list_fills_a_tall_panel_above_its_footer` in `crates/ui-egui/src/panels/library_panel/tests.rs`). Scores and estimates unchanged. | @@ -191,6 +194,7 @@ tools, never checked side by side) isn't captured row by row. | Node-editing cursors: Direct Selection's white arrow with a hollow or filled square over an anchor (path unselected or selected); the Reshape Segment cursor over a curved segment (Direct Selection, Anchor Point, the Pen with Alt); the Anchor Point caret for the Pen with Alt; Group Selection's plus (also Direct Selection with Alt); a filled arrow while dragging that turns hollow on a snap; a double arrowhead for an Alt-drag copy | partial | as the public manual describes them, drawn in code; no cue over handles (none documented) | | Anchor Point and Curvature tools' own cursors | done | the caret on the anchor it converts; the pen nib with a curve badge | | Scissors hover and cuts use the Pen's path, alignment, intersection and anchor snapping (#6470) | implemented | Existing Smart Guides, Snap to Point, pixel and grid options apply; Pixel Preview turns off Smart Guides. Alt still adds an anchor without cutting, and a cut still leaves one new endpoint selected. Headless regressions: `crates/tools/src/draw2/anchor/tests.rs` and `crates/engine/tests/scissors_snap.rs`. | +| Scissors cut-point preview (#8655) | implemented | Native marker at the actual anchor or curve target; current snapping, cut and Alt Add Anchor behavior retained. `crates/tools/src/draw2/anchor/tests.rs`, `crates/engine/tests/scissors_snap.rs`. | | Free Transform's Cmd/Ctrl side-shear cursor | done | two arrows passing along the side (ShearH, ShearV), instead of the resize arrow across it | | Live Paint Bucket cursors | partial | a filled bucket over a face a click fills, a brush over an edge it paints, an empty bucket where it paints nothing, following Paint Fills, Paint Strokes and Shift; the Eyedropper with Alt; the crosshair with Use Precise Cursors. No cursor swatch preview | | Cursors of their own for Lasso, Magic Wand, the freehand tools, Shaper, Measure, Print Tiling, the symbolism tools, vertical type, Scissors (over a segment and away), Mesh and Puppet Warp | partial | each tool returns its own cursor and Use Precise Cursors turns them into the crosshair; until they're drawn they borrow the crosshair, the I-beam, the Pen's add cursor or not-allowed | @@ -201,7 +205,7 @@ tools, never checked side by side) isn't captured row by row. | Busy cursor during long operations | done | Background open, save and export show the system progress cursor (gap G1) | | Each anchor snaps to Smart Guides and construction angles | done | `DrawSnap` | | Curvature tool: click/drag points, double-click or Alt-click for a corner, temporary Direct Selection, point conversion | partial | circular point markers without direction handles or duplicate markers, Anchor Size and Hide Edges regression-tested (#1236, in part); curve geometry: each stretch of three points follows the circle through them (handles along its tangent, chord/(3·cos²(α/2)) long, shorter in a turn tighter than 30°), open ends curving in, the same rule for the rubber band, dragged, inserted and converted points (#1236, in part); neighbours of a point dragged on an existing path keep their tangents, and modifiers requested in #975 remain | -| Quick Pen tool: straight lines, continuous arcs and sharp-corner arcs, Alt/Option to switch action, C to flip an arc, `[` / `]` for its size, Alt+P / Option+P, close on the first point, continue from an end, Escape to end ([help page](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/draw-with-quick-pen-tool.html), [shortcuts](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/quick-pen-tool-keyboard-shortcuts.html)) | partial | `path.quickPen` and the tool in `crates/tools/src/quickpen.rs`, in the Pen tool's group (#2660). Not yet: the on-canvas toolbar with its More menu, dragging a path's ends to change a line's or arc's length, Ctrl+scroll for the arc size, and editing and deleting with the tool | +| Quick Pen tool: straight lines, continuous arcs and sharp-corner arcs, Alt/Option to switch action, C to flip an arc, `[` / `]` for its size, Alt+P / Option+P, close on the first point, continue from an end, Escape to end ([help page](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/draw-with-quick-pen-tool.html), [shortcuts](https://helpx.adobe.com/illustrator/web/add-and-edit-artwork/draw-and-edit-paths/quick-pen-tool-keyboard-shortcuts.html)) | partial | `path.quickPen` and the tool in `crates/tools/src/quickpen.rs`, in the Pen tool's group (#2660); the on-canvas toolbar with its actions, Flip Arc and its More menu (Hide Toolbar and Reset Toolbar Position, and VectorCraft's own Pin Toolbar Position) in `crates/ui-egui/src/canvas/quick_pen_bar.rs`. Not yet: dragging a path's ends to change a line's or arc's length, Ctrl+scroll for the arc size, and editing and deleting with the tool | | Icon-strip flyout resizing (#5713) | done | Canvas-side edge and bottom; user size persists after reopening and workspace restore; Glyphs and Artboards pointer/cursor regression | | Icon-strip flyout resizing from the top (storytold/craft-libs#1094) | done | Top edge (a 4 pt band over the tab strip) and the canvas-side top corner; the bottom and the icon-column edge stay; the moved top persists after reopening and workspace restore; `an_icon_flyout_grows_upward_from_its_top_edge_and_free_corner` | | Graphic Styles list fills a taller panel (#2992) | done | Docked, floating or in a resized flyout, the list takes the height above the panel's footer, as the Artboards list does; outside a sized panel it stays 220 pt; `the_list_fills_a_tall_panel_above_its_footer` | @@ -253,7 +257,7 @@ tools, never checked side by side) isn't captured row by row. | Drag a curved segment to bend it, a straight one to move its anchors | done | | | Drag by an anchor of a path selected whole moves the whole path; Alt-drag by an anchor or a segment copies it, Alt toggles the copy during the drag, and the copy snaps by the anchor pressed, onto the original too | done | #1104 | | Handles shown are the handles that drag; tolerance from Selection & Anchor Display | done | #494 | -| Drag a handle with Shift (45° about its anchor), Alt (move one handle alone), Space (ordinary paths: move its anchor and both handles) | done | handles snap to smart guides; handle and anchor drags no longer stall when the pointer leaves and re-enters the window, and a move in the release's frame lands (#834); Space pressed during an ordinary path's handle drag moves its owning anchor and both handles; releasing Space while keeping the mouse down resumes handle adjustment. This also applies while Cmd/Ctrl lends Direct Selection to the Pen, which then continues the same path (#7237, request 3 only) | +| Drag a handle with Shift (45° about its anchor), Alt (move one handle alone), Control/Command added mid-drag (mirror the opposite handle), Space (ordinary paths: move its anchor and both handles) | done | handles snap to smart guides; handle and anchor drags no longer stall when the pointer leaves and re-enters the window, and a move in the release's frame lands (#834); #7842: temporary mirroring covers paths, transformed type on a path and blend spines, preserves the anchor mode and the pre-press selection-tool loan, and keeps Alt independent priority; the Control/Command press that lends Direct Selection while another tool, such as the Pen, is chosen does not mirror until it is let go and pressed again; `crates/engine/tests/direct_handle_mirror.rs`; Space pressed during an ordinary path's handle drag moves its owning anchor and both handles; releasing Space while keeping the mouse down resumes handle adjustment. This also applies while Cmd/Ctrl lends Direct Selection to the Pen, which then continues the same path (#7237, request 3 only) | | Show handles when multiple anchors are selected; Highlight anchors on mouse over; anchor and handle size | done | Preferences › Selection & Anchor Display | | Convert selected anchors to corner/smooth from the Control bar and Properties | done | | | Cut path at selected anchors, Remove Anchor Points, Delete removes segments | done | Open-path anchor Delete removes adjoining segments without bridging the gap; #3380 (deletion only): disconnected survivors of an ordinary contour become independent selected sibling objects, while multi-subpath paths and compound members stay intact; targeted core and full-frame Delete/Backspace regressions pass for survivor selection and Undo/Redo. Explicit Remove Anchor Points keeps its reconnect/refit behavior; #1278: segment Delete preserves neighboring edges and endpoint anchors; a second Delete removes all selected surviving objects; explicit anchor Delete retains its behavior; #1674: Delete removes every selected anchor of a closed path and objects selected whole along with them, and keeps the surviving objects selected; #2241: Remove Anchor Points then selects the next anchor along the path (the one before at an open end), so it can be run again without picking each anchor | @@ -296,6 +300,7 @@ tools, never checked side by side) isn't captured row by row. | Ruler origin: corner drag with preview, snapped as a drawn point is (Smart Guides, Snap to Point and the ruler guides, pixels, the grid), double-click reset to the active artboard, relative X/Y fields, native save/reopen | done | #1212; `document.setRulerOrigin`, `document.resetRulerOrigin`; geometry and command coordinates stay absolute | | Ruler guides as Layers rows: shown, hidden, locked and deleted with their layer; rows dragged to another layer; each row's own eye and lock; a row dropped on the trash deletes its guide; selected guide rows keep their highlight away from the pointer (#7344); a plain click on another row lets go of the guide | done | `guide.setLayer`; guides from older files go on a layer; `layer.setProps` on a guide's id hides or locks it alone; Object › Lock/Hide › Selection, Unlock All and Show All reach guides; `guide.remove {indexes}`; #7340 | | Objects made into guides: drawn in the guide colour and style of Preferences; Lock Guides locks them too (no select, move or delete), in groups as well: a marquee leaves them out, so it does not take their group, and they still move with their group; a dragged selection snaps to ruler guides with Smart Guides on, by the nearest point of the path when pressed on its stroke or beside its edge, so the path lands exactly on the guide | done | #1534 (#1543, #1583); #3701; #8538 | +| View › Trim View hides the ruler guides, the guide paths and the grid while it is on, and View › Guides › Show/Hide Guides and View › Show/Hide Grid are greyed out until it is off (#8363) | done | As public forum threads describe ([trim view hides guides](https://community.adobe.com/t5/illustrator-discussions/trim-view-hides-guides/td-p/14066140), [guides greyed out](https://community.adobe.com/t5/illustrator-discussions/guides-greyed-out/m-p/11132728)). The Show/Hide choices are kept and come back as they were; the items stay greyed in the canvas context menu and the Properties panel's buttons, and refuse to run from keys, the palette or MCP. Hidden guides are neither snapped to nor picked, as with Hide Guides, and a selected guide path is deselected. The rulers stay as they are, but a drag or double-click on them makes no guide, since it could not be seen: no preview line, no undo step, a status message instead. `menus::tests::trim_view_greys_out_show_guides_and_show_grid`, `canvas::tests::{trim_view_hides_the_guides_and_the_grid, trim_view_deselects_selected_guide_paths, trim_view_makes_no_guide_from_the_rulers}` | | A selected ruler guide's X or Y in the Transform panel; typing a value moves it | not scored | #1659 (part of #1597); several guides move together; not in Properties or the Control bar. Not established by the documentation we could find: the help pages on guides, rulers and the Transform, Control and Properties panels (read again on 2026-10-14) don't describe it, and the one public statement is a user's [community answer](https://community.adobe.com/questions-652/adding-a-new-custom-guide-785586), which is not documentation. Kept as a convenience pending the owner's decision; no parity claim | | Alt swaps a ruler guide's orientation while dragging | missing | Alt-drag copies the selected guides ([Use rulers](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/use-rulers.html)); `guide.move` `{copy: true}` | | Alt swaps a new ruler guide's orientation while dragging | done | Both rulers; preview, snapping and final placement follow the current modifier ([public shortcut reference](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)). | @@ -402,7 +407,7 @@ Cmd/Ctrl+/ (`appearance.addFill`) and Cmd/Ctrl+Alt+/ (`appearance.addStroke`) ad selected objects, as the Appearance panel's Add New Fill and Add New Stroke buttons do. ~110 distinct modified shortcuts on menu commands plus single-key tool shortcuts for the default toolbar -(`crates/tools/src/catalog.rs`), a shortcut editor with chords, and saved sets. Cmd/Ctrl+Alt+L (`ui.newLayer`) opens Layer Options for a new layer, as an Alt-click on the Layers panel's New Layer button does, and Cmd/Ctrl+L still adds a layer without the dialog. F8 (`ui.symbolOptions`) opens Symbol Options for a new symbol made from the selection, as the Symbols panel's New Symbol button does. Rename (`ui.rename`, in the shortcut editor with no default key; a VectorCraft addition, #5324) opens the Layers panel's name field on the selected layer, group or object's row, as double-clicking its name does: Enter renames it in one undo step and Escape keeps the name; several selected objects, or a row the panel's search, filter or Show Layers Only hides, is refused with a message. Not yet diffed item by item +(`crates/tools/src/catalog.rs`), a shortcut editor with chords, and saved sets. Cmd/Ctrl+Alt+L (`ui.newLayer`) opens Layer Options for a new layer, as an Alt-click on the Layers panel's New Layer button does, and Cmd/Ctrl+L still adds a layer without the dialog. F8 (`ui.symbolOptions`) opens Symbol Options for a new symbol made from the selection, as the Symbols panel's New Symbol button does. Rename (`ui.rename`, in the shortcut editor with no default key; a VectorCraft addition, #5324) opens the Layers panel's name field on the selected layer, group or object's row, as double-clicking its name does: Enter renames it in one undo step and Escape keeps the name; several selected objects, or a row the panel's search, filter or Show Layers Only hides, is refused with a message. Color Picker… (`ui.colorPicker`) is in the shortcut editor with no default key; a key assigned to it opens the Color Picker for the Fill or Stroke proxy in front, with or without a selection and with no document open. Not yet diffed item by item against Illustrator's published default shortcut list; estimated ~70% of it. Remaining: other panel shortcuts, the type shortcuts (tracking/kerning/leading/baseline steps with Alt/Shift), and selection shortcuts in the Layers panel. The shortcut editor also lists the commands that are in no menu but run without parameters (Edit › Duplicate, @@ -493,7 +498,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Info panel follows the tool in use: W and H show the change in x and y, with the distance and the angle, while the selection moves, the Gradient tool draws a vector or a Pen drag pulls out an anchor's handle; the Scale tool's percentages; the center and angles of a Rotate, Reflect or Shear tool drag; the Zoom tool's magnification; the Paintbrush's brush. W and H follow Use Preview Bounds, several selected objects show only the paint and type they share, and Show Options names a tint or a gradient swatch | done | `info.readout`; `Tool::readout`; behavior from the Info panel overview in the [archived user guide](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=76); number formats, the rows shown between drags and the Direct Selection and Group Selection readouts are VectorCraft's own | | Make Compound Path on a group (such as outlined type) keeps its backmost path's paint; compound paths joined into one keep their holes | done | #1537 | | Symbol libraries: Window › Symbol Libraries (Basic Shapes, UI Frames, Map Markers, Inventory Icons, Skill Icons, User Defined, Other Library…, Save Symbols…) and the Symbols panel's Symbol Libraries Menu button and its menu's Open Symbol Library / Save Symbol Library…; a click on a library symbol adds it to the document's Symbols (one undo step, it becomes the current symbol), Shift/Cmd-clicks select for Add to Symbols, and a symbol dragged onto the canvas is added and placed where it is dropped | done | [public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-or-import-symbol-libraries.html), [Symbols panel options](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html), [placing from a library](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-and-place-symbols.html); `window.symbolLibrary`, `window.symbolLibrary.other`, `ui.saveSymbolLibrary` (dialog `saveSymbolLibrary`), `window.userSymbolLibrary1`…`10`; `panels::tests_symbol_libraries`; five built-in libraries (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons, Skill Icons; original, generated in code) | -| Brush libraries: Window › Brush Libraries (Art Ribbons, Ink and Wash, Calligraphic Nibs, Pressure Sensitive, Bristle Brushes, Pattern Borders, Scatter Shapes, Stipple, Game Trails, Energy Beams, Dry Media, Tech Circuit, Engraving, Arrows, User Defined, Other Library…, Save Brushes…) and the Brushes panel's Brush Libraries Menu button and its menu's Open Brush Library / Save Brush Library…; a click on a library brush adds it to the document's Brushes (one undo step, it becomes the current brush, and selected paths take it in the same step), Shift/Cmd-clicks select for Add to Brushes, a brush dragged onto a path is added and applied to it and one dragged onto the Brushes panel is added; thumbnails render with the library's patterns and symbols | done | [public source](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/create-new-brush-libraries.html), [import brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/import-brushes-from-brush-libraries-or-other-files.html), [Brushes panel overview](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/brushes-panel-overview.html); `window.brushLibrary`, `window.brushLibrary.other`, `ui.saveBrushLibrary` (dialog `saveBrushLibrary`), `window.userBrushLibrary1`…`10`; `panels::tests_brush_libraries`; fourteen built-in libraries (original, generated in code) | +| Brush libraries: Window › Brush Libraries (Art Ribbons, Ink and Wash, Calligraphic Nibs, Pressure Sensitive, Bristle Brushes, Pattern Borders, Decorative, Scatter Shapes, Stipple, Game Trails, Energy Beams, Dry Media, Tech Circuit, Engraving, Arrows, User Defined, Other Library…, Save Brushes…) and the Brushes panel's Brush Libraries Menu button and its menu's Open Brush Library / Save Brush Library…; a click on a library brush adds it to the document's Brushes (one undo step, it becomes the current brush, and selected paths take it in the same step), Shift/Cmd-clicks select for Add to Brushes, a brush dragged onto a path is added and applied to it and one dragged onto the Brushes panel is added; thumbnails render with the library's patterns and symbols | done | [public source](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/create-new-brush-libraries.html), [import brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/import-brushes-from-brush-libraries-or-other-files.html), [Brushes panel overview](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/brushes-panel-overview.html); `window.brushLibrary`, `window.brushLibrary.other`, `ui.saveBrushLibrary` (dialog `saveBrushLibrary`), `window.userBrushLibrary1`…`10`; `panels::tests_brush_libraries`; fifteen built-in libraries (original, generated in code) | | Brushes panel menu › Options of Selected Object…: changes the selected brushed paths' brush settings on those paths only, leaving the brush and its other strokes as they are; the brush type's options dialog opens without the Name row (and without an art brush's scale and direction options or a pattern brush's tiles), and OK sends only the values changed in it | done | [Modify brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/modify-brushes.html), [Brushes panel overview](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/brushes-panel-overview.html); `brush.objectOptions`, `ui.brushObjectOptions`; which fields a path can set is VectorCraft's own choice (calligraphic, scatter, art and pattern brushes; not bristle); `options_of_selected_object_*` tests in `crates/engine/src/tests/brushsym.rs` and `crates/ui-egui/src/dialogs/brush_options/tests.rs`, brush tests in `crates/brush/src/tests.rs` | | Symbols panel: New Symbol opens Symbol Options (Name) before making the symbol; Alt-click skips it | partial | #1560 (#1566); Registration 9-point grid in Symbol Options (`symbol.new` / `symbol.place`); Export Type (Graphic / Movie Clip) and Enable Guides for 9-Slice Scaling (scaled instances keep their corners; in symbol editing mode the guides are drawn over the art and the Selection tool drags them); Symbol Type (Dynamic Symbol / Static Symbol, new symbols dynamic; #4938); Align to Pixel Grid (`alignToPixelGrid` on `symbol.new` / `symbol.options`: the art snaps at the symbol's natural size and instances at that size stay on whole points; [Aligning symbols to pixel grid](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=28)) | | Dynamic symbols: an instance changes the fill, stroke, opacity and blend of objects in its symbol's art and stays linked; Reset in the Properties panel's Quick Actions and the Symbols panel menu (Reset Symbol Instance) | partial | #4938; `symbol.instance.setAppearance` (by child-index path) and `symbol.instance.reset`; redefining keeps the changes, Break Link bakes them; Direct Selection of a path, compound path or type object inside an instance, with the Fill/Stroke controls setting its solid fill or stroke, is on canvas; on-canvas editing beyond a solid fill and stroke, and `.ai` read and write, remain | @@ -506,6 +511,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Canvas context menu | done | Right-clicking type opens the canvas menu, with Bullets and Numbering and Spelling. Right-clicking a path offers Object › Path › Simplify… and Smooth…, each opening what its menu item opens (#8344). Artboard rows, library groups and items, the rulers and floating toolbar grips have menus too. Gaps: other panels have none | | Layers panel row context menu | done | Right-clicking a layer/group/object row shows a context menu with Options…, Duplicate, Delete, Lock/Hide Others, Locate Object, and Collect for Export; right-clicking a ruler guide row shows Hide/Show, Lock/Unlock, Release Guides, Delete and Locate Object; right-clicking a blend spine row shows Select, Blend Options…, Reverse Spine, Reverse Front to Back, Expand, Release and Locate Object (#8592). | | Swatches item context menu (G12) | done | List and thumbnail items offer Swatch Options…, Duplicate Swatch and Delete Swatch for the clicked item. Right-click selects without applying paint; reserved/missing items disable actions. All 39 Swatches tests pass, including all five views and Undo; the regression fails with the menu hooks removed. Rendered headless menus inspected. Full workspace CI passed on Linux/WSL on the merged branch (all 13 gates), including the test-helper correction for the upstream compile error tracked in #7727; native Windows full CI has two unchanged engine-test failures. | +| Links panel row context menu (G12) | done | Right-clicking a link row presents an item context menu offering Relink…, Go To Link, Update Link, Edit Original, Show in Folder, and Embed Image / Unembed…; right-clicking an unselected row selects it first, preserving selection if already part of a multi-selection. Tests: `panels::tests_links::right_click_context_menu_in_links_panel`. | | SVG Interactivity panel: JavaScript for each object's events and the document's linked JavaScript files, written to SVG and read back as text | done | `svgInteractivity.*`, `ui.javascriptFilesDialog` | | Retype panel | partial | Window › Retype lists the fonts whose glyphs exactly match at least one selected outlined shape, ranked by how many shapes each matches, ten and then five more, with samples in three sizes and the user's own text; a click sets the font on selected live type (`retype.find`, `type.retypeFonts`). Opening it from the Type menu, the context menu and the Properties panel, filtering by font source and favorites, near matches, installed fonts not yet loaded and text in images are missing (#4934) | | Comments, Version History panels | missing | cloud features (out of scope) | @@ -620,6 +626,8 @@ before release (#6373). [Paint faces and edges](https://helpx.adobe.com/illustra | Date | Change | Summary | |---|---|---| +| 2026-11-19 | minor | View › Trim View hides the ruler guides, guide paths and the grid while it is on and greys out Show/Hide Guides and Show/Hide Grid until it is off; the choices come back as they were and the rulers stay, though dragging or double-clicking them makes no guide meanwhile (#8363). Scores and estimates unchanged. | +| 2026-11-19 | minor | Scissors previews its actual anchor or curve cut point with a native point marker while hovering, retaining existing snapping, Alt Add Anchor and cut behavior (#8655). Scores and estimates unchanged. | | 2026-11-19 | minor | Artboard tool: Shift held once a move or an Alt-drag copy of an artboard is under way keeps it to the level, upright or 45° line from General › Constrain Angle, and snaps slide it along that line; a Shift-press still draws an artboard inside another or marquee-selects (#2497), #8580. Scores and estimates unchanged. | | 2026-11-19 | minor | Canvas context menu: a right-click on a path, a group of paths or a compound path offers Simplify… between Average… and Smooth…, in the Path menu's order, opening the Simplify slider at the Auto-Simplify level, or the Simplify dialog on its kept settings, as Object › Path › Simplify… does (#8344). Scores and estimates unchanged. | | 2026-11-19 | minor | G12: Place: show progress window with Cancel for slow placed files exceeding 0.4 s (part of #5930, `file.cancelPlace`); indeterminate moving bar, Cancel (Esc) leaves the document unmodified without undo steps; scores and estimates unchanged. | @@ -640,6 +648,7 @@ before release (#6373). [Paint faces and edges](https://helpx.adobe.com/illustra | 2026-11-12 | minor | Floating panels: the app counts as inactive only once none of its windows has had focus for 0.25 s, so focus moving between its own windows (a press on a panel's bar) leaves the panels' OS windows at their level; with two floating panels, a press on one panel's bar no longer hands the keyboard to the other or leaves both behind the main window (#6986). `focus_moving_between_the_apps_windows_leaves_the_palettes_on_top`; scores and estimates unchanged. | | 2026-11-14 | minor | Direct Selection: Space during an ordinary path's direction-handle drag moves its anchor and both handles; releasing Space resumes handle adjustment, and a Cmd/Ctrl loan preserves Pen continuation (#7237, request 3 only). Handle-hover labels remain open; scores and estimates unchanged. | | 2026-11-12 | minor | Numeric fields: a focus click released more than 1 pt from its press keeps the caret; a tap within 1 pt still selects the whole value (#6659, follow-up to #1326). Scores and estimates unchanged. | +| 2026-11-19 | minor | Graphic Styles: right-click item context menus for tiles and rows (Options…, Duplicate, Delete, Redefine, Break Link); regression tests in crates/ui-egui/src/panels/graphic_styles.rs; scores and estimates unchanged. | | 2026-11-15 | minor | G12: Swatches item menus validated in all five views: 39 focused tests passed, regression fails without the menu hooks, rendered list/thumbnail layouts inspected, and fresh local deep CodeRabbit review found zero issues. Full workspace CI passed on Linux/WSL on the merged branch (all 13 gates), including the test-helper correction for the upstream compile error tracked in #7727; native Windows full CI has two unchanged engine-test failures. Scores and estimates unchanged. | | 2026-11-12 | minor | Remove Background for a selected image in the Contextual Task Bar, Properties › Quick Actions and the Control bar, which runs at once with its defaults. Scores and estimates unchanged. | | 2026-11-12 | minor | Live Paint Bucket fills faces crossed in one drag (#6373). Scores and estimates unchanged. |