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/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 8e45364857..060afd92a8 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 0ac1bbe416..df091cc719 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)) { @@ -168,14 +177,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), @@ -351,12 +412,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 74636721b8..e2a7b551a3 100644 --- a/crates/effects/src/solids/tests.rs +++ b/crates/effects/src/solids/tests.rs @@ -1594,6 +1594,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..5afdf15cc3 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; 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/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/trace.rs b/crates/engine/src/cmd/buildcmds/trace.rs index f0f2557ded..765c6ca77e 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")) } @@ -649,7 +650,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..7c0be8255c 100644 --- a/crates/engine/src/cmd/clipboard.rs +++ b/crates/engine/src/cmd/clipboard.rs @@ -109,6 +109,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 @@ -484,6 +487,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..f7b5de29dd 100644 --- a/crates/engine/src/cmd/clipboard/resources.rs +++ b/crates/engine/src/cmd/clipboard/resources.rs @@ -1161,6 +1161,7 @@ impl Clipboard { char_styles: pick(Res::CharStyle, &src.char_styles), para_styles: pick(Res::ParaStyle, &src.para_styles), brushes, + set_densities: src.set_densities_of(&nodes), nodes, ..Default::default() } 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/edit.rs b/crates/engine/src/cmd/edit.rs index 5e0231228b..f5ee63f167 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 { 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..3f9d749a6c 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(), } } } 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/paint.rs b/crates/engine/src/cmd/paint.rs index 071c5f9862..56d9f1379f 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()?; @@ -378,11 +379,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 +755,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. 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..45df90f0f1 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -746,5 +746,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..0bce618fa3 100644 --- a/crates/engine/src/cmd/recolor.rs +++ b/crates/engine/src/cmd/recolor.rs @@ -130,7 +130,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 +262,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 +279,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 +287,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 +406,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 } => { @@ -2051,7 +2058,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..daba176fb3 100644 --- a/crates/engine/src/cmd/stroke.rs +++ b/crates/engine/src/cmd/stroke.rs @@ -445,7 +445,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() { 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..cdf1d441cd 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) { diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 1e9ef6d699..12851cc7bb 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)>, @@ -160,6 +164,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 +335,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..7c80262dbb 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, @@ -89,6 +90,7 @@ impl Session { 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 +139,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..158bb02c87 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. @@ -9491,9 +9550,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/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/recolor.rs b/crates/engine/src/tests/recolor.rs index b2664a9682..9767aaec3e 100644 --- a/crates/engine/src/tests/recolor.rs +++ b/crates/engine/src/tests/recolor.rs @@ -1422,6 +1422,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..fe38a92a49 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; } _ => {} @@ -1309,9 +1326,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 +1376,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 +1415,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 @@ -1519,6 +1578,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 +1591,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/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 01da0fa29f..931512640a 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1012,6 +1012,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…", @@ -1573,7 +1579,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} 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; 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}", ), ( "ui.savePdfDialog", 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 0ea03dcbf9..19905110ce 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 78d2fcdcbe..917290bff3 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/direct.rs b/crates/tools/src/direct.rs index e1c0c88dae..c14dfd4c2b 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]); } 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/lib.rs b/crates/tools/src/lib.rs index f06c5cd5a6..9057b33cc3 100644 --- a/crates/tools/src/lib.rs +++ b/crates/tools/src/lib.rs @@ -230,6 +230,11 @@ pub trait Tool: Send { 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/settings.rs b/crates/tools/src/settings.rs index 4f4ac487e2..3d3f2a3873 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"]), 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/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 128134425e..b4a8eee2a0 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -359,8 +359,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 { @@ -1150,6 +1152,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 @@ -1173,27 +1241,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/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 35c9fd3737..5f5741fc9c 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. 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/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 1f34a72f9a..12e0001944 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -629,6 +629,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 +653,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/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/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_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/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 0574bc31a6..cc3896cf95 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -586,6 +586,7 @@ 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 Опции на цветното колело @@ -1960,6 +1961,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 Пейзаж @@ -3136,6 +3142,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 Нулиране на редовете към цветовете на илюстрацията @@ -3273,9 +3284,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 го запазва, но все още не използва временни дискове. @@ -3287,13 +3303,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. Най-многото стъпки за отмяна, които всеки документ пази; по-малко число премахва най-старите стъпки, когато щракнете върху ОК. Стъпки може да отпаднат и по-рано, ако заемат твърде много памет. @@ -3312,6 +3330,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, ако е инсталиран. @@ -3326,7 +3347,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. Стойностите по подразбиране се прилагат, когато щракнете върху ОК в Настройки. Отказ там запазва текущите ви настройки. @@ -3557,6 +3577,7 @@ digits Malayalam Малаялам Recent Commands Последни команди No recent commands Няма последни команди Type to search commands, tools, panels and effects Въведете текст, за да търсите команди, инструменти, панели и ефекти + Clear Recent Commands Изчистване на последните команди Search commands Търсене на команди Search Commands… Търсене на команди… Secondary Вторичен @@ -4755,6 +4776,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` трябва да бъде масив @@ -7892,6 +7915,20 @@ breakText Glyphs Глифи Flower Цвете Tree Дърво Mountain Планина + 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 e8ae8bb0f1..dc518a0701 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -819,6 +819,7 @@ {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 @@ -4323,6 +4324,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 @@ -4551,6 +4557,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 @@ -4644,6 +4655,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… @@ -4763,9 +4775,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. @@ -4777,13 +4793,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. @@ -4802,6 +4820,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. @@ -5203,6 +5224,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 @@ -7947,6 +7970,20 @@ shape Open Otvoren Flower Cvijet Tree Drvo Mountain Planina + 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 0a101f8007..3421cc3902 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -887,6 +887,7 @@ 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 @@ -2499,6 +2500,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 @@ -3979,6 +3985,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 @@ -4131,9 +4142,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. @@ -4145,13 +4161,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. @@ -4170,6 +4188,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. @@ -4184,7 +4205,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. @@ -4772,6 +4792,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 @@ -6146,6 +6167,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 @@ -7135,6 +7158,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 @@ -7242,7 +7269,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ó @@ -8928,6 +8958,20 @@ breakText Glyphs Glifs Flower Flor Tree Arbre Mountain Muntanya + 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 e4afdf7f2d..67cffc2657 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -831,6 +831,7 @@ {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 @@ -4432,6 +4433,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 @@ -4660,6 +4666,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é @@ -4753,6 +4764,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í… @@ -4872,9 +4884,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á. @@ -4886,13 +4902,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. @@ -4911,6 +4929,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. @@ -5498,6 +5519,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 @@ -5907,6 +5930,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 @@ -6832,7 +6859,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 @@ -10752,6 +10782,20 @@ breakText Glyphs Glyfy Flower Květina Tree Strom Mountain Hora + 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 5f68361aa2..5328486061 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 @@ -3528,6 +3531,7 @@ 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 @@ -6886,6 +6890,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 +7114,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 +7210,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 +7330,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 +7348,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 +7375,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. @@ -8079,6 +8103,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 +9137,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 @@ -10814,6 +10844,20 @@ breakText Glyphs Glyffer Flower Blomst Tree Træ Mountain Bjerg + 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 0e3c4f8c66..b5feda811e 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -590,6 +590,7 @@ 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 @@ -2040,6 +2041,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 @@ -3204,6 +3210,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 @@ -3342,9 +3353,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. @@ -3356,13 +3372,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. @@ -3381,6 +3399,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. @@ -3395,7 +3416,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. @@ -3642,6 +3662,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 @@ -5074,6 +5095,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 @@ -5485,6 +5508,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 @@ -6398,7 +6425,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 @@ -10393,6 +10423,20 @@ breakText Glyphs Glyphen Flower Blume Tree Baum Mountain Berg + 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 299e430c54..754d76d04f 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -565,6 +565,7 @@ 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 Επιλογές χρωματικού τροχού @@ -1935,6 +1936,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 Οριζόντιος προσανατολισμός @@ -4062,6 +4068,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 Επαναφορά γραμμών στα χρώματα του σχεδίου @@ -4195,9 +4206,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 την αποθηκεύει, αλλά δεν χρησιμοποιεί ακόμη δίσκους προσωρινής αποθήκευσης. @@ -4209,13 +4225,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. Τα περισσότερα βήματα αναίρεσης που κρατά κάθε έγγραφο· μικρότερος αριθμός αφαιρεί τα παλαιότερα βήματα όταν κάνετε κλικ στο Εντάξει. Βήματα μπορεί να φύγουν και νωρίτερα αν πιάνουν πολλή μνήμη. @@ -4234,6 +4252,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, αν είναι εγκατεστημένο. @@ -4248,7 +4269,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. Οι προεπιλογές εφαρμόζονται όταν κάνετε κλικ στο Εντάξει στις Προτιμήσεις. Το Ακύρωση εκεί διατηρεί τις τρέχουσες προτιμήσεις σας. @@ -4378,6 +4398,7 @@ digits Malayalam Μαλαγιάλαμ Recent Commands Πρόσφατες εντολές No recent commands Δεν υπάρχουν πρόσφατες εντολές Type to search commands, tools, panels and effects Πληκτρολογήστε για αναζήτηση εντολών, εργαλείων, πλαισίων και εφέ + Clear Recent Commands Εκκαθάριση πρόσφατων εντολών Search commands Αναζήτηση εντολών Search Commands… Αναζήτηση εντολών… Secondary Δευτερεύον @@ -5542,6 +5563,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 @@ -6217,7 +6242,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 +7013,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 επιλέξτε φάκελο προέλευσης @@ -8901,6 +8931,20 @@ breakText Glyphs Γλύφοι Flower Λουλούδι Tree Δέντρο Mountain Βουνό + 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 953ff2f93c..76b9de9383 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -610,6 +610,7 @@ 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 @@ -2039,6 +2040,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 @@ -3242,6 +3248,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 @@ -3379,9 +3390,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. @@ -3393,13 +3409,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. @@ -3418,6 +3436,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. @@ -3432,7 +3453,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. @@ -3675,6 +3695,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 @@ -5186,6 +5207,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 @@ -5600,6 +5623,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 @@ -6805,7 +6832,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 @@ -10645,6 +10675,20 @@ breakText Glyphs Glifos Flower Flor Tree Árbol Mountain Montaña + 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 41bd29df7c..a558e989b1 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -817,6 +817,7 @@ {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 @@ -4349,6 +4350,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ä @@ -4570,6 +4576,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 @@ -4663,6 +4674,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… @@ -4782,9 +4794,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ä. @@ -4796,13 +4813,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. @@ -4821,6 +4840,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. @@ -4835,7 +4857,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. @@ -5825,6 +5846,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 @@ -6735,7 +6760,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 +7018,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 @@ -8984,6 +9014,20 @@ breakText Glyphs Merkit Flower Kukka Tree Puu Mountain Vuori + 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 0e49bbc19b..e506b44df7 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -611,6 +611,7 @@ 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 @@ -2029,6 +2030,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 @@ -3230,6 +3236,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 @@ -3367,9 +3378,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. @@ -3381,13 +3397,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. @@ -3406,6 +3424,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é. @@ -3420,7 +3441,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. @@ -3663,6 +3683,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 @@ -5145,6 +5166,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 @@ -5555,6 +5578,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 @@ -6397,7 +6424,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 @@ -10715,6 +10745,20 @@ breakText Glyphs Glyphes Flower Fleur Tree Arbre Mountain Montagne + 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 021f3c409c..5165e4eff3 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -2040,6 +2040,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 ભાષા @@ -3445,9 +3451,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 તેને સાચવે છે, પરંતુ હજી સ્ક્રેચ ડિસ્કનો ઉપયોગ કરતું નથી. @@ -3459,13 +3469,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. દરેક દસ્તાવેજ રાખે તે પૂર્વવત્ પગલાંની મહત્તમ સંખ્યા; ઓછી સંખ્યા ઠીક પર ક્લિક કરો ત્યારે સૌથી જૂનાં પગલાં દૂર કરે છે. પગલાં વધુ મેમરી લે ત્યારે વહેલાં પણ દૂર થઈ શકે છે. @@ -3484,6 +3496,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 ઇન્સ્ટોલ હોય તો તેમાં ખૂલે છે. @@ -3783,6 +3798,7 @@ arrowhead Feather પીંછું No recent commands કોઈ તાજેતરના આદેશો નથી Type to search commands, tools, panels and effects આદેશો, ટૂલ્સ, પેનલ્સ અને ઇફેક્ટ્સ શોધવા માટે લખો Recent તાજેતરના + Clear Recent Commands તાજેતરના આદેશો સાફ કરો Search commands આદેશો શોધો Search images છબીઓ શોધો Searching… શોધી રહ્યા છીએ… @@ -4800,6 +4816,7 @@ 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 રંગ વ્હીલ વિકલ્પો @@ -5640,6 +5657,20 @@ swatch [Registration] [રજિસ્ટ્રેશન] Flower ફૂલ Tree વૃક્ષ Mountain પર્વત + 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 e8583ed631..42c782cb8d 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -1273,6 +1273,7 @@ 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 कलर व्हील ऑप्शन्स @@ -3001,6 +3002,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 लैब मूल्य @@ -4605,6 +4611,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 सिंबल इंस्टेंस रीसेट करें @@ -4762,9 +4773,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 इसे सहेजता है, पर अभी स्क्रैच डिस्क का उपयोग नहीं करता। @@ -4776,13 +4791,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. हर दस्तावेज़ अधिकतम जितने पूर्ववत चरण रखता है; कम संख्या ठीक है पर क्लिक करने पर सबसे पुराने चरण हटा देती है। ज़्यादा मेमोरी लेने पर चरण पहले भी हट सकते हैं। @@ -4801,6 +4818,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 इंस्टॉल होने पर उसमें खुलती है। @@ -5127,6 +5147,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 खोज फ़ॉन्ट फ़ोल्डर @@ -7066,6 +7087,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` खाली है @@ -8896,6 +8919,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 तक होना चाहिए @@ -9147,7 +9174,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}: क्लिपिंग पाथ आर्ट को काटने के लिए बहुत जटिल है @@ -10358,6 +10388,20 @@ theme Appearance अपीयरेंस Flower फूल Tree पेड़ Mountain पर्वत + 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 25f97832d9..a469ec1382 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -814,6 +814,7 @@ 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 @@ -2521,6 +2522,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 @@ -3818,6 +3824,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 @@ -3971,9 +3982,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. @@ -3985,13 +4000,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. @@ -4010,6 +4027,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. @@ -4309,6 +4329,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 @@ -5525,6 +5546,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 @@ -6370,6 +6393,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 @@ -6817,7 +6844,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 @@ -10741,6 +10771,20 @@ breakText Glyphs Glifák Flower Virág Tree Fa Mountain Hegy + 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 2668b92799..29196d231d 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 @@ -1405,6 +1408,7 @@ {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 @@ -4752,6 +4756,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 +4980,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 +5076,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 +5196,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 +5215,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 +5242,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 +5259,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. @@ -6899,6 +6923,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 @@ -8590,6 +8616,20 @@ breakText Glyphs Glif Flower Bunga Tree Pohon Mountain Gunung + 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 @@ -9018,3 +9058,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 ac2b88757c..99f026ffd5 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -612,6 +612,7 @@ 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 @@ -2080,6 +2081,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 @@ -3289,6 +3295,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 @@ -3427,9 +3438,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. @@ -3441,13 +3457,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. @@ -3466,6 +3484,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. @@ -3480,7 +3501,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. @@ -3727,6 +3747,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 @@ -5212,6 +5233,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 @@ -5622,6 +5645,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 @@ -6445,7 +6472,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 @@ -10427,6 +10457,20 @@ breakText Glyphs Glifi Flower Fiore Tree Albero Mountain Montagna + 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 824e69a0d3..84c9252d0f 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -868,6 +868,7 @@ 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 カラーホイールオプション @@ -3269,6 +3270,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 変更を取り消し @@ -3400,9 +3406,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 は保存しますが、仮想記憶ディスクはまだ使用しません。 @@ -3414,13 +3424,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 をクリックしたときに古いステップから削除されます。メモリを使いすぎる場合は、さらに早く削除されることがあります。 @@ -3439,6 +3451,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 で開きます。 @@ -3599,6 +3614,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 レイヤー上のすべてのアートを選択 @@ -4418,6 +4434,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 大きいサムネール表示 @@ -5642,6 +5663,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 を指定してください @@ -5676,6 +5699,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 までの値にしてください @@ -6494,7 +6521,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}: クリッピングパスが複雑すぎるため、アートを切り抜けません @@ -10490,6 +10520,20 @@ breakText Glyphs 字形 Flower 花 Tree 木 Mountain 山 + 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 5c66cd6dbd..9e74b91a62 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -2941,6 +2941,7 @@ {name1} {value1}, {name2} {value2} {name1} {value1}, {name2} {value2} Wheel View წრის ხედი Box View კვადრატის ხედი + Show Out-of-Gamut Colors ფერთა გამის გარეთ მყოფი ფერების ჩვენება Box Channel კვადრატის არხი Color box ფერის კვადრატი Color Wheel Options ფერთა წრის პარამეტრები @@ -6169,6 +6170,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 გრაფიკული სტილის გამოყენება @@ -6365,6 +6371,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 არცერთი @@ -6454,6 +6465,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… ჩაშენების მოხსნა… @@ -6574,9 +6586,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 მას ინახავს, მაგრამ სამუშაო დისკებს ჯერ არ იყენებს. @@ -6588,13 +6605,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-ზე დაწკაპუნებისას შლის უძველეს ნაბიჯებს. ნაბიჯები შეიძლება ადრეც წაიშალოს, თუ ბევრ მეხსიერებას იკავებს. @@ -6613,6 +6632,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-ში იხსნება, თუ ის დაინსტალირებულია. @@ -6627,7 +6649,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-ს დააჭერთ. იქ გაუქმება ინარჩუნებს თქვენს მიმდინარე პარამეტრებს. @@ -7341,6 +7362,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-მდე @@ -8157,7 +8182,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 +8804,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 გადახლართვა @@ -11038,6 +11068,20 @@ font-script Japanese იაპონური Flower ყვავილი Tree ხე Mountain მთა + 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 63c6fb7e69..8fbaa37bf2 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -861,6 +861,7 @@ 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 색상환 옵션 @@ -3258,6 +3259,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 변경 내용 실행 취소 @@ -3389,9 +3395,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는 이 값을 저장하지만 아직 스크래치 디스크를 사용하지 않습니다. @@ -3403,13 +3414,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. 각 문서가 보관하는 실행 취소 단계의 최대 수입니다. 낮추면 확인을 클릭할 때 가장 오래된 단계가 삭제됩니다. 메모리를 너무 많이 쓰면 단계가 더 일찍 삭제될 수도 있습니다. @@ -3428,6 +3441,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에서 열립니다. @@ -3442,7 +3458,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. 기본값은 환경 설정에서 확인을 클릭하면 적용됩니다. 그곳에서 취소를 누르면 현재 환경 설정이 유지됩니다. @@ -3590,6 +3605,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 레이어의 모든 아트웍 선택 @@ -4408,6 +4424,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 큰 축소판 보기 @@ -5571,6 +5592,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여야 합니다 @@ -5605,6 +5628,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 사이여야 합니다 @@ -6415,7 +6442,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}: 클리핑 패스가 너무 복잡하여 아트를 자를 수 없습니다 @@ -10390,6 +10420,20 @@ breakText Glyphs 글리프 Flower 꽃 Tree 나무 Mountain 산 + 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 eb784e2400..a4bc659663 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -1397,6 +1397,7 @@ 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 @@ -4757,6 +4758,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 @@ -4976,6 +4982,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 @@ -5067,6 +5078,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… @@ -5186,9 +5198,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. @@ -5200,13 +5217,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. @@ -5225,6 +5244,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. @@ -5239,7 +5261,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. @@ -5955,6 +5976,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 @@ -8582,7 +8607,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 +8920,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 @@ -10791,6 +10821,20 @@ breakText Glyphs Glyphs Flower Bloem Tree Boom Mountain Berg + 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 29b697fff8..21aecaef9c 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -780,6 +780,7 @@ {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 @@ -4297,6 +4298,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 @@ -4503,6 +4509,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 @@ -4596,6 +4607,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… @@ -4716,8 +4728,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. @@ -4730,21 +4746,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ą. @@ -4754,6 +4773,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. @@ -5315,6 +5337,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ę @@ -5727,6 +5751,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 @@ -6656,7 +6684,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ę @@ -10615,6 +10646,20 @@ breakText Glyphs Glify Flower Kwiat Tree Drzewo Mountain Góra + 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 651383ef5a..69f7aa383a 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -549,6 +549,7 @@ 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 @@ -2707,6 +2708,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 @@ -2843,9 +2849,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. @@ -2857,13 +2868,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. @@ -2882,6 +2895,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. @@ -2896,7 +2912,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. @@ -3106,6 +3121,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 @@ -4868,6 +4884,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 @@ -5720,6 +5740,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 @@ -6782,7 +6807,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 +6959,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 @@ -10824,6 +10854,20 @@ swatch Yellow Green Verde-amarelado Flower Flor Tree Árvore Mountain Montanha + 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 3dcedc574a..c3338e0269 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -608,6 +608,7 @@ 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 Параметры цветового круга @@ -2066,6 +2067,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 Альбомная @@ -3272,6 +3278,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 Повернуть вид по выделению @@ -3410,9 +3421,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 сохраняет его, но пока не использует рабочие диски. @@ -3424,13 +3439,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. Наибольшее число шагов отмены, которое хранит каждый документ; меньшее число удаляет самые старые шаги при нажатии ОК. Шаги могут уйти и раньше, если занимают слишком много памяти. @@ -3449,6 +3466,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, если он установлен. @@ -3708,6 +3728,7 @@ digits Malayalam Малаялам Recent Commands Недавние команды No recent commands Нет недавних команд Type to search commands, tools, panels and effects Начните вводить для поиска команд, инструментов, панелей и эффектов + Clear Recent Commands Очистить список недавних команд Search commands Поиск команд Search Commands… Поиск команд… Secondary Вторичный @@ -5208,6 +5229,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}` — встроенная рабочая среда; выберите другое имя @@ -5620,6 +5643,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 @@ -6443,7 +6470,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}: обтравочный контур слишком сложен, чтобы обрезать им иллюстрацию @@ -10808,6 +10838,20 @@ shape Open Открытый Flower Цветок Tree Дерево Mountain Гора + 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 882a62d958..c1be1f1792 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -593,6 +593,7 @@ 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 @@ -1982,6 +1983,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 @@ -3162,6 +3168,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 @@ -3299,9 +3310,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. @@ -3313,13 +3329,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. @@ -3338,6 +3356,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. @@ -3352,7 +3373,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. @@ -3583,6 +3603,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 @@ -5476,6 +5497,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 @@ -6312,7 +6337,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 +6999,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 @@ -10845,6 +10875,20 @@ digits Hindi Hindi Flower Blomma Tree Träd Mountain Berg + 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 9fe375f95c..0977fc6573 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -580,6 +580,26 @@ fn nature_symbol_library_names_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() { @@ -4093,6 +4113,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}"); @@ -6548,7 +6584,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 7afa9539d7..fa29777338 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -591,6 +591,7 @@ 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 @@ -1861,6 +1862,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 @@ -3007,6 +3013,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 @@ -3144,9 +3155,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. @@ -3158,13 +3174,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. @@ -3183,6 +3201,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. @@ -3197,7 +3218,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. @@ -3463,6 +3483,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 @@ -4913,6 +4934,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ç @@ -5320,6 +5343,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 @@ -6136,7 +6163,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 @@ -10710,6 +10740,20 @@ breakText Glyphs Glifler Flower Çiçek Tree Ağaç Mountain Dağ + 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 0317d48fdd..36e05d4941 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -606,6 +606,7 @@ 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 Параметри колірного кола @@ -2074,6 +2075,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 Альбомна @@ -3281,6 +3287,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 Повернути вид за виділенням @@ -3419,9 +3430,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 зберігає його, але поки не використовує робочі диски. @@ -3433,13 +3449,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. Найбільша кількість кроків скасування, яку зберігає кожен документ; менше число видаляє найстаріші кроки, коли ви натискаєте ОК. Кроки можуть зникнути й раніше, якщо займають надто багато пам’яті. @@ -3458,6 +3476,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, якщо його встановлено. @@ -3472,7 +3493,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. Значення за промовчанням застосовуються, коли ви натискаєте ОК у вікні «Налаштування». Скасувати там зберігає поточні налаштування. @@ -3719,6 +3739,7 @@ digits Malayalam Малаялам Recent Commands Нещодавні команди No recent commands Немає нещодавніх команд Type to search commands, tools, panels and effects Почніть вводити для пошуку команд, інструментів, панелей та ефектів + Clear Recent Commands Очистити список нещодавніх команд Search commands Пошук команд Search Commands… Пошук команд… Secondary Вторинний @@ -5196,6 +5217,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}` - вбудоване робоче середовище; виберіть інше ім’я @@ -5606,6 +5629,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 @@ -6425,7 +6452,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}: відсічний контур надто складний, щоб обрізати ним ілюстрацію @@ -10403,6 +10433,20 @@ breakText Glyphs Гліфи Flower Квітка Tree Дерево Mountain Гора + 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 b43c160a04..a8821531ef 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -725,6 +725,7 @@ 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 @@ -2372,6 +2373,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 @@ -3592,6 +3598,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 @@ -3743,9 +3754,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. @@ -3757,13 +3773,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ớ. @@ -3782,6 +3800,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. @@ -3796,7 +3817,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. @@ -4073,6 +4093,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ữ @@ -5194,6 +5215,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 @@ -6072,6 +6095,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 @@ -6177,7 +6204,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ẽ @@ -8600,6 +8630,20 @@ breakText Glyphs Glyph Flower Hoa Tree Cây Mountain Núi + 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 c8a35229ee..000cc4c30d 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -557,6 +557,7 @@ 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 色轮选项 @@ -1956,6 +1957,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 横向 @@ -3132,6 +3138,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 将各行重置为图稿的颜色 @@ -3269,9 +3280,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 会存储它,但尚未使用暂存盘。 @@ -3283,13 +3298,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. 每个文档保留的最大撤销步骤数;调低后,单击“确定”时会删除最早的步骤。步骤占用过多内存时也可能更早被删除。 @@ -3308,6 +3325,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 中打开。 @@ -3535,6 +3555,7 @@ digits Malayalam 马拉雅拉姆数字 Recent Commands 最近使用的命令 No recent commands 没有最近使用的命令 Type to search commands, tools, panels and effects 输入以搜索命令、工具、面板和效果 + Clear Recent Commands 清除最近使用的命令 Search commands 搜索命令 Search Commands… 搜索命令… Secondary 次要 @@ -5311,6 +5332,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 @@ -5342,6 +5365,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 之间 @@ -6695,7 +6722,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}:剪切路径过于复杂,无法用来剪切图稿 @@ -10595,6 +10625,20 @@ breakText Glyphs 字形 Flower 花朵 Tree 树木 Mountain 山脉 + 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 07a4fd319f..fed07e7d06 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -574,6 +574,7 @@ 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 色輪選項 @@ -2685,6 +2686,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 @@ -2716,6 +2719,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 之間 @@ -3341,6 +3348,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 橫向 @@ -4572,6 +4584,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 依選取範圍旋轉檢視 @@ -4710,9 +4727,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 會儲存它,但尚未使用暫存磁碟。 @@ -4724,13 +4745,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. 每份文件保留的最大復原步驟數;調低後,按一下「確定」時會刪除最早的步驟。步驟佔用過多記憶體時也可能更早被刪除。 @@ -4749,6 +4772,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 中開啟。 @@ -5008,6 +5034,7 @@ digits Malayalam 馬來亞拉姆數字 Recent Commands 最近使用的指令 No recent commands 沒有最近使用的指令 Type to search commands, tools, panels and effects 輸入以搜尋指令、工具、面板與效果 + Clear Recent Commands 清除最近使用的指令 Search commands 搜尋指令 Search Commands… 搜尋指令… Secondary 次要 @@ -6543,7 +6570,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}:剪裁路徑過於複雜,無法用來剪裁圖稿 @@ -10410,6 +10440,20 @@ breakText Glyphs 字符 Flower 花朵 Tree 樹木 Mountain 山脈 + 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..e768f11c89 100644 --- a/crates/ui-egui/src/io/open.rs +++ b/crates/ui-egui/src/io/open.rs @@ -133,8 +133,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())?; @@ -570,7 +572,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/menus/run.rs b/crates/ui-egui/src/menus/run.rs index 5ea673909c..3ef085bc04 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -794,8 +794,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`). diff --git a/crates/ui-egui/src/menus/state.rs b/crates/ui-egui/src/menus/state.rs index a4461c4b9e..52561b4542 100644 --- a/crates/ui-egui/src/menus/state.rs +++ b/crates/ui-egui/src/menus/state.rs @@ -273,6 +273,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() } diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 9756591534..d1db926bf9 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1013,6 +1013,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…", @@ -1574,7 +1580,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} 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; 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}", ), ( "ui.savePdfDialog", diff --git a/crates/ui-egui/src/palette.rs b/crates/ui-egui/src/palette.rs index 8cda77bb7b..69e4d5e17c 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 { @@ -522,19 +522,24 @@ 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> { +/// 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 +1070,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 +1206,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 +1221,11 @@ 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"); + // 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"); @@ -1129,7 +1272,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. @@ -1461,15 +1604,18 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { 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 +1632,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(); @@ -1823,6 +1974,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); @@ -2104,6 +2259,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 +2568,71 @@ mod tests { assert_eq!(open.app.ui.recent_commands, ["paint.swap", "object.group"]); } + /// 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 +2690,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] @@ -2904,7 +3392,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() } diff --git a/crates/ui-egui/src/palette/search.rs b/crates/ui-egui/src/palette/search.rs index 1be7bd5a3c..5cfe8ef6c2 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)); } @@ -1923,7 +1964,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..5a04384e55 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,8 @@ mod tests_color_wheel; #[cfg(test)] mod tests_color_wheel_box; #[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..8b479c3256 100644 --- a/crates/ui-egui/src/panels/appearance.rs +++ b/crates/ui-egui/src/panels/appearance.rs @@ -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/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..6b3d563ed0 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,25 @@ //! 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`). +//! 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 +//! and Show Color Vision Preview are kept with the preferences (`ui.colorWheel`). -use egui::{Rect, Sense, Stroke, StrokeKind, Ui, UiBuilder, vec2}; +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 +97,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, @@ -94,9 +114,51 @@ pub struct Settings { pub vision: 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, + } } } @@ -146,12 +208,22 @@ 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; 7] = ["view", "channel", "sliders", "gamut", "harmony", "harmonyRule", "vision"]; match p { Value::Null => {} Value::Object(o) => { @@ -161,7 +233,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 +242,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 +275,13 @@ pub(crate) fn command(app: &mut VectorcraftApp, p: &Value) -> Result 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, /// or red, green and blue. fn box_values(ch: Channel, hsb: [f32; 3]) -> [f32; 3] { @@ -272,16 +437,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 +467,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 +577,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 +616,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 +655,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 +876,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 +886,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 +923,80 @@ 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); 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/links.rs b/crates/ui-egui/src/panels/links.rs index 14794de987..b631596535 100644 --- a/crates/ui-egui/src/panels/links.rs +++ b/crates/ui-egui/src/panels/links.rs @@ -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/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..9fb93ea928 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"}); + 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..ac054cc519 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,7 @@ 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}); let with = |v: serde_json::Value| { let mut v = v; v.as_object_mut().unwrap().extend(harmony.as_object().unwrap().clone()); @@ -217,9 +217,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"); 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"); assert_eq!(app.ui.color_wheel, Settings { view: View::Box, channel: Channel::Red, ..Default::default() }, "an error changes nothing"); } @@ -277,7 +277,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_gamut.rs b/crates/ui-egui/src/panels/tests_color_wheel_gamut.rs new file mode 100644 index 0000000000..3de5f2a7fd --- /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}); + 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..8a0cb95ee5 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"}); 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" ); 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..b0be98c21e 100644 --- a/crates/ui-egui/src/panels/tests_links.rs +++ b/crates/ui-egui/src/panels/tests_links.rs @@ -736,3 +736,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 1226b292d7..eeb0af53ce 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 61993a8581..64bc5e08f3 100644 --- a/crates/ui-egui/src/panels/three_d.rs +++ b/crates/ui-egui/src/panels/three_d.rs @@ -11,10 +11,11 @@ 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; @@ -155,9 +156,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()) @@ -240,13 +243,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 @@ -259,6 +268,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()); @@ -581,10 +598,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..ba09192e2b 100644 --- a/crates/ui-egui/src/shortcut_editor.rs +++ b/crates/ui-egui/src/shortcut_editor.rs @@ -992,9 +992,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 diff --git a/crates/ui-egui/src/shortcuts/tests.rs b/crates/ui-egui/src/shortcuts/tests.rs index f29308c4b5..091741a655 100644 --- a/crates/ui-egui/src/shortcuts/tests.rs +++ b/crates/ui-egui/src/shortcuts/tests.rs @@ -1638,6 +1638,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 +2119,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 diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index bb3a450fce..fea9e6e533 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -651,6 +651,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). @@ -762,6 +767,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, @@ -825,7 +834,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, @@ -1319,6 +1329,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, @@ -1348,6 +1359,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/taskbar.rs b/crates/ui-egui/src/tests/taskbar.rs index 1615681f57..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] diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index ffd71addf0..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,11 +38,13 @@ 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, 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/docs/control-protocol.md b/docs/control-protocol.md index 0af0e02a42..64926171bb 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -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`, diff --git a/docs/effects-parity.md b/docs/effects-parity.md index 1b0d755ff8..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)) | +| 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 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)) | +| 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 271319fde7..df988ebe81 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`. @@ -716,8 +724,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 @@ -957,6 +965,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 e08509c0c8..719b65322e 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -675,20 +675,37 @@ 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}`, +the list return an error and change nothing. The command returns `{view, channel, sliders, gamut, harmony, harmonyRule, vision}`, 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 @@ -1620,7 +1637,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 +2357,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 +3504,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 +3913,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 +3950,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 @@ -4768,7 +4827,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 @@ -5165,7 +5230,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, @@ -5177,12 +5242,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: @@ -5748,12 +5848,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 @@ -6060,6 +6163,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"`, @@ -6747,6 +6870,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 @@ -6873,7 +7004,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. @@ -7307,6 +7438,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 @@ -7393,7 +7565,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` @@ -7412,7 +7584,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 @@ -8011,6 +8185,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. @@ -10908,10 +11084,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}}} @@ -12290,6 +12468,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 @@ -13572,7 +13791,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..406bc1f4f7 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-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: 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 | +| 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, 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,8 @@ not take the artwork yet. Overflow-menu drag remains separate. Scores and hours | 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 | 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 87fa323ad1..b01a46712c 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-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: 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 | @@ -745,6 +749,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 +874,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`. @@ -1170,10 +1178,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`). @@ -1230,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`). @@ -1357,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. @@ -1462,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). @@ -1557,7 +1573,8 @@ 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`). 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`). @@ -1947,7 +1964,9 @@ 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 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. @@ -2087,6 +2106,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). @@ -2320,6 +2340,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`). @@ -2478,6 +2499,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. @@ -3041,6 +3063,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). @@ -3105,6 +3135,8 @@ Edit › Copy and Cut put the selected ruler guides on the clipboard, with the s | 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 | 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 35b097f4ac..dda534b90e 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 @@ -605,7 +627,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). @@ -630,7 +652,8 @@ out, perspective). No Adobe software, assets, presets or bevel shapes were used. 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 bevel paths are not supported. +- 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..4289760629 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-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: 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 | @@ -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 | @@ -402,7 +406,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 +497,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 +510,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 +625,7 @@ before release (#6373). [Paint faces and edges](https://helpx.adobe.com/illustra | 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 | 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 +646,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. |