diff --git a/ROADMAP.md b/ROADMAP.md index 05862568d6..b3877be5c8 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -155,6 +155,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 2026-11-01: Divide into Dashes joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the selected paths, or only their direct-selected segments, are cut into separate open paths of a dash length measured along the curve, with an optional gap (left empty, or kept as pieces), each keeping the path's appearance; Fit to Corners and Ends stretches or squeezes the lengths so every run starts and ends on a dash. A dialog with Preview, one undo step, at most 100000 pieces. A VectorCraft addition: headline numbers unchanged. - 2026-11-15: Common Tangents in the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): the straight lines that touch two selected convex closed paths (ellipses at any rotation and scale, or convex Bézier paths) without crossing either are added as open paths with the current stroke: external, internal or all, and the line joining the centers if asked; a path inside the other has none unless the two touch, and a message says why; a dialog with Preview, one undo step (`addon.pathtools.commonTangents`, #7845). A VectorCraft addition: headline numbers unchanged. - 2026-11-15: With Smart Guides and Snap to Tangent on, a Line Segment drag pressed on one convex curved path and dragged near another lands on a common tangent of the two: both ends move to where the line touches the paths, each labeled "tangent" (#7845). A VectorCraft addition: headline numbers unchanged. +- 2026-11-15: Smooth Bridge joins the Path Precision Tools add-on (Object › Plug-ins › Path Precision Tools): two selected circles become one closed outline joined by two concave arcs that touch both circles, so every anchor is smooth; the arcs' radius is a percentage of the smaller circle's radius (1 to 1000%, 100% by default), and Keep Originals adds the outline above the circles instead of replacing them. A dialog with Preview, one undo step (`addon.pathtools.bridge`). A VectorCraft addition: headline numbers unchanged. - 2026-11-03: Text Tweaker, the first tool of the Type Tools add-on (Object › Plug-ins › Type Tools): one character attribute (size, baseline shift, rotation, horizontal or vertical scale, tracking, leading or stroke weight) goes letter by letter from a start value to an end value along a straight ramp, an ease, a bow, a spike or at random with a seed, set as the Character panel sets it, while the text stays live; a dialog with Preview, one undo step (`addon.type.textTweaker`, #4924). A VectorCraft addition: headline numbers unchanged. - 2026-11-01: Group Overlapping Objects joins the Arrange Tools add-on (Object › Plug-ins › Arrange Tools): the selected objects whose visual bounds overlap or touch, chains included, go into one group each, within their own layer or group, at the stacking place of their frontmost member; objects that overlap nothing stay as they are. One undo step, a sweep along x so thousands of loose pieces group quickly (at most 20000 objects). A VectorCraft addition: headline numbers unchanged. - 2026-10-31: Export for Screens works as the reference app's dialog: Artboards and Assets tabs with a grid or list of thumbnails, Clear Selection and Prefix, Create Sub-folders by Scale or Format (on by default), Export PDFs As Single File (the chosen artboards as one PDF's pages, `pdfs: "single"`) or Multiple Files, iOS and Android rows, format presets in a ☰ menu, and a count of the files the export writes (#4895). About 55 community PRs and fixes landed the same day: Find Font, Replace Font, Outline Stroke and Expand leave hidden and locked art alone (with a warning); DXF export writes LINE and ELLIPSE entities and outlines only the strokes a CAD line can't draw; Blob Brush Angle and Roundness; Shift-constrained Perspective Selection; Grid Repeat Options Preview; a gradient mesh from a file budgeted at about a million quads; width-profile strokes keep their shape zoomed out; `.ai`/EPS import fidelity (area type, envelopes, transparency in dictionaries, character styles); PDF import finds hyphenated and CMap-suffixed font names; Windows renders follow the process's core affinity; Enter or Escape in a floating panel's field no longer reaches the canvas (#4803); Properties shows Blend Options for any selected blend (#4817); Artwork Cleanup finds doubled type (#4835) and joins stacked lines into one object (Join Point Text, #4826). Headline numbers unchanged. diff --git a/apps/vectorcraft/src/display_profile.rs b/apps/vectorcraft/src/display_profile.rs index 2be6e27aa5..ee35a407a7 100644 --- a/apps/vectorcraft/src/display_profile.rs +++ b/apps/vectorcraft/src/display_profile.rs @@ -10,7 +10,7 @@ //! - macOS: the window's layer is tagged sRGB and macOS converts it (`mac_color_space`). //! //! While the preference is on, a background thread reads the display every [`EVERY`] seconds, -//! and at once when the window moves to another display. +//! and at once when the window moves to another display or Edit › Refresh Monitor Profile asks. use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; @@ -31,6 +31,8 @@ pub(crate) struct Reader { looked: Option, /// A reading is running. busy: Arc, + /// [`DisplayProfile::attach_reader`] was called. + attached: bool, } /// Clears [`Reader::busy`] when the reading thread ends, also by a panic. @@ -45,22 +47,22 @@ impl Drop for Done { impl Reader { /// Starts a reading when one is due and none is running. `now` is the frame's time in seconds. pub(crate) fn tick(&mut self, window: &winit::window::Window, now: f64, enabled: bool, profile: &DisplayProfile, ctx: &egui::Context) { - if !enabled || self.busy.load(Ordering::Acquire) || self.looked.is_some_and(|at| (at..at + LOOK_EVERY).contains(&now)) { - return; + if !self.attached { + profile.attach_reader(); + self.attached = true; } - self.looked = Some(now); - let display = window.current_monitor().and_then(|m| m.name()); - if !due(self.last.as_ref(), now, display.as_deref()) { + let Some(display) = self.start(now, enabled, profile, || window.current_monitor().and_then(|m| m.name())) else { return; - } - self.last = Some((now, display.clone())); + }; profile.pending(); self.busy.store(true, Ordering::Release); let done = Done(self.busy.clone()); let (profile, ctx) = (profile.clone(), ctx.clone()); let spawned = std::thread::Builder::new().name("display profile".into()).spawn(move || { - let _done = done; - if profile.report(read(display)) { + let changed = profile.report(read(display)); + drop(done); + // A request made while this reading ran starts on the next frame. + if changed || profile.read_requested() { ctx.request_repaint(); } }); @@ -68,6 +70,32 @@ impl Reader { log::warn!("couldn't start reading the display profile: {e}"); } } + + /// The display to read at `now` when a reading is to start, looked up with `display`. A + /// request from Refresh Monitor Profile ([`DisplayProfile::request_read`]) starts one at once, + /// past [`EVERY`] and [`LOOK_EVERY`]; while a reading runs it waits, and a frame that finds the + /// preference off drops it. A request made with the preference on is kept when the preference + /// goes off and on again between two frames. + fn start(&mut self, now: f64, enabled: bool, profile: &DisplayProfile, display: impl FnOnce() -> Option) -> Option> { + if !enabled { + profile.take_request(); + return None; + } + if self.busy.load(Ordering::Acquire) { + return None; + } + let asked = profile.take_request(); + if !asked && self.looked.is_some_and(|at| (at..at + LOOK_EVERY).contains(&now)) { + return None; + } + self.looked = Some(now); + let display = display(); + if !asked && !due(self.last.as_ref(), now, display.as_deref()) { + return None; + } + self.last = Some((now, display.clone())); + Some(display) + } } /// Whether a reading of `display` is due at `now`, after the last one (`last`): none yet, another @@ -570,6 +598,56 @@ mod tests { assert!(due(Some(&last), 50.0, Some("DP-1"))); } + fn attached() -> DisplayProfile { + let profile = DisplayProfile::default(); + profile.attach_reader(); + profile + } + + #[test] + fn a_requested_reading_starts_on_the_next_frame_past_both_intervals() { + let (mut r, profile) = (Reader::default(), attached()); + let dp1 = || Some("DP-1".to_string()); + assert_eq!(r.start(100.0, true, &profile, dp1), Some(Some("DP-1".into()))); + // Inside the display lookup interval and the reading interval: nothing starts. + assert_eq!(r.start(100.5, true, &profile, || panic!("not looked up")), None); + assert_eq!(r.start(102.0, true, &profile, dp1), None); + profile.request_read(true).unwrap(); + assert_eq!(r.start(102.1, true, &profile, dp1), Some(Some("DP-1".into()))); + assert!(!profile.read_requested(), "the request is taken"); + // The intervals run again from the requested reading. + assert_eq!(r.start(102.2, true, &profile, dp1), None); + assert_eq!(r.start(111.0, true, &profile, dp1), None); + assert_eq!(r.start(113.0, true, &profile, dp1), Some(Some("DP-1".into()))); + } + + #[test] + fn a_request_made_while_a_reading_runs_waits_for_it_to_end() { + let (mut r, profile) = (Reader::default(), attached()); + let dp1 = || Some("DP-1".to_string()); + assert!(r.start(0.0, true, &profile, dp1).is_some()); + r.busy.store(true, Ordering::Release); + profile.request_read(true).unwrap(); + assert_eq!(r.start(0.1, true, &profile, dp1), None); + assert_eq!(r.start(5.0, true, &profile, dp1), None); + assert!(profile.read_requested(), "kept while the reading runs"); + r.busy.store(false, Ordering::Release); + assert_eq!(r.start(5.1, true, &profile, dp1), Some(Some("DP-1".into()))); + assert!(!profile.read_requested()); + } + + #[test] + fn a_request_is_dropped_when_the_preference_goes_off() { + let (mut r, profile) = (Reader::default(), attached()); + let dp1 = || Some("DP-1".to_string()); + assert!(r.start(0.0, true, &profile, dp1).is_some()); + profile.request_read(true).unwrap(); + assert_eq!(r.start(0.1, false, &profile, dp1), None); + assert!(!profile.read_requested()); + assert_eq!(r.start(0.2, true, &profile, dp1), None, "no reading starts later for it"); + assert!(profile.request_read(false).is_err()); + } + #[test] fn wayland_sessions_are_told_apart_from_x11_by_the_environment() { let env = |pairs: &'static [(&'static str, &'static str)]| { diff --git a/apps/vectorcraft/src/host_services.rs b/apps/vectorcraft/src/host_services.rs index 53e0484534..1ce124c1dd 100644 --- a/apps/vectorcraft/src/host_services.rs +++ b/apps/vectorcraft/src/host_services.rs @@ -96,7 +96,24 @@ fn dialog_for(d: D, request: &PickRequest) -> D { Some(folder) => d.folder(folder), None => d, }; - if pick.name.is_empty() { d } else { d.file_name(&pick.name) } + if pick.name.is_empty() { + return d; + } + // Windows' save dialog changes the extension when a different file type is chosen only when + // the suggested name has no explicit extension. rfd supplies the first filter's extension to + // that dialog, so leave the suffix to Windows for saves that offer several formats (#5451). + // A remaining dot in the stem would look like another explicit extension to Windows. + #[cfg(windows)] + if matches!(request, PickRequest::Save(_)) + && pick.filters.len() > 1 + && let Some(ext) = std::path::Path::new(&pick.name).extension().and_then(|e| e.to_str()) + && pick.filters.iter().any(|(_, exts)| exts.iter().any(|e| e.eq_ignore_ascii_case(ext))) + && let Some(stem) = std::path::Path::new(&pick.name).file_stem().and_then(|s| s.to_str()) + && !stem.contains('.') + { + return d.file_name(stem); + } + d.file_name(&pick.name) } #[cfg(test)] @@ -796,7 +813,7 @@ mod dialog_tests { /// The file types a dialog was given, by label. #[derive(Default)] - struct Filters(Vec<(String, Vec)>); + struct Filters(Vec<(String, Vec)>, Option); impl DialogSettings for Filters { fn parent(self, _window: &winit::window::Window) -> Self { @@ -812,7 +829,8 @@ mod dialog_tests { fn folder(self, _folder: &str) -> Self { self } - fn file_name(self, _name: &str) -> Self { + fn file_name(mut self, name: &str) -> Self { + self.1 = Some(name.to_string()); self } } @@ -869,4 +887,24 @@ mod dialog_tests { let first = fileio::place_filters().next().map(|(_, exts)| open_extensions(exts, CASE_SENSITIVE_FILTERS)); assert_eq!(placed.first().map(|(_, exts)| exts.clone()), first); } + + /// A format selected after the Windows Save As dialog opens can replace the suffix of the + /// suggested name. Single-format saves and open dialogs keep the supplied name verbatim. + #[cfg(windows)] + #[test] + fn save_dialog_with_several_formats_leaves_the_extension_to_windows() { + let filters = vec![FilePick::filter("VectorCraft", &["vectorcraft"]), FilePick::filter("PDF-compatible .ai", &["ai"])]; + let pick = FilePick { name: "Poster.vectorcraft".into(), filters: filters.clone(), ..Default::default() }; + assert_eq!(dialog_for(Filters::default(), &PickRequest::Save(pick.clone())).1.as_deref(), Some("Poster")); + assert_eq!(dialog_for(Filters::default(), &PickRequest::Open(pick)).1.as_deref(), Some("Poster.vectorcraft")); + + let pick = FilePick { name: "Poster.AI".into(), filters: filters.clone(), ..Default::default() }; + assert_eq!(dialog_for(Filters::default(), &PickRequest::Save(pick)).1.as_deref(), Some("Poster")); + let pick = FilePick { name: "Poster.design".into(), filters: filters.clone(), ..Default::default() }; + assert_eq!(dialog_for(Filters::default(), &PickRequest::Save(pick)).1.as_deref(), Some("Poster.design")); + let pick = FilePick { name: "draft.v1.vectorcraft".into(), filters: filters.clone(), ..Default::default() }; + assert_eq!(dialog_for(Filters::default(), &PickRequest::Save(pick)).1.as_deref(), Some("draft.v1.vectorcraft")); + let pick = FilePick { name: "Poster.vectorcraft".into(), filters: vec![filters[0].clone()], ..Default::default() }; + assert_eq!(dialog_for(Filters::default(), &PickRequest::Save(pick)).1.as_deref(), Some("Poster.vectorcraft")); + } } diff --git a/crates/brush/src/colorize.rs b/crates/brush/src/colorize.rs index 00edeb3113..10dc66b587 100644 --- a/crates/brush/src/colorize.rs +++ b/crates/brush/src/colorize.rs @@ -97,6 +97,75 @@ pub fn colorize(n: &mut Node, mode: Colorization, stroke: &Paint) { walk(n, mode, key); } +/// Mixed into a stroke's seed for its hue jitter, so the amounts come from a sequence of their own +/// and a copy's size, spacing, scatter and rotation stay as they were without hue jitter. +const HUE_JITTER_SALT: u64 = 0x6875_655f_6a69_7474; + +/// Turn the hue of each of `copies` (a scatter brush's copies, in order along the path) by its +/// own amount between −`amount` and `amount` degrees, drawn from `seed` (the stroke's +/// [`crate::track::seed_of`]). +pub(crate) fn jitter_hues(copies: &mut [Node], amount: f64, seed: u64) { + let mut rng = crate::track::Rng::new(seed ^ HUE_JITTER_SALT); + for n in copies { + let turn = rng.range(-amount, amount) as f32; + turn_hues(n, turn); + } +} + +/// `c` with its hue turned by `degrees`, worked out on its own components so nothing else about it +/// changes: RGB in HSB of its values, CMYK over C, M and Y with K kept (as +/// [`Color::complement_keep_model`] does), Lab by turning a and b. `None` for a color without a hue: +/// white, black and grays, in their own model (Gray, CMYK with no C, M or Y ink). +fn turned(c: &Color, degrees: f32) -> Option { + if !degrees.is_finite() || vectorcraft_color::recolor::Neutral::of(c).is_some() { + return None; + } + let turn = |v: [f32; 3]| { + let [h, s, b] = vectorcraft_color::rgb_to_hsb(v); + (s > 0.0).then(|| vectorcraft_color::hsb_to_rgb([(h + degrees).rem_euclid(360.0), s, b])) + }; + match *c { + Color::Rgb { r, g, b } => turn([r, g, b]).map(|[r, g, b]| Color::rgb(r, g, b)), + Color::Cmyk { c, m, y, k } => turn([1.0 - c, 1.0 - m, 1.0 - y]).map(|[r, g, b]| Color::cmyk(1.0 - r, 1.0 - g, 1.0 - b, k)), + Color::Gray { .. } => None, + Color::Lab { l, a, b } => { + let (sin, cos) = f64::from(degrees).to_radians().sin_cos(); + let (a, b) = (f64::from(a), f64::from(b)); + Some(Color::lab(l, (a * cos - b * sin) as f32, (a * sin + b * cos) as f32)) + } + } +} + +fn turn_paint(p: &mut Paint, degrees: f32) { + if let Paint::Solid { color, .. } = p + && let Some(c) = turned(color, degrees) + { + *p = Paint::solid(c); + } +} + +/// Turn the hue of the solid fills and strokes under `n`, its type's characters included. A +/// mask's colors are its values, so they stay. +fn turn_hues(n: &mut Node, degrees: f32) { + for it in &mut n.appearance.items { + match it { + AppearanceItem::Fill(f) => turn_paint(&mut f.paint, degrees), + AppearanceItem::Stroke(s) => turn_paint(&mut s.paint, degrees), + } + } + if let NodeKind::Text(t) = &mut n.kind { + for r in &mut t.runs { + turn_paint(&mut r.style.fill, degrees); + turn_paint(&mut r.style.stroke, degrees); + } + } + if let Some(ch) = n.children_mut() { + for c in ch.iter_mut() { + turn_hues(Arc::make_mut(c), degrees); + } + } +} + /// Strip the brushes from every stroke under `n`, its masks' art included. fn strip_brushes(n: &mut Node) { for it in &mut n.appearance.items { diff --git a/crates/brush/src/defaults.rs b/crates/brush/src/defaults.rs index 8cf7467397..b99f36ecec 100644 --- a/crates/brush/src/defaults.rs +++ b/crates/brush/src/defaults.rs @@ -172,6 +172,7 @@ pub fn defaults() -> &'static [Brush] { rotation: (-180.0, 180.0), rotation_relative_to_path: false, colorization: Colorization::Tints, + hue_jitter: 0.0, modes: None, }), }, @@ -185,6 +186,7 @@ pub fn defaults() -> &'static [Brush] { rotation: (-35.0, 35.0), rotation_relative_to_path: true, colorization: Colorization::None, + hue_jitter: 0.0, modes: None, }), }, diff --git a/crates/brush/src/lib.rs b/crates/brush/src/lib.rs index 43336f93dd..c5354d75cd 100644 --- a/crates/brush/src/lib.rs +++ b/crates/brush/src/lib.rs @@ -298,6 +298,12 @@ pub struct Scatter { /// Rotation relative to the path direction (else to the page). pub rotation_relative_to_path: bool, pub colorization: Colorization, + /// Hue jitter in degrees, 0 to 180: each copy turns the hue of the solid colors it draws, after + /// the colorization, by its own amount between −`hue_jitter` and `hue_jitter`. The stroke's + /// path and the brush name fix the amounts, so a stroke draws the same colors every time. + /// 0 (brushes saved before there was hue jitter) leaves the colors as they are. + #[serde(skip_serializing_if = "is_zero")] + pub hue_jitter: f64, /// How size, spacing, scatter and rotation vary between their two values: Fixed takes the /// first, Random any value between them, Pressure the first at the lightest pen pressure and /// the second at the heaviest, Tilt the first with the pen lying flat and the second upright, @@ -318,6 +324,7 @@ impl Default for Scatter { rotation: (0.0, 0.0), rotation_relative_to_path: false, colorization: Colorization::None, + hue_jitter: 0.0, modes: None, } } @@ -326,6 +333,8 @@ impl Default for Scatter { impl Scatter { /// The ranges of size (%), spacing (%), scatter (%) and rotation (°). pub const RANGES: [(f64, f64); 4] = [(1.0, 10000.0), (1.0, 10000.0), (-1000.0, 1000.0), (-180.0, 180.0)]; + /// The range of [`Scatter::hue_jitter`] (°). + pub const HUE_JITTER_RANGE: (f64, f64) = (0.0, 180.0); /// Size, spacing, scatter and rotation, each as its (first, second) values. pub fn values(&self) -> [(f64, f64); 4] { @@ -624,6 +633,10 @@ fn within_pair((a, b): (f64, f64), range: (f64, f64), fallback: f64) -> (f64, f6 (within(a, range, fallback), within(b, range, fallback)) } +fn is_zero(v: &f64) -> bool { + *v == 0.0 +} + fn valid_tile_frame(frame: Rect) -> bool { [frame.x0, frame.y0, frame.x1, frame.y1].into_iter().all(f64::is_finite) && frame.width().is_finite() @@ -714,6 +727,7 @@ impl Brush { s.spacing = within_pair(s.spacing, spacing, d.spacing.0); s.scatter = within_pair(s.scatter, scatter, 0.0); s.rotation = within_pair(s.rotation, rotation, 0.0); + s.hue_jitter = within(s.hue_jitter, Scatter::HUE_JITTER_RANGE, 0.0); s.colorization.sanitize(); } BrushKind::Art(a) => { @@ -1093,6 +1107,12 @@ pub fn stroke_pieces(doc: &Document, brush: &Brush, bp: &BezPath, stroke: &Strok for n in &mut out { colorize(n, colorization, &stroke.paint); } + // One piece per copy, in the order the copies run along the path. + if let BrushKind::Scatter(s) = &brush.kind + && s.hue_jitter > 0.0 + { + colorize::jitter_hues(&mut out, s.hue_jitter, track::seed_of(bp, &brush.name)); + } leave_out_brushed(doc, &mut out, &mut Known::new()); out } diff --git a/crates/brush/src/tests.rs b/crates/brush/src/tests.rs index fdec056730..f4f2d1ae20 100644 --- a/crates/brush/src/tests.rs +++ b/crates/brush/src/tests.rs @@ -1033,6 +1033,165 @@ fn stain_mixes_type_strokes_too() { assert_eq!(run_paints(&[art]), [(Paint::solid(blue), Paint::solid(blue))]); } +/// A scatter brush of rectangles filled `fill`, with `colorization` and `hue_jitter`. +fn jittered(fill: Color, colorization: Colorization, hue_jitter: f64) -> Brush { + let mut art = rect_art(10.0, 4.0); + art.appearance.set_fill(Paint::solid(fill)); + Brush { name: "s".into(), kind: BrushKind::Scatter(Scatter { art, colorization, hue_jitter, ..Default::default() }) } +} + +/// The fill color of each copy. +fn fill_colors(out: &[Node]) -> Vec { + out.iter().map(|n| n.appearance.fill_paint().color().unwrap()).collect() +} + +/// How far hue `h` is from `from`, in degrees, either way round. +fn hue_gap(h: f32, from: f32) -> f32 { + let d = (h - from).rem_euclid(360.0); + d.min(360.0 - d) +} + +#[test] +fn hue_jitter_turns_each_copy_the_same_every_time() { + let doc = Document::new(1.0, 1.0); + let path = line(0.0, 0.0, 200.0, 0.0); + let b = jittered(Color::rgb(1.0, 0.0, 0.0), Colorization::None, 90.0); + let out = stroke_pieces(&doc, &b, &path, &stroke(1.0)); + assert_eq!(out.len(), 20); + assert_eq!(stroke_pieces(&doc, &b, &path, &stroke(1.0)), out, "the same stroke draws the same colors"); + let colors = fill_colors(&out); + let hues: Vec = colors.iter().map(|c| c.to_hsb()[0]).collect(); + assert!(hues.iter().all(|h| hue_gap(*h, 0.0) <= 90.01), "{hues:?}"); + assert!(hues.iter().any(|h| hue_gap(*h, 0.0) > 10.0), "the copies turn: {hues:?}"); + let distinct: std::collections::HashSet = colors.iter().map(Color::to_hex).collect(); + assert!(distinct.len() > 10, "each copy turns by its own amount: {distinct:?}"); + // Saturation and brightness stay; the copies stay where they were, at their size and angle. + assert!(colors.iter().all(|c| near(f64::from(c.to_hsb()[1]), 1.0, 1e-3) && near(f64::from(c.to_hsb()[2]), 1.0, 1e-3)), "{colors:?}"); + let plain = stroke_pieces(&doc, &jittered(Color::rgb(1.0, 0.0, 0.0), Colorization::None, 0.0), &path, &stroke(1.0)); + let boxes = |o: &[Node]| o.iter().map(|n| n.geometric_bounds().unwrap()).collect::>(); + assert_eq!(boxes(&out), boxes(&plain)); + // Another path draws other amounts. + let other = fill_colors(&stroke_pieces(&doc, &b, &line(0.0, 10.0, 200.0, 10.0), &stroke(1.0))); + assert_ne!(other, colors); +} + +#[test] +fn hue_jitter_of_zero_changes_nothing() { + let red = Color::rgb(1.0, 0.0, 0.0); + let out = stroke_pieces(&Document::new(1.0, 1.0), &jittered(red, Colorization::None, 0.0), &line(0.0, 0.0, 200.0, 0.0), &stroke(1.0)); + assert!(!out.is_empty() && fill_colors(&out).iter().all(|c| *c == red)); + // A brush without hue jitter is saved as before, and one saved before reads as 0. + let v = serde_json::to_value(jittered(red, Colorization::None, 0.0)).unwrap(); + assert!(v.get("hue_jitter").is_none(), "{v}"); + let mut old = serde_json::to_value(jittered(red, Colorization::None, 45.0)).unwrap(); + assert_eq!(old.as_object_mut().unwrap().remove("hue_jitter"), Some(serde_json::json!(45.0))); + let BrushKind::Scatter(s) = Brush::from_json(old).unwrap().kind else { panic!("not a scatter brush") }; + assert_eq!(s.hue_jitter, 0.0, "a brush saved without the key reads as 0"); + let mut with = v.clone(); + with["hue_jitter"] = serde_json::json!(45.0); + let BrushKind::Scatter(s) = Brush::from_json(with).unwrap().kind else { panic!("not a scatter brush") }; + assert_eq!(s.hue_jitter, 45.0); + // Values outside 0..180 are clamped. + for (given, kept) in [(500.0, 180.0), (-20.0, 0.0)] { + let mut v = v.clone(); + v["hue_jitter"] = serde_json::json!(given); + let BrushKind::Scatter(s) = Brush::from_json(v).unwrap().kind else { panic!("not a scatter brush") }; + assert_eq!(s.hue_jitter, kept, "{given}"); + } +} + +#[test] +fn hue_jitter_turns_after_the_colorization() { + let doc = Document::new(1.0, 1.0); + let path = line(0.0, 0.0, 200.0, 0.0); + // Tints: black art takes the blue stroke color, which then turns. + let blue = StrokeLayer::new(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 1.0); + let hues: Vec = + fill_colors(&stroke_pieces(&doc, &jittered(Color::BLACK, Colorization::Tints, 30.0), &path, &blue)).iter().map(|c| c.to_hsb()[0]).collect(); + assert!(!hues.is_empty() && hues.iter().all(|h| hue_gap(*h, 240.0) <= 30.01), "{hues:?}"); + assert!(hues.iter().any(|h| hue_gap(*h, 240.0) > 3.0), "{hues:?}"); + // A gray stroke color has no hue: its tints stay as they are. + let gray = StrokeLayer::new(Paint::solid(Color::rgb(0.5, 0.5, 0.5)), 1.0); + let turned = stroke_pieces(&doc, &jittered(Color::BLACK, Colorization::Tints, 180.0), &path, &gray); + let still = stroke_pieces(&doc, &jittered(Color::BLACK, Colorization::Tints, 0.0), &path, &gray); + assert_eq!(fill_colors(&turned), fill_colors(&still)); + // Nor does black ink alone, nor a gray, as a process stroke color. + for key in [Color::cmyk(0.0, 0.0, 0.0, 1.0), Color::cmyk(0.0, 0.0, 0.0, 0.5), Color::gray(0.4)] { + let key = StrokeLayer::new(Paint::solid(key), 1.0); + let turned = stroke_pieces(&doc, &jittered(Color::BLACK, Colorization::Tints, 180.0), &path, &key); + let still = stroke_pieces(&doc, &jittered(Color::BLACK, Colorization::Tints, 0.0), &path, &key); + assert_eq!(fill_colors(&turned), fill_colors(&still), "{key:?}"); + } + // A turned process color stays a process color, turned over its C, M and Y with its K kept. + let cmyk = fill_colors(&stroke_pieces(&doc, &jittered(Color::cmyk(0.0, 1.0, 1.0, 0.25), Colorization::None, 60.0), &path, &stroke(1.0))); + assert!(cmyk.iter().any(|c| *c != Color::cmyk(0.0, 1.0, 1.0, 0.25)), "{cmyk:?}"); + for c in &cmyk { + let Color::Cmyk { c, m, y, k } = *c else { panic!("not CMYK: {c:?}") }; + assert_eq!(k, 0.25); + // Full ink in one channel and none in another, as the color before it. + assert!(near(f64::from(c.max(m).max(y)), 1.0, 1e-4) && near(f64::from(c.min(m).min(y)), 0.0, 1e-4), "{c} {m} {y}"); + } + // An RGB color keeps its saturation and brightness in its own values. + let rgb = fill_colors(&stroke_pieces(&doc, &jittered(Color::rgb(0.8, 0.2, 0.4), Colorization::None, 90.0), &path, &stroke(1.0))); + for c in &rgb { + let Color::Rgb { r, g, b } = *c else { panic!("not RGB: {c:?}") }; + assert!(near(f64::from(r.max(g).max(b)), 0.8, 1e-4) && near(f64::from(r.min(g).min(b)), 0.2, 1e-4), "{c:?}"); + } + // A Lab color keeps its lightness and chroma. + let lab = fill_colors(&stroke_pieces(&doc, &jittered(Color::lab(50.0, 40.0, 30.0), Colorization::None, 90.0), &path, &stroke(1.0))); + assert!(lab.iter().any(|c| *c != Color::lab(50.0, 40.0, 30.0)), "{lab:?}"); + for c in &lab { + let Color::Lab { l, a, b } = *c else { panic!("not Lab: {c:?}") }; + assert!(l == 50.0 && near(f64::from(a.hypot(b)), 50.0, 1e-3), "{c:?}"); + } +} + +/// Hue jitter turns type's characters, the colors Tints and Shades and Hue Shift give, and a color +/// linked to a swatch (which loses the link); a pattern paint stays. +#[test] +fn hue_jitter_turns_type_every_colorization_and_linked_colors() { + let doc = Document::new(1.0, 1.0); + let path = line(0.0, 0.0, 200.0, 0.0); + let red = Paint::solid(Color::rgb(1.0, 0.0, 0.0)); + let typed = |hue_jitter| Brush { + name: "s".into(), + kind: BrushKind::Scatter(Scatter { art: type_art(red.clone(), red.clone()), hue_jitter, ..Default::default() }), + }; + let still = run_paints(&stroke_pieces(&doc, &typed(0.0), &path, &stroke(1.0))); + let turned = run_paints(&stroke_pieces(&doc, &typed(90.0), &path, &stroke(1.0))); + assert!(!still.is_empty() && still.iter().all(|p| *p == (red.clone(), red.clone())), "{still:?}"); + assert_eq!(turned.len(), still.len()); + assert!(turned.iter().any(|p| *p != (red.clone(), red.clone())), "the characters turn: {turned:?}"); + assert!(turned.iter().all(|(f, s)| f == s), "a copy's character fill and stroke turn by the same amount: {turned:?}"); + // Tints and Shades and Hue Shift: the colors they give turn. + let blue = StrokeLayer::new(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 1.0); + for colorization in [Colorization::TintsAndShades, Colorization::HueShift { key: Color::rgb(1.0, 0.0, 0.0) }] { + let art = Color::rgb(1.0, 0.0, 0.0); + let still = fill_colors(&stroke_pieces(&doc, &jittered(art, colorization, 0.0), &path, &blue)); + let turned = fill_colors(&stroke_pieces(&doc, &jittered(art, colorization, 45.0), &path, &blue)); + assert_eq!(turned.len(), still.len()); + assert_ne!(turned, still, "{colorization:?}"); + for (t, s) in turned.iter().zip(&still) { + assert!(hue_gap(t.to_hsb()[0], s.to_hsb()[0]) <= 45.01, "{colorization:?}: {t:?} from {s:?}"); + } + } + // A color linked to a swatch turns and loses the link; a pattern paint stays. + let linked = Paint::Solid { color: Color::rgb(1.0, 0.0, 0.0), swatch: Some("Red".into()), tint: 1.0 }; + let pattern = Paint::Pattern { pattern: "Dots".into(), xf: Affine::IDENTITY }; + let mut art = rect_art(10.0, 4.0); + art.appearance.set_fill(linked.clone()); + art.appearance.set_stroke(pattern.clone()); + let b = |hue_jitter| Brush { name: "s".into(), kind: BrushKind::Scatter(Scatter { art: art.clone(), hue_jitter, ..Default::default() }) }; + let still = stroke_pieces(&doc, &b(0.0), &path, &stroke(1.0)); + let turned = stroke_pieces(&doc, &b(90.0), &path, &stroke(1.0)); + assert!(!still.is_empty() && still.iter().all(|n| n.appearance.fill_paint() == linked)); + assert_eq!(turned.len(), still.len()); + for n in &turned { + assert!(matches!(n.appearance.fill_paint(), Paint::Solid { swatch: None, .. }), "{:?}", n.appearance.fill_paint()); + assert_eq!(n.appearance.stroke().map(|s| &s.paint), Some(&pattern)); + } +} + /// An instance whose fill has an opacity of 0 does not stain its symbol's art, so the art keeps its /// swatch links. #[test] diff --git a/crates/doc/src/dimension.rs b/crates/doc/src/dimension.rs index e803d867fc..9e78d17d4d 100644 --- a/crates/doc/src/dimension.rs +++ b/crates/doc/src/dimension.rs @@ -112,6 +112,18 @@ pub enum ArrowStyle { None, } +impl ArrowStyle { + /// The stroke arrowhead drawn at each end of the dimension line, or None for no head. + pub fn arrowhead(self) -> Option { + match self { + Self::Filled => Some(crate::Arrowhead::Triangle), + Self::Open => Some(crate::Arrowhead::TriangleOpen), + Self::Tick => Some(crate::Arrowhead::Slash), + Self::None => None, + } + } +} + /// Where the label sits across the dimension line. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs index f4a307cd5c..4365f7788a 100644 --- a/crates/doc/src/document.rs +++ b/crates/doc/src/document.rs @@ -339,6 +339,7 @@ impl Document { /// Index path from the top-level layer list to `id` (e.g. `[0, 3, 1]`): the first place in /// tree order where `id` appears. pub fn index_path(&self, id: NodeId) -> Option> { + crate::id_index::note_path_lookup(); // The cached path, while the node there still has the id ([`id_index`]). let cached = self.index.get(); match cached.as_ref().and_then(|m| m.get(&id)) { @@ -423,6 +424,44 @@ impl Document { out } + /// Every node whose id is in `ids`, in tree order (the order of [`Document::walk`]): unlike + /// [`Document::index_paths`], an id that appears more than once (a damaged file) gives every + /// node that has it. When the cache ([`id_index`]) holds each id once, at a path that still + /// checks out, the nodes are found along those paths; otherwise one walk of the tree finds + /// them. As for every cached lookup, a second node given an existing id after the cache was + /// built is not found while the first one's cached path checks out (see [`id_index`]). + pub fn nodes_in_order(&self, ids: impl IntoIterator) -> Vec<&Node> { + let want: std::collections::HashSet> = ids.into_iter().collect(); + // As in `index_paths`, one walk is quicker than checking the cached paths of a good share + // of the document. + if let Some(cache) = self.index.get().filter(|c| want.len().saturating_mul(8) < c.len()) { + let mut paths = Vec::with_capacity(want.len()); + let cached = want.iter().all(|id| match cache.get(id) { + Some(Some(p)) if self.node_at(&p).is_some_and(|n| n.id == *id) => { + paths.push(p); + true + } + _ => false, + }); + if cached { + // A node's path sorts after the paths of the nodes before it in tree order, its + // ancestors included. + paths.sort_unstable(); + return paths.iter().filter_map(|p| self.node_at(p)).collect(); + } + } + let mut out = Vec::new(); + if !want.is_empty() { + crate::id_index::note_tree_walk(); + self.walk(|n| { + if want.contains(&n.id) { + out.push(n); + } + }); + } + out + } + /// The node at index path `path` (as [`Document::index_path`] gives it). pub fn node_at(&self, path: &[usize]) -> Option<&Node> { let (first, rest) = path.split_first()?; diff --git a/crates/doc/src/hit.rs b/crates/doc/src/hit.rs index 6a32a21bbc..93baa85ed8 100644 --- a/crates/doc/src/hit.rs +++ b/crates/doc/src/hit.rs @@ -2096,7 +2096,9 @@ pub fn compound_part_at(n: &Node, p: Point, tol: f64) -> Option { /// Objects (children of layers, or of `scope` in isolation mode) touched by a marquee rect, leaving /// out those on a locked artboard ([`crate::LockedArtboards::holds_id`]). Symbol instances are measured /// by their art ([`Node::geometric_bounds_with`]), and outside that box, except in outline, they are -/// touched where the live geometry effects of a clipping path in their art show it. The art of a clip group or of a layer with a +/// touched where the live geometry effects of a clipping path in their art show it, or where the +/// geometry effects of their active fill or stroke reshape the art. Images are also touched, except +/// in outline, where their own fills and strokes paint outside their box. The art of a clip group or of a layer with a /// clipping mask counts only when the marquee meets the region its clipping path clips to, and then /// only within that region's bounds. In isolation mode the clipping mask of the isolated container, /// or of the parent of the single object isolated, does not limit the marquee, as it does not limit @@ -2265,8 +2267,10 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option, leaves: bool, wh /// Does the marquee `r` touch `n`? It skips the children of a Shaper Group that clicks skip /// ([`shaper_hides`]). An Intertwine group is touched by its members, and a repeat is touched /// by the copies it draws, as clicks hit them. Objects of every other kind except paths, - /// compound paths, layers and groups are touched by their box. A clipping path is touched by - /// its own geometry ([`mask_marquee`]) and on the edge of its region ([`clip_edge_touches`]). + /// compound paths, layers and groups are touched by their box, and an image or a symbol + /// instance also where its fills and strokes paint outside it ([`painted_touches`]). A clipping + /// path is touched by its own geometry ([`mask_marquee`]) and on the edge of its region + /// ([`clip_edge_touches`]). fn touches(n: &Node, s: &SymbolBoxes, r: Rect, scope: Option, whole_compounds: bool, outline: bool) -> bool { // A path or compound path whose geometry effects reshape it, or a group or layer whose own // geometry effects reshape its members, is touched where that art is drawn ([`drawn_art`]). @@ -2296,12 +2300,27 @@ fn marquee_with(doc: &Document, r: Rect, scope: Option, leaves: bool, wh NodeKind::Compound { children, .. } => children.iter().any(|c| c.visible && touches(c, s, r, scope, whole_compounds, outline)), NodeKind::Repeat(spec) => spec.expand(Some(s.document())).iter().any(|copy| touches(copy, s, r, scope, whole_compounds, outline)), // A symbol instance is touched by its box, and outside it where the live geometry - // effects of a clipping path in its art show the art. In the art of another instance - // walked outside that instance's box, it is touched only by its own art ([`ArtOnly`]). - NodeKind::SymbolInstance { .. } => !ArtOnly::on() && box_touches(n, s, r) || !outline && instance_art_touches(n, s, r, whole_compounds), + // effects of a clipping path in its art show the art, or where the geometry effects of + // its active fill or stroke reshape the art ([`painted_touches`]). In the art of another + // instance walked outside that instance's box, it is touched only by its own art + // ([`ArtOnly`]) and those shapes. + NodeKind::SymbolInstance { .. } => { + !ArtOnly::on() && box_touches(n, s, r) || !outline && (instance_art_touches(n, s, r, whole_compounds) || painted_touches(n, s, r)) + } + // An image is touched by its box, and outside it where its own fills and strokes paint. + NodeKind::Image(_) => box_touches(n, s, r) || !outline && painted_touches(n, s, r), _ => box_touches(n, s, r), } } + /// Does the marquee `r` touch the shapes that the fills and strokes of image or symbol + /// instance `n` paint ([`image_paint`]), where clicks hit them ([`hit_painted`])? Each shape is + /// touched by its path, as a path is ([`vectorcraft_geom::hit::intersects_rect`]). Only when + /// `r` meets the reach of `n` ([`Node::reach_bounds_with`]). + fn painted_touches(n: &Node, s: &SymbolBoxes, r: Rect) -> bool { + let meets = |b: Rect| b.x0 <= r.x1 && r.x0 <= b.x1 && b.y0 <= r.y1 && r.y0 <= b.y1; + n.reach_bounds_with(s).is_some_and(meets) + && image_paint(Some(s.document()), n).iter().any(|(bp, _, _)| vectorcraft_geom::hit::intersects_rect(&PathData::from_bezpath(bp), r)) + } /// Does the marquee `r` touch the box of `n`? A box with no width or no height (an instance of /// a symbol that draws a straight line) is touched where the marquee crosses it. fn box_touches(n: &Node, s: &SymbolBoxes, r: Rect) -> bool { diff --git a/crates/doc/src/id_index.rs b/crates/doc/src/id_index.rs index ed89f6ead4..149a8e488b 100644 --- a/crates/doc/src/id_index.rs +++ b/crates/doc/src/id_index.rs @@ -82,6 +82,16 @@ impl Paths { pub(crate) fn len(&self) -> usize { self.ids.len() } + /// The entry of `id` in the table: `Some(None)` when the id appears more than once, `None` + /// when it isn't in the table. + pub(crate) fn entry(&self, id: &NodeId) -> Option> { + self.ids.get(id).copied() + } + /// Entry `e`'s parent entry (`u32::MAX` for a top-level layer) and its index among its + /// siblings. + pub(crate) fn place(&self, e: u32) -> Option<(u32, u32)> { + self.at.get(e as usize).copied() + } } /// Lookups that had to walk (the cache didn't have the id, or its path no longer checks out) @@ -108,6 +118,22 @@ pub(crate) fn note_tree_walk() { TREE_WALKS.set(TREE_WALKS.get().saturating_add(1)); } +thread_local! { + /// [`path_lookups`] of this thread. + static PATH_LOOKUPS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// How many times [`crate::Document::index_path`] has run on this thread, the lookups that +/// [`crate::Document::node`] and [`crate::Document::ancestry`] make through it included. +pub fn path_lookups() -> u64 { + PATH_LOOKUPS.get() +} + +/// Adds one to [`path_lookups`]. +pub(crate) fn note_path_lookup() { + PATH_LOOKUPS.set(PATH_LOOKUPS.get().saturating_add(1)); +} + /// The cache, shared by clones of a document (each checks every path it uses against its own tree). #[derive(Default)] pub struct IdIndex(RwLock>>, std::sync::atomic::AtomicU32); diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 7ad3a8d108..123e31bc08 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -21,7 +21,7 @@ pub mod graph; mod halftone_radii; pub mod hit; mod id_index; -pub use id_index::tree_walks; +pub use id_index::{path_lookups, tree_walks}; pub mod inks; mod inline; pub mod intertwine; @@ -48,6 +48,8 @@ pub mod marks; mod mem; pub use mem::{appearance_heap_bytes, paint_heap_bytes}; pub mod metadata; +mod nearest; +pub use nearest::NearestFinder; pub mod node; pub mod objects_on_path; pub mod orient; diff --git a/crates/doc/src/nearest.rs b/crates/doc/src/nearest.rs new file mode 100644 index 0000000000..0adc6269f9 --- /dev/null +++ b/crates/doc/src/nearest.rs @@ -0,0 +1,90 @@ +//! The nearest node of a kind at or above each of many objects, found along one index path per +//! object. + +use std::sync::Arc; + +use crate::id_index::Paths; +use crate::{Document, Node, NodeId}; + +/// Finds, for one object after another, the nearest node that passes a test: the object itself, +/// then its parent, and so on up to its layer. Made by [`Document::nearest_finder`]. +/// +/// Each node on the way is tested as [`Document::node`] gives its id, so the answer is the one that +/// `doc.ancestry(id)` read from the end, with `doc.node` for each id, gives. While the lookup cache +/// places the object and each id on its path where they are, a lookup reads that one path; an id +/// the cache does not place there (one that appears more than once, or a cache older than the +/// tree) is looked up with [`Document::node`]. +pub struct NearestFinder<'a> { + doc: &'a Document, + cache: Option>, + /// The cache entries from the top-level layer down to the object. + entries: Vec, + /// The nodes at those entries. + nodes: Vec<&'a Node>, +} + +impl Document { + /// A [`NearestFinder`] for this document. + pub fn nearest_finder(&self) -> NearestFinder<'_> { + NearestFinder { doc: self, cache: self.index.get(), entries: vec![], nodes: vec![] } + } +} + +impl<'a> NearestFinder<'a> { + /// The node nearest `id` (itself, then its parent, and so on up to its layer) for which `pred` + /// holds; `None` when `id` is not in the tree or no node on its path passes. + pub fn nearest(&mut self, id: NodeId, mut pred: impl FnMut(&Node) -> bool) -> Option<&'a Node> { + let doc = self.doc; + let ids: Vec = if self.cached_path(id) { + let cache = self.cache.as_deref()?; + // The depth of the first id from the object up that the cache does not place there. + let mut unplaced = None; + for (k, (&node, &e)) in self.nodes.iter().zip(&self.entries).enumerate().rev() { + if cache.entry(&node.id) != Some(Some(e)) { + unplaced = Some(k); + break; + } + if pred(node) { + return Some(node); + } + } + let k = unplaced?; + self.nodes[..=k].iter().map(|n| n.id).collect() + } else { + doc.ancestry(id).unwrap_or_default() + }; + let found = ids.into_iter().rev().find_map(|a| doc.node(a).filter(|n| pred(n))); + // Those lookups may have built the cache again. + self.cache = doc.index.get(); + found + } + + /// Fill `entries` and `nodes` with the cached path to `id`; false when the cache has no path for + /// it or the path no longer leads to it. + fn cached_path(&mut self, id: NodeId) -> bool { + self.entries.clear(); + self.nodes.clear(); + let Some(cache) = self.cache.as_deref() else { return false }; + let Some(Some(mut e)) = cache.entry(&id) else { return false }; + loop { + let Some((parent, _)) = cache.place(e) else { return false }; + self.entries.push(e); + if parent == u32::MAX { + break; + } + // A parent's entry is made before its children's, so the walk up ends. + if parent >= e { + return false; + } + e = parent; + } + self.entries.reverse(); + let mut siblings: &'a [Arc] = &self.doc.layers; + for &e in &self.entries { + let Some(n) = cache.place(e).and_then(|(_, i)| siblings.get(i as usize)) else { return false }; + self.nodes.push(&**n); + siblings = n.children().map_or(&[], |c| c.as_slice()); + } + self.nodes.last().is_some_and(|n| n.id == id) + } +} diff --git a/crates/doc/src/setup.rs b/crates/doc/src/setup.rs index 4dd8394ce2..e91542fe1a 100644 --- a/crates/doc/src/setup.rs +++ b/crates/doc/src/setup.rs @@ -220,6 +220,13 @@ pub fn language_quotes(language: &str) -> Option { LANGUAGES.iter().find(|(l, _, _)| l.eq_ignore_ascii_case(language)).map(|(_, _, q)| *q) } +/// The BCP 47 tag of the [`LANGUAGES`] entry named or tagged `language` (case-insensitive), the +/// default's included (`en-US`): what a document's language ([`DocSetup::language`]) is written +/// as in an exported file. `None` for a language not in the list. +pub fn language_tag(language: &str) -> Option<&'static str> { + LANGUAGES.iter().find(|(n, t, _)| n.eq_ignore_ascii_case(language) || t.eq_ignore_ascii_case(language)).map(|(_, t, _)| *t) +} + /// The [`LANGUAGES`] entry named or tagged `language` (case-insensitive) as a character's /// language ([`crate::CharStyle::language`]) stores it: its tag, or `None` for the default (the /// first entry); `Err` for a language not in the list. @@ -404,6 +411,16 @@ impl DocSetup { mod tests { use super::*; + /// A document's language is written by its tag, the default's included (#3644). + #[test] + fn document_languages_have_their_tags() { + assert_eq!(language_tag(&DocSetup::default().language), Some("en-US")); + assert_eq!(language_tag("French"), Some("fr")); + assert_eq!(language_tag("german: swiss"), Some("de-CH")); + assert_eq!(language_tag("sr-latn"), Some("sr-Latn")); + assert_eq!((language_tag("Klingon"), language_tag("")), (None, None)); + } + /// Characters store a language of the list by its tag, the default as none. #[test] fn char_languages_are_stored_by_tag() { diff --git a/crates/doc/src/tests/lookups.rs b/crates/doc/src/tests/lookups.rs index 2f83b65c5e..9c5c278a53 100644 --- a/crates/doc/src/tests/lookups.rs +++ b/crates/doc/src/tests/lookups.rs @@ -157,6 +157,58 @@ fn cached_lookups_follow_any_edit_of_the_tree() { } } +/// Every node whose id is in `ids`, by walking the tree. +fn every_node(d: &Document, ids: &[NodeId]) -> Vec<*const Node> { + let mut out = vec![]; + d.walk(|n| { + if ids.contains(&n.id) { + out.push(n as *const Node); + } + }); + out +} + +/// [`Document::nodes_in_order`] gives every node with each id in tree order, repeated ids +/// included, with the cache built and without it, for a few ids (cached paths) and for many (a +/// walk). +#[test] +fn nodes_in_order_match_a_walk() { + for seed in 1..40 { + let (d, ids) = tree(seed); + let few: Vec = ids.iter().copied().step_by(17).collect(); + for cold in [true, false] { + if cold { + d.drop_lookup_cache(); + } else { + d.node(ids[0]); + } + for list in [&ids[..], &few[..], &ids[ids.len() / 2..ids.len() / 2 + 1], &[]] { + let found: Vec<*const Node> = d.nodes_in_order(list.iter().copied()).into_iter().map(|n| n as *const Node).collect(); + assert_eq!(found, every_node(&d, list), "seed {seed}, cold {cold}, {list:?}"); + } + } + // An id that the tree repeats: every node with it. + let Some(dup) = ids.iter().enumerate().find(|(i, id)| ids[..*i].contains(id)).map(|(_, id)| *id) else { continue }; + assert!(d.nodes_in_order([dup]).len() >= 2, "seed {seed}: {dup:?} is in the tree more than once"); + // A second node given an id once held once, after the cache was built: the lookup finds the + // cached node, which has that id; with the cache built afresh, both. + let mut d = d; + let once = ids.iter().copied().find(|id| every_node(&d, &[*id]).len() == 1 && d.node(*id).is_some_and(|n| !n.is_layer())); + let Some(once) = once else { continue }; + d.node(once); + let copy = Arc::new(Node::path(once, shapes::rectangle(Rect::new(0.0, 0.0, 2.0, 2.0)), Appearance::default_art())); + if let Some(ch) = Arc::make_mut(&mut d.layers[0]).children_mut() { + ch.insert(0, copy); + } + let found = d.nodes_in_order([once]); + assert!(!found.is_empty() && found.iter().all(|n| n.id == once), "seed {seed}: {once:?}"); + d.drop_lookup_cache(); + d.node(once); + let found: Vec<*const Node> = d.nodes_in_order([once]).into_iter().map(|n| n as *const Node).collect(); + assert_eq!(found, every_node(&d, &[once]), "seed {seed}: {once:?} cached afresh"); + } +} + /// Nodes of `d` picked and ordered by `seed`. None lies inside another, and each of them, and each /// node it is in, appears in the tree once. fn picks(d: &Document, seed: u64) -> Vec { @@ -282,3 +334,112 @@ fn edits_of_many_refuse_missing_repeated_and_nested_ids() { assert_eq!(serde_json::to_string(&b).ok(), saved, "{what}: the document stays as it was"); } } + +/// The nearest node passing `pred` at or above `id`, as `ancestry` read from the end with `node` +/// for each id finds it. +fn nearest_by_ancestry(d: &Document, id: NodeId, pred: impl Fn(&Node) -> bool) -> Option<*const Node> { + d.ancestry(id).unwrap_or_default().into_iter().rev().find_map(|a| d.node(a).filter(|n| pred(n))).map(|n| n as *const Node) +} + +/// [`Document::nearest_finder`] gives what [`nearest_by_ancestry`] gives for every id, on a clone +/// each, so both start from the same cache. +fn nearest_agrees(d: &Document, ids: &[NodeId], what: &str) { + type Pred = fn(&Node) -> bool; + let preds: [(&str, Pred); 5] = [ + ("group", |n| matches!(n.kind, NodeKind::Group { .. })), + ("layer", |n| n.is_layer()), + ("any", |_| true), + ("none", |_| false), + ("id divisible by 3", |n| n.id.0 % 3 == 0), + ]; + for (name, pred) in preds { + let (a, b) = (d.clone(), d.clone()); + let want: Vec<_> = ids.iter().map(|id| nearest_by_ancestry(&a, *id, pred)).collect(); + let mut find = b.nearest_finder(); + let got: Vec<_> = ids.iter().map(|id| find.nearest(*id, pred).map(|n| n as *const Node)).collect(); + assert_eq!(got, want, "{what}: {name}"); + } +} + +#[test] +fn nearest_finder_matches_the_ancestry_walk() { + for seed in 1..30 { + let (mut d, ids) = tree(seed); + nearest_agrees(&d, &ids, "no cache"); + d.node(ids[0]); + nearest_agrees(&d, &ids, "cached"); + // Every path in the first layer shifts: the cache is stale there. + let extra = d.alloc_id(); + let leaf = Arc::new(Node::path(extra, shapes::rectangle(Rect::new(0.0, 0.0, 1.0, 1.0)), Appearance::default_art())); + if let Some(ch) = Arc::make_mut(&mut d.layers[0]).children_mut() { + ch.insert(0, leaf); + } + nearest_agrees(&d, &ids, "a stale cache"); + // A group with the id of a node in the last layer, earlier in tree order than it, put in + // after the cache was built. + d.drop_lookup_cache(); + d.node(ids[0]); + let last = d.layers.len() - 1; + let dup = d.layers[last].children().and_then(|c| c.last()).map(|n| n.id); + if let Some(dup) = dup + && let Some(ch) = Arc::make_mut(&mut d.layers[0]).children_mut() + { + ch.insert(0, Arc::new(Node::group(dup, vec![]))); + } + nearest_agrees(&d, &ids, "a duplicate put in after the cache was built"); + d.drop_lookup_cache(); + nearest_agrees(&d, &ids, "a duplicate, cached afresh"); + } +} + +/// An id on the path that an earlier node of another kind also has: the earlier node is the one +/// tested, as `node` gives it. +#[test] +fn nearest_finder_tests_the_first_node_with_a_repeated_id() { + let mut d = Document::new(612.0, 792.0); + let layer = d.layers[0].id; + let leaf = |id: u64| Arc::new(Node::path(NodeId(id), shapes::rectangle(Rect::new(0.0, 0.0, 5.0, 5.0)), Appearance::default_art())); + d.insert(Some(layer), 0, Node::group(NodeId(500), vec![leaf(501)])).unwrap(); + d.insert(Some(layer), 1, Node::path(NodeId(600), shapes::rectangle(Rect::new(0.0, 0.0, 5.0, 5.0)), Appearance::default_art())).unwrap(); + // A group that has the path's id, after the path in tree order. + d.insert(Some(layer), 2, Node::group(NodeId(600), vec![leaf(601)])).unwrap(); + let is_group = |n: &Node| matches!(n.kind, NodeKind::Group { .. }); + for cached in [false, true] { + d.drop_lookup_cache(); + if cached { + d.node(layer); + } + let mut find = d.nearest_finder(); + assert_eq!(find.nearest(NodeId(501), is_group).map(|n| n.id), Some(NodeId(500)), "cached {cached}"); + assert_eq!(find.nearest(NodeId(601), is_group).map(|n| n.id), None, "cached {cached}: id 600 is the path"); + assert_eq!(find.nearest(NodeId(999_999), is_group).map(|n| n.id), None, "cached {cached}: not in the tree"); + } +} + +/// With the cache built, finding the nearest group of every object of a large tree looks no id up +/// and walks the tree no time. +#[test] +fn nearest_finder_reads_one_path_per_object() { + let mut d = Document::new(612.0, 792.0); + let layer = d.layers[0].id; + let mut leaves = vec![]; + for g in 0..2_000 { + let kids: Vec> = (0..3) + .map(|_| { + let id = d.alloc_id(); + leaves.push(id); + Arc::new(Node::path(id, shapes::rectangle(Rect::new(0.0, 0.0, 5.0, 5.0)), Appearance::default_art())) + }) + .collect(); + let gid = d.alloc_id(); + d.insert(Some(layer), g, Node::group(gid, kids)).unwrap(); + } + d.drop_lookup_cache(); + d.node(layer); + let (lookups, walks) = (path_lookups(), tree_walks()); + let mut find = d.nearest_finder(); + let found = leaves.iter().filter(|id| find.nearest(**id, |n| matches!(n.kind, NodeKind::Group { .. })).is_some()).count(); + assert_eq!(found, leaves.len()); + assert_eq!(path_lookups() - lookups, 0, "lookups by id"); + assert_eq!(tree_walks() - walks, 0, "walks of the tree"); +} diff --git a/crates/effects/src/catalog.rs b/crates/effects/src/catalog.rs index 9e829c70d3..b17045e934 100644 --- a/crates/effects/src/catalog.rs +++ b/crates/effects/src/catalog.rs @@ -189,7 +189,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, see threeD.mapGraphic: symbol: name of a document symbol, face: front|back (front; the back reads left to right as seen from behind), x: pt (0; the offset of the graphic's center from the center of the object's bounds, in the face's own plane), y: pt (0), scale: % (1..10000, 100; of the symbol's own size), rotation: degrees (-360..360, 0; counterclockwise); drawn turned, foreshortened and shaded with the cap and clipped to it, on a solid cap only), 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), 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).", 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( diff --git a/crates/effects/src/lib.rs b/crates/effects/src/lib.rs index 9eae81118a..7eec83c7f5 100644 --- a/crates/effects/src/lib.rs +++ b/crates/effects/src/lib.rs @@ -103,8 +103,8 @@ pub use solids::{ validate_three_d_params, view_options, with_graphic, }; pub use solids::{ - GRAPHIC_MAX_OFFSET, GRAPHIC_SCALE_RANGE, GRAPHICS_NOT_TAKEN, appearance_graphic_symbols, exports_three_d, graphic_frame_at, - graphics_reshaped_after, rename_appearance_graphic_symbol, + GRAPHIC_MAX_OFFSET, GRAPHIC_SCALE_RANGE, GRAPHICS_NOT_TAKEN, appearance_graphic_symbols, exports_three_d, graphic_fitting_scale, + graphic_frame_at, graphic_side_size, graphics_reshaped_after, rename_appearance_graphic_symbol, }; pub use stylize::{ScribbleSetting, scribble_setting_id, scribble_settings}; pub use svg_filter::SVG_FILTER; diff --git a/crates/effects/src/solids.rs b/crates/effects/src/solids.rs index 27f006e64e..bdbe16547a 100644 --- a/crates/effects/src/solids.rs +++ b/crates/effects/src/solids.rs @@ -30,7 +30,7 @@ pub use graphics::{ }; pub use graphics::{ MAX_OFFSET as GRAPHIC_MAX_OFFSET, NOT_TAKEN as GRAPHICS_NOT_TAKEN, SCALE_RANGE as GRAPHIC_SCALE_RANGE, appearance_graphic_symbols, - rename_appearance_graphic_symbol, + fitting as graphic_fitting_scale, rename_appearance_graphic_symbol, }; pub(crate) mod shadow; @@ -84,11 +84,16 @@ pub fn three_d_params_as(from: &str, params: &Value, to: &str) -> Value { } } // A plane has only a front, and Revolve's graphics go on its side, named the front, so graphics - // on the back cap are dropped. - if (to == ROTATE || to == crate::REVOLVE) + // on the back cap and on Extrude & Bevel's side are dropped. Inflate takes graphics on its front + // and back, so it drops those on the side. + if (to == ROTATE || to == crate::REVOLVE || to == INFLATE) && let Some(Value::Array(list)) = out.get_mut(GRAPHICS) { - list.retain(|g| g.get("face").and_then(Value::as_str) != Some(PlanarFace::Back.id())); + let back = to != INFLATE; + list.retain(|g| { + let face = g.get("face").and_then(Value::as_str); + !(back && face == Some(PlanarFace::Back.id())) && face != Some(PlanarFace::Side.id()) + }); } Value::Object(out) } @@ -177,6 +182,7 @@ pub fn extrude_options(p: &Value) -> Extrude { both_sides: flag(p, "bevelBothSides", false), }), hidden: false, + map_surface: false, } } @@ -254,6 +260,56 @@ fn facets(id: &str, path: &PathData, rule: FillRule, bounds: Rect, p: &Value) -> } } +/// [`facets`] of Extrude & Bevel with parameters `p`, with the pieces of the side of its longest +/// contour carrying where they lie on it unrolled ([`Facet::surface`]), for its side's graphics. +fn side_facets(path: &PathData, rule: FillRule, bounds: Rect, p: &Value) -> Result, String> { + #[cfg(test)] + SOLID_GEOMETRY_BUILT.with(|n| n.set(n.get() + 1)); + vectorcraft_three_d::extrude(path, rule, bounds, Extrude { map_surface: true, ..extrude_options(p) }, view_options(p)) +} + +/// [`side_facets`], and with `cast` the faces the solid's shadow is cast from, from the same build +/// ([`facets_and_faces`]). +fn side_facets_and_faces(path: &PathData, rule: FillRule, bounds: Rect, p: &Value, cast: bool) -> Result { + if !cast { + return side_facets(path, rule, bounds, p).map(|f| (f, None)); + } + #[cfg(test)] + SOLID_GEOMETRY_BUILT.with(|n| n.set(n.get() + 1)); + let options = Extrude { map_surface: true, ..extrude_options(p) }; + vectorcraft_three_d::extrude_shadowed(path, rule, bounds, options, view_options(p)).map(|(f, faces)| (f, Some(faces))) +} + +/// The part of `parts` ([`solid_parts`]) whose solid takes the graphics on Extrude & Bevel's side, +/// with parameters `p` and built about `bounds`: the first of those with the longest outline +/// ([`vectorcraft_three_d::extrude_side_size`]). `None` when the effect `id` is not Extrude & Bevel +/// or has no graphic on its side, or when no part has a side. +fn side_carrier(id: &str, p: &Value, parts: &[Part<'_>], bounds: Rect) -> Option { + if id != EXTRUDE || !mapped_graphics(p).iter().any(|g| g.face == PlanarFace::Side) { + return None; + } + let options = extrude_options(p); + parts + .iter() + .enumerate() + .filter_map(|(k, (_, _, area, rule, _, _))| vectorcraft_three_d::extrude_side_size(area, *rule, bounds, options).map(|(w, ..)| (k, w))) + .fold(None, |best: Option<(usize, f64)>, (k, w)| if best.is_some_and(|(_, top)| top >= w) { best } else { Some((k, w)) }) + .map(|(k, _)| k) +} + +/// The size of Extrude & Bevel's side unrolled for the graphics on it: the side of the part of +/// `shapes` that [`side_carrier`] picks, with parameters `p`, as wide as the part of it about x = 0 +/// that does not reach its cut and as tall as the length across its bevels and walls. +fn side_size(p: &Value, shapes: &[Profile]) -> Option<(f64, f64)> { + let (parts, bounds) = solid_parts(shapes, union_bounds(shapes)?); + let options = extrude_options(p); + parts + .iter() + .filter_map(|(_, _, area, rule, _, _)| vectorcraft_three_d::extrude_side_size(area, *rule, bounds, options)) + .fold(None, |best: Option<(f64, f64, f64)>, size| if best.is_some_and(|top| top.0 >= size.0) { best } else { Some(size) }) + .map(|(_, height, span)| (span, height)) +} + /// [`facets`], and with `cast` for Extrude & Bevel or Rotate the faces the solid's shadow is cast /// from, from the same build. Inflate's solids are built together ([`built_solids_cast`]), and the /// classic effects cast no shadow: they keep no faces. @@ -342,6 +398,7 @@ fn validate_solid_for(doc: Option<&Document>, n: &Node, id: &str, p: &Value, at: let b = union_bounds(&shapes).ok_or_else(|| format!("{label} requires a group holding a shape with at least two anchors"))?; check_profiles(id, p, &shapes, b)?; check_solids(id, p, &shapes)?; + check_side_graphics(doc, n, id, p, &shapes)?; return check_membrane_graphics(doc, n, id, p, &shapes); } let (path, rule) = object_profile(n, label)?; @@ -360,6 +417,7 @@ fn validate_solid_for(doc: Option<&Document>, n: &Node, id: &str, p: &Value, at: let shapes = [Profile { path, rule, items, opacity: 1.0, scopes: vec![] }]; check_profiles(id, p, &shapes, b)?; check_solids(id, p, &shapes)?; + check_side_graphics(doc, n, id, p, &shapes)?; check_membrane_graphics(doc, n, id, p, &shapes) } @@ -385,7 +443,7 @@ fn check_membrane_graphics(doc: Option<&Document>, n: &Node, id: &str, p: &Value if id != INFLATE || wireframe::wireframe_params(id, p) || mapped_graphics(p).is_empty() { return Ok(()); } - for face in PlanarFace::ALL { + for face in [PlanarFace::Front, PlanarFace::Back] { graphics::validate_surface_symbols(doc, p, face)?; } let fx = Effect { id: id.into(), params: p.clone(), visible: true }; @@ -398,6 +456,30 @@ fn check_membrane_graphics(doc: Option<&Document>, n: &Node, id: &str, p: &Value Ok(()) } +/// An error when the graphics on the side of Extrude & Bevel `id` with parameters `p`, with the +/// symbols of `doc`, are past their limits on the side of the solid of `shapes` that takes them +/// ([`side_carrier`]): their art, or the parts they draw on its pieces +/// ([`graphics::surface_parts`]), or when the object `n`'s surfaces can't be built at all. They are +/// built as the art builds them ([`surfaces_with`]), so its pieces are the ones the art draws, cuts +/// included. Without `doc` nothing is drawn, and nothing is checked. +fn check_side_graphics(doc: Option<&Document>, n: &Node, id: &str, p: &Value, shapes: &[Profile]) -> Result<(), String> { + let Some(doc) = doc else { return Ok(()) }; + let Some(b) = union_bounds(shapes) else { return Ok(()) }; + let (parts, bounds) = solid_parts(shapes, b); + if side_carrier(id, p, &parts, bounds).is_none() { + return Ok(()); + } + graphics::validate_surface_symbols(doc, p, PlanarFace::Side)?; + let fx = Effect { id: id.into(), params: p.clone(), visible: true }; + let mut dropped = false; + // Art that can't be built draws the source path, without the side's graphics. + let built = surfaces_with(Some(doc), n, &fx, shapes, false, false, &mut dropped); + if dropped || built.is_none() { + return Err("The graphics are too complex: simplify the symbols' art".into()); + } + Ok(()) +} + /// Do the solids 3D effect `id` with parameters `p` builds from the profiles of `shapes` about `b` /// build? Only the profiles no solid of [`check_solids`] is built from are built here: for Rotate /// every shape's, except with its shadow cast that of a shape with a visible fill, whose plane is @@ -442,7 +524,7 @@ fn check_solids(id: &str, p: &Value, shapes: &[Profile]) -> Result<(), String> { if !cast { return built_solids(id, p, &parts, bounds, MAX_OBJECT_FACES).try_for_each(|r| r.map(|_| ())); } - let built = built_solids_cast(id, p, &parts, bounds, MAX_OBJECT_FACES, true, false) + let built = built_solids_cast(id, p, &parts, bounds, MAX_OBJECT_FACES, true, false, None) .map(|r| r.map(|solid| solid.and_then(|(_, faces)| faces))) .collect::, String>>()?; cast_built(id, p, shapes, built).map(|_| ()) @@ -731,7 +813,7 @@ fn membrane_parts( ) -> Option>>> { let shade = |f: &graphics::OnFace<'_>, c: vectorcraft_doc::color::Color| Paint::solid(crate::lighting::shade(c, f.facet.illumination)); let mut out: Vec>> = vec![vec![]; facets.len()]; - for face in PlanarFace::ALL.into_iter().filter(|face| graphics.iter().any(|g| g.face == *face)) { + for face in [PlanarFace::Front, PlanarFace::Back].into_iter().filter(|face| graphics.iter().any(|g| g.face == *face)) { let on: Vec> = facets.iter().map(|facet| graphics::OnFace { facet, face }).collect(); let parts = graphics::surface_parts(doc, id, (graphics, face), &on, &shade, copies)?; for (slot, extra) in out.iter_mut().zip(parts) { @@ -742,8 +824,9 @@ fn membrane_parts( } /// `surface`, a plain group of one face for each facet ([`surface`]), with each face followed by -/// the parts of the graphics that `parts` holds for its facet ([`membrane_parts`]): a face with -/// parts becomes a group of the face and its parts, so nearer faces drawn after it cover them too. +/// the parts of the graphics that `parts` holds for its facet (on Extrude & Bevel's side +/// [`graphics::surface_parts`], on Inflate's front and back [`membrane_parts`]): a face with parts +/// becomes a group of the face and its parts, so nearer faces drawn after it cover them too. /// `surface` is returned as it is when no facet has a part or it is not such a group. fn with_surface_parts(id: NodeId, mut surface: Node, parts: Vec>>) -> Node { if parts.iter().all(Vec::is_empty) { @@ -879,7 +962,7 @@ fn built_solids<'a>( bounds: Rect, limit: usize, ) -> impl Iterator>, String>> + 'a { - built_solids_cast(id, p, parts, bounds, limit, false, false).map(|r| r.map(|s| s.map(|(f, _)| f))) + built_solids_cast(id, p, parts, bounds, limit, false, false, None).map(|r| r.map(|s| s.map(|(f, _)| f))) } /// One solid's facets and, when its shadow is cast, the faces it is cast from. @@ -892,7 +975,10 @@ type SurfacesAndFaces = (Vec>, Vec>); /// [`built_solids`], and with `cast` for Extrude & Bevel or Inflate each solid's faces its shadow /// is cast from, from the same build ([`SolidFaces`]). With `membrane`, Inflate's solids are built /// with the pieces of their front and puffed back carrying where they lie in the art's plane, for -/// the graphics drawn on them ([`vectorcraft_three_d::Inflate::map_surface`]). +/// the graphics drawn on them ([`vectorcraft_three_d::Inflate::map_surface`]). The solid of part +/// `side`, when there is one, is built with the pieces of its side carrying where they lie on it +/// unrolled, for the graphics on Extrude & Bevel's side ([`side_carrier`]). +#[allow(clippy::too_many_arguments)] // the build's inputs and the two surfaces that carry graphics fn built_solids_cast<'a>( id: &'a str, p: &'a Value, @@ -901,6 +987,7 @@ fn built_solids_cast<'a>( limit: usize, cast: bool, membrane: bool, + side: Option, ) -> impl Iterator, String>> + 'a { // Inflate's eye is placed for every puff together, as far away as the highest needs. let mut inflated = (id == INFLATE).then(|| -> Box>> { @@ -914,7 +1001,7 @@ fn built_solids_cast<'a>( }); let mut kept = 0usize; let mut ended = false; - parts.iter().map_while(move |(item, _, area, rule, _, _)| { + parts.iter().enumerate().map_while(move |(k, (item, _, area, rule, _, _))| { if ended { return None; } @@ -926,6 +1013,7 @@ fn built_solids_cast<'a>( SOLID_GEOMETRY_BUILT.with(|n| n.set(n.get() + 1)); each.next().unwrap_or_else(|| Ok((vec![], None))) } + None if side == Some(k) => side_facets_and_faces(area, *rule, bounds, p, cast), None => facets_and_faces(id, area, *rule, bounds, p, cast), }; let result = match built { @@ -1178,6 +1266,8 @@ fn cut(s: &Facet, c: &[Point], wall: &Facet, outline: &[Point], turn: f64) -> Op f.depth = s.depth_at(mid).unwrap_or(s.depth); f.contours = vec![points]; f.outline = s.outline.as_ref().and_then(|o| clip_to_side(o, c, &values, sign)); + // A piece keeps where the whole face lies on the side: the parts of the side's graphics + // drawn on it are cut to its own outline ([`graphics::SurfaceFace::curved`]). Some(f) }; Some((piece(1.0)?, piece(-1.0)?)) @@ -1869,8 +1959,9 @@ fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile } /// [`surfaces_for`], with `membrane` building Inflate's solids with their front and puffed back -/// carrying the graphics ([`built_solids_cast`]), and setting `dropped` when those graphics are past -/// their limits on the pieces drawn and the solids draw without them. +/// carrying the graphics ([`built_solids_cast`]), and setting `dropped` when those graphics, or the +/// graphics on Extrude & Bevel's side, are past their limits on the pieces drawn and the solid that +/// takes them draws without them. fn surfaces_with( doc: Option<&Document>, n: &Node, @@ -1922,10 +2013,13 @@ fn surfaces_with( return Some((if masks { masked(n.id, out) } else { out.into_iter().map(|(_, s)| s).collect() }, built)); } let (parts, bounds) = solid_parts(shapes, b); + // The graphics on Extrude & Bevel's side go once, on the side of the solid with the longest + // outline, whose pieces are built carrying where they lie on it. + let carrier = if graphics_on { side_carrier(&fx.id, &p, &parts, bounds) } else { None }; let mut solids = vec![]; let mut built = vec![]; - let made = built_solids_cast(&fx.id, &p, &parts, bounds, MAX_OBJECT_FACES, cast, membrane); - for ((item, opacity, _, _, scopes, member), f) in parts.iter().zip(made) { + let made = built_solids_cast(&fx.id, &p, &parts, bounds, MAX_OBJECT_FACES, cast, membrane, carrier); + for (k, ((item, opacity, _, _, scopes, member), f)) in parts.iter().zip(made).enumerate() { let item: &AppearanceItem = item; match f { Ok(Some((f, _))) if !crate::revolve::paint_copies_add(&mut paint_bytes, facet_copies(&f, paint_ref(item), colored), paint_ref(item)) => { @@ -1936,10 +2030,11 @@ fn surfaces_with( built.push(faces); } // A stroke's outline past the limits is left out; the fill's solid still draws. Built - // with the graphics' pieces, a stroke past the limits draws without the graphics. + // with the graphics' pieces, a stroke past the limits draws without the graphics, and + // the side's graphics on that outline are not drawn. Ok(None) => { built.push(None); - *dropped |= membrane; + *dropped |= membrane || carrier == Some(k); } // A loaded file or a shape edited past the limits (its own, or those of the object's // solids together) keeps drawing its source path instead of failing the frame; @@ -2025,7 +2120,9 @@ fn surfaces_with( let seals: Vec = solids.iter().map(|(.., f, _)| underlaid(f, colored)).collect(); let seal = |range: std::ops::Range| seals.get(range).is_some_and(|s| s.iter().any(|s| *s)); let membrane_graphics = if membrane && graphics_on { mapped_graphics(&p) } else { vec![] }; - // The paint copies of Inflate's graphics, apart from those of the surfaces, as on Revolve. + let side_graphics = carrier.map(|_| mapped_graphics(&p)).unwrap_or_default(); + // The paint copies of Inflate's graphics and of the side's, apart from those of the surfaces, + // as on Revolve. let mut graphic_copies = 0usize; let surfaces: Vec = solids .into_iter() @@ -2034,14 +2131,22 @@ fn surfaces_with( let depths: Vec = f.iter().map(|f| Placed::of(f, shape, paints)).collect(); let ends = f.iter().map(|f| f.end.filter(|_| !f.away)).collect(); let (paint, opacity, blend) = paint_of(item, member); - // The pieces of Inflate's front and back draw the parts of the graphics that fall on - // them; past the graphics' limits the solid draws without them. - let parts = if membrane_graphics.is_empty() || !f.iter().any(|f| f.surface.is_some()) { + // The pieces of Inflate's front and back, and the carrier's pieces of Extrude & Bevel's + // side, draw the parts of the graphics that fall on them; past the graphics' limits the + // solid draws without them. + let parts = if !f.iter().any(|f| f.surface.is_some()) { vec![] - } else { + } else if !membrane_graphics.is_empty() { let parts = membrane_parts(doc, n.id, &membrane_graphics, &f, &mut graphic_copies); *dropped |= parts.is_none(); parts.unwrap_or_default() + } else if !side_graphics.is_empty() { + let shade = |f: &Facet, c: vectorcraft_doc::color::Color| Paint::solid(crate::lighting::shade(c, f.illumination)); + let parts = graphics::surface_parts(doc, n.id, (&side_graphics, PlanarFace::Side), &f, &shade, &mut graphic_copies); + *dropped |= parts.is_none(); + parts.unwrap_or_default() + } else { + vec![] }; let drawn = parts.iter().any(|p| !p.is_empty()); let art = if classic { @@ -2363,8 +2468,18 @@ pub fn graphics_reshaped_after(n: &Node, item: Option, index: usize) -> b /// Finds a 3D effect in a list of effects, with its index there. type Pick<'p> = dyn for<'e> Fn(&'e [Effect]) -> Option<(usize, &'e Effect)> + 'p; -/// [`graphic_frame`] of the 3D effect `pick` finds in the effects of `n` or its `item`. -fn frame_of(doc: Option<&Document>, n: &Node, item: Option, pick: &Pick<'_>) -> Option { +/// The size of the side unrolled of the Extrude & Bevel at `index` of the effects of `n` (on the +/// object itself with `item` `None`, else on its fill or stroke `item`), that a new graphic on it +/// fits: on the side of its solid with the longest outline, as wide as the part about x = 0 that +/// does not reach the side's cut, and as tall as the length across its bevels and walls. `None` when that effect is not a visible Extrude & Bevel with a +/// depth, or its art can't be built. +pub fn graphic_side_size(doc: Option<&Document>, n: &Node, item: Option, index: usize) -> Option<(f64, f64)> { + let (fx, shapes) = frame_shapes(doc, n, item, &|fx: &[Effect]| fx.get(index).filter(|e| e.visible && e.id == EXTRUDE).map(|e| (index, e)))?; + side_size(&crate::merged_params(&fx.id, &fx.params), &shapes) +} + +/// The 3D effect `pick` finds in the effects of `n` or its `item`, and the shapes it builds from. +fn frame_shapes(doc: Option<&Document>, n: &Node, item: Option, pick: &Pick<'_>) -> Option<(Effect, Vec)> { let n = &*resolve(doc, n, "").ok()?; let (fx, shapes) = if is_container(n) { let (index, fx) = pick(&n.appearance.effects).filter(|_| item.is_none())?; @@ -2388,6 +2503,12 @@ fn frame_of(doc: Option<&Document>, n: &Node, item: Option, pick: &Pick<' } } }; + Some((fx.clone(), shapes)) +} + +/// [`graphic_frame`] of the 3D effect `pick` finds in the effects of `n` or its `item`. +fn frame_of(doc: Option<&Document>, n: &Node, item: Option, pick: &Pick<'_>) -> Option { + let (fx, shapes) = frame_shapes(doc, n, item, pick)?; if !takes_graphics(&fx.id) { return None; } @@ -2419,7 +2540,7 @@ fn frame_of(doc: Option<&Document>, n: &Node, item: Option, pick: &Pick<' // their handles. A stroke left out places none of its own. When a fill's solid can't be // built, or the solids together pass the limit, the art draws its source and no piece // places a handle. - let built: Vec = built_solids_cast(INFLATE, &p, &parts, bounds, MAX_OBJECT_FACES, false, true) + let built: Vec = built_solids_cast(INFLATE, &p, &parts, bounds, MAX_OBJECT_FACES, false, true, None) .collect::, String>>() .map(|solids| solids.into_iter().flatten().flat_map(|(f, _)| f).collect()) .unwrap_or_default(); @@ -2427,7 +2548,16 @@ fn frame_of(doc: Option<&Document>, n: &Node, item: Option, pick: &Pick<' } let options = extrude_options(&p); let map = |face| vectorcraft_three_d::extrude_face_map(bounds, options, view, face); - Some(graphics::GraphicFrame::new(bounds, map(PlanarFace::Front), map(PlanarFace::Back))) + let frame = graphics::GraphicFrame::new(bounds, map(PlanarFace::Front), map(PlanarFace::Back)); + // With graphics on the side, the part of it the viewer sees places their handles. + let side = side_carrier(&fx.id, &p, &parts, bounds) + .and_then(|k| parts.get(k)) + .and_then(|(_, _, area, rule, _, _)| side_facets(area, *rule, bounds, &p).ok()) + .map(|facets| graphics::SideFrame::of(&facets)); + Some(match side { + Some(side) => frame.with_side(side), + None => frame, + }) } /// The bounds of the art symbol `name` of `doc` draws as a graphic, in the symbol's coordinates. diff --git a/crates/effects/src/solids/graphics.rs b/crates/effects/src/solids/graphics.rs index ee256cf34f..687d534c2f 100644 --- a/crates/effects/src/solids/graphics.rs +++ b/crates/effects/src/solids/graphics.rs @@ -1,6 +1,6 @@ -//! Graphics mapped onto a 3D object's planar faces (Window › 3D and Materials › Materials › -//! Graphics): the art of a document symbol drawn on Extrude & Bevel's front or back cap, or on a -//! plane, turned, foreshortened and shaded with that face and clipped to it. +//! Graphics mapped onto a 3D object's faces (Window › 3D and Materials › Materials › +//! Graphics): the art of a document symbol drawn on Extrude & Bevel's front or back cap or on its +//! side, or on a plane, turned, foreshortened and shaded with that face and clipped to it. //! //! The effect keeps its graphics in its `graphics` parameter, each `{symbol, face, x, y, scale, //! rotation}`: the symbol's name, the face, the offset of the graphic's center from the center of @@ -12,7 +12,10 @@ //! On Revolve the graphics lie on the swept side surface, unrolled flat //! ([`vectorcraft_three_d::SurfaceCell`]): x and y are the offset of the graphic's center from the //! middle of that surface, x around the axis and y along the profile, and each face of the side -//! draws the part of the graphics that falls on it ([`surface_parts`]). +//! draws the part of the graphics that falls on it ([`surface_parts`]). Graphics on Extrude & +//! Bevel's side (face `side`) lie on its walls and bevels unrolled the same way, x along the +//! outline and y from the front toward the back, drawn on the pieces of the side of the solid with +//! the longest outline. //! //! On Inflate the graphics lie on the puffed front, and on the puffed back when Both Sides is on: //! each is placed in the art's plane as on Extrude & Bevel's caps and carried straight out onto @@ -117,7 +120,7 @@ impl MappedGraphic { }; let face = match m.get("face") { None => PlanarFace::Front, - Some(v) => v.as_str().and_then(PlanarFace::parse).ok_or_else(|| format!("`{GRAPHICS}` face must be front or back"))?, + Some(v) => v.as_str().and_then(PlanarFace::parse).ok_or_else(|| format!("`{GRAPHICS}` face must be front, back or side"))?, }; let number = |key: &str, default: f64, (lo, hi): (f64, f64)| -> Result { match m.get(key) { @@ -146,7 +149,7 @@ impl MappedGraphic { * Affine::scale(self.scale / 100.0) * Affine::translate(-art.center().to_vec2()); match self.face { - PlanarFace::Front => place, + PlanarFace::Front | PlanarFace::Side => place, // Seen from behind, the back's right is the front's left. PlanarFace::Back => { Affine::translate(center.to_vec2()) * Affine::scale_non_uniform(-1.0, 1.0) * Affine::translate(-center.to_vec2()) * place @@ -155,8 +158,8 @@ impl MappedGraphic { } } -/// The 3D effects that take graphics: Extrude & Bevel (its caps), Rotate (the plane), Revolve (its -/// swept side) and Inflate (its puffed front and back). +/// The 3D effects that take graphics: Extrude & Bevel (its caps and its side), Rotate (the plane), +/// Revolve (its swept side) and Inflate (its puffed front and back). pub fn takes_graphics(id: &str) -> bool { id == super::EXTRUDE || id == super::ROTATE || id == crate::REVOLVE || id == super::INFLATE } @@ -172,7 +175,7 @@ pub fn mapped_graphics(p: &Value) -> Vec { /// Are the graphics in parameters `p` of 3D effect `id` valid? Only Extrude & Bevel, Rotate, /// Revolve and Inflate take graphics; a plane has only a front, and Revolve's graphics go on its -/// side, named the front. +/// side, named the front. Only Extrude & Bevel takes graphics on its side. pub fn validate(id: &str, p: &Value) -> Result<(), String> { let list = match p.get(GRAPHICS) { None => return Ok(()), @@ -190,12 +193,15 @@ pub fn validate(id: &str, p: &Value) -> Result<(), String> { } for v in list { let g = MappedGraphic::from_value(v)?; - if id == super::ROTATE && g.face == PlanarFace::Back { + if id == super::ROTATE && g.face != PlanarFace::Front { return Err("A plane has one face: map its graphics onto the front".into()); } - if id == crate::REVOLVE && g.face == PlanarFace::Back { + if id == crate::REVOLVE && g.face != PlanarFace::Front { return Err("Revolve maps graphics onto its side: map them onto the front".into()); } + if id == super::INFLATE && g.face == PlanarFace::Side { + return Err("Inflate maps graphics onto its front and back, not onto a side".into()); + } } Ok(()) } @@ -605,11 +611,11 @@ struct Unrolled { place: Affine, } -/// The areas of `graphics` on `face` (the front, for Revolve's side; Inflate's front or back) -/// placed on the unrolled side surface, or in the art's plane about the center of the object's -/// bounds, cut into straight pieces. A graphic whose symbol `doc` does not have, or whose art is -/// past the limits of [`pieces_of`], is left out. `None` when the pieces take more than -/// [`MAX_ELEMENTS`] points together. +/// The areas of `graphics` on `face` (the front, for Revolve's side; Extrude & Bevel's side; +/// Inflate's front or back) placed on the unrolled side surface, or in the art's plane about the +/// center of the object's bounds, cut into straight pieces. A graphic whose symbol `doc` does not +/// have, or whose art is past the limits of [`pieces_of`], is left out. `None` when the pieces take +/// more than [`MAX_ELEMENTS`] points together. fn unrolled(doc: &Document, graphics: &[MappedGraphic], face: PlanarFace) -> Option> { let mut pieces = vec![]; let mut points = 0usize; @@ -690,9 +696,9 @@ fn straight_pieces(path: &BezPath, points: &mut usize) -> Option> (*points <= MAX_ELEMENTS).then_some(polygons) } -/// Do the graphics on `face` in parameters `p` (the front of Revolve; Inflate's front or back) fit -/// the limits with the symbols of `doc`? Their art, cut into straight pieces on the surface, may -/// take up to [`MAX_ELEMENTS`] points together. +/// Do the graphics on `face` in parameters `p` (the front of Revolve; Extrude & Bevel's side; +/// Inflate's front or back) fit the limits with the symbols of `doc`? Their art, cut into straight +/// pieces on the surface, may take up to [`MAX_ELEMENTS`] points together. pub(crate) fn validate_surface_symbols(doc: &Document, p: &Value, face: PlanarFace) -> Result<(), String> { let list = mapped_graphics(p); if !list.iter().any(|g| g.face == face) || unrolled(doc, &list, face).is_some() { @@ -702,7 +708,7 @@ pub(crate) fn validate_surface_symbols(doc: &Document, p: &Value, face: PlanarFa } /// A face of a surface that graphics are drawn on ([`surface_parts`]): a face of Revolve's swept -/// side, or a piece of Inflate's front or back. +/// side, a piece of Extrude & Bevel's walls and bevels, or a piece of Inflate's front or back. pub(crate) trait SurfaceFace { /// Where the face lies on the surface, when it carries graphics and shows the surface's outside /// to the viewer. @@ -734,6 +740,30 @@ impl SurfaceFace for vectorcraft_three_d::Face { } } +/// A piece of Extrude & Bevel's side ([`Facet::surface`]). +impl SurfaceFace for Facet { + fn outer_cell(&self) -> Option<&vectorcraft_three_d::SurfaceCell> { + self.surface.as_ref().filter(|c| c.outward) + } + fn curved(&self) -> Option> { + if let Some(outline) = &self.outline { + return Some(Cow::Borrowed(outline)); + } + // A piece of a stroke's face cut where it passes through a wall keeps its face's cell. + let cut = self.surface.as_ref().is_some_and(|c| self.contours.len() != 1 || self.contours.first() != Some(&c.page)); + cut.then(|| Cow::Owned(self.path())) + } + fn rgb_light(&self) -> Option { + self.rgb_gradient + } + fn light(&self) -> [f64; 3] { + self.illumination + } + fn outline_path(&self) -> PathData { + self.path() + } +} + /// A piece of Inflate's front or back ([`Facet::membrane`]) that carries graphics on `face` only. pub(crate) struct OnFace<'a> { pub(crate) facet: &'a Facet, @@ -764,11 +794,11 @@ impl SurfaceFace for OnFace<'_> { } } -/// The parts of the graphics on `face` of `graphics` (the front of Revolve; Inflate's front or -/// back) that fall on each of `faces`, a surface's faces in drawing order, for an object with id -/// `id`: for each face, the nodes to draw right after it. Only faces of the surface that show their -/// outside to the viewer carry a part, so a graphic narrows toward the silhouette, is hidden past -/// it and is covered by the nearer faces drawn after it. +/// The parts of the graphics on `face` of `graphics` (the front of Revolve; Extrude & Bevel's side; +/// Inflate's front or back) that fall on each of `faces`, a surface's faces in drawing order, for +/// an object with id `id`: for each face, the nodes to draw right after it. Only faces of the +/// surface that show their outside to the viewer carry a part, so a graphic narrows toward the +/// silhouette, is hidden past it and is covered by the nearer faces drawn after it. /// `shade` gives the paint of a solid color on a face, as the surface under it is shaded; the /// colors of gradients and patterns are multiplied by the face's light. A graphic whose symbol /// `doc` does not have, or that is past the limits of its art, draws nothing. `None` past @@ -1071,15 +1101,94 @@ pub(super) fn art_bounds(doc: &Document, name: &str) -> Option { /// Where a 3D object's graphics are drawn: the bounds its solids are built with (the graphics' /// offsets are from their center), the maps of its front and back faces, when it has them, and -/// for Inflate the pieces of its puffed faces the viewer sees. +/// the visible part of its side unrolled, when it has graphics there, and for Inflate the pieces of +/// its puffed faces the viewer sees. #[derive(Clone, Debug, PartialEq)] pub struct GraphicFrame { pub bounds: Rect, front: Option, back: Option, + side: Option, membrane: Option, } +/// Does triangle `t` hold point `q`, its edges included? +fn in_triangle(t: &[Point; 3], q: Point) -> bool { + let side = |a: Point, b: Point| (b - a).cross(q - a); + let s = [side(t[0], t[1]), side(t[1], t[2]), side(t[2], t[0])]; + s.iter().all(|v| *v >= -1e-9) || s.iter().all(|v| *v <= 1e-9) +} + +/// The pieces of Extrude & Bevel's side that show their outside to the viewer, as the graphics are +/// drawn on them ([`surface_parts`]): each piece's corners on the side unrolled and on the page, the +/// outline its parts are cut to when that is not the polygon of its corners, and its depth (larger +/// is nearer). +#[derive(Clone, Debug, Default, PartialEq)] +pub struct SideFrame { + pieces: Vec, +} + +#[derive(Clone, Debug, PartialEq)] +struct SidePiece { + uv: Vec, + page: Vec, + outline: Option, + depth: f64, +} + +impl SideFrame { + /// The pieces of `facets` that carry where they lie on the side unrolled and show its outside. + pub(super) fn of(facets: &[Facet]) -> Self { + let pieces = facets + .iter() + .filter_map(|f| { + let cell = f.outer_cell().filter(|c| c.uv.len() == c.page.len() && (3..=4).contains(&c.uv.len()))?; + let outline = f.curved().map(|o| o.to_bezpath()); + Some(SidePiece { uv: cell.uv.clone(), page: cell.page.clone(), outline, depth: f.depth }) + }) + .collect(); + Self { pieces } + } + + /// Point `p` of the side unrolled mapped onto the page, or with `from_page` a page point mapped + /// onto the side unrolled, through the nearest piece whose drawn part holds it: within the + /// triangle of its corners on the same side of its diagonal from corner 0 to corner 2, grown and + /// cut to its outline as [`surface_parts`] cuts the parts. `None` when no piece holds it. + fn map(&self, p: Point, from_page: bool) -> Option { + let mut best: Option<(Point, f64)> = None; + for piece in &self.pieces { + let (from, to) = if from_page { (&piece.page, &piece.uv) } else { (&piece.uv, &piece.page) }; + let triangles: &[[usize; 3]] = if from.len() == 3 { &[[0, 1, 2]] } else { &[[0, 1, 2], [0, 2, 3]] }; + for corners in triangles { + let pick = |of: &[Point]| Some([*of.get(corners[0])?, *of.get(corners[1])?, *of.get(corners[2])?]); + let (Some(a), Some(b)) = (pick(from), pick(to)) else { continue }; + let window = if piece.outline.is_some() { grown(a, 3.0) } else { a }; + if !in_triangle(&window, p) { + continue; + } + // A four-cornered piece's two triangles meet along its diagonal: each holds its side. + if triangles.len() == 2 + && let (Some(&d0), Some(&d2), Some(&own)) = (from.first(), from.get(2), from.get(if corners[1] == 1 { 1 } else { 3 })) + { + let across = |q: Point| (d2 - d0).cross(q - d0); + if across(p) * across(own) < 0.0 { + continue; + } + } + let Some(q) = triangle_map(&a, &b).map(|m| m * p).filter(|q| q.is_finite()) else { continue }; + let on_page = if from_page { p } else { q }; + if piece.outline.as_ref().is_some_and(|o| !o.contains(on_page)) { + continue; + } + if best.is_none_or(|(_, depth)| piece.depth > depth) { + best = Some((q, piece.depth)); + } + } + } + best.map(|(q, _)| q) + } +} + /// The pieces of Inflate's front and puffed back that show their outside to the viewer, as the /// graphics are drawn on them ([`surface_parts`]): each piece's face, its corners in the art's plane /// (offsets from the center of the object's bounds) and on the page, its depth (larger is nearer) @@ -1165,11 +1274,7 @@ impl MembraneFrame { /// that point of the page. `None` when no piece the viewer sees holds it, or when another nearer /// piece, of either face, or a nearer cover hides that point of the page. fn map(&self, face: PlanarFace, p: Point, from_page: bool) -> Option { - let inside = |t: &[Point; 3], q: Point| { - let side = |a: Point, b: Point| (b - a).cross(q - a); - let s = [side(t[0], t[1]), side(t[1], t[2]), side(t[2], t[0])]; - s.iter().all(|v| *v >= -1e-9) || s.iter().all(|v| *v <= 1e-9) - }; + let inside = in_triangle; let mut best: Option<(Point, f64, &MembranePiece)> = None; for piece in self.pieces.iter().filter(|piece| piece.face == face) { let (from, to) = if from_page { (&piece.page, &piece.uv) } else { (&piece.uv, &piece.page) }; @@ -1213,19 +1318,25 @@ impl MembraneFrame { impl GraphicFrame { pub(super) fn new(bounds: Rect, front: Option, back: Option) -> Self { - Self { bounds, front, back, membrane: None } + Self { bounds, front, back, side: None, membrane: None } + } + + /// The frame with the visible part of the side `side`, for its graphics' handles. + pub(super) fn with_side(self, side: SideFrame) -> Self { + Self { side: Some(side), ..self } } /// The frame of an Inflate object built about `bounds`, whose graphics are drawn on the pieces /// of `membrane`. pub(super) fn inflated(bounds: Rect, membrane: MembraneFrame) -> Self { - Self { bounds, front: None, back: None, membrane: Some(membrane) } + Self { bounds, front: None, back: None, side: None, membrane: Some(membrane) } } pub fn map(&self, face: PlanarFace) -> Option<&FaceMap> { match face { PlanarFace::Front => self.front.as_ref(), PlanarFace::Back => self.back.as_ref(), + PlanarFace::Side => None, } } @@ -1236,41 +1347,41 @@ impl GraphicFrame { match face { PlanarFace::Front => Point::new(c.x + x, c.y + y), PlanarFace::Back => Point::new(c.x - x, c.y + y), + PlanarFace::Side => Point::new(x, y), } } /// Where graphic `g`'s center lands on the page, and whether its face is turned toward the - /// viewer. `None` when the object has no such face or the point has no page point. On Inflate - /// the center lands on the puffed face above it, and is `None` where the viewer does not see - /// that face. + /// viewer. `None` when the object has no such face or the point has no page point. A graphic on + /// the side lands where its center is on the part of the side the viewer sees, and is `None` + /// elsewhere. On Inflate the center lands on the puffed face above it, and is `None` where the + /// viewer does not see that face. pub fn handle(&self, g: &MappedGraphic) -> Option<(Point, bool)> { + if g.face == PlanarFace::Side { + return Some((self.side.as_ref()?.map(Point::new(g.x, g.y), false)?, true)); + } if let Some(membrane) = &self.membrane { - let uv = match g.face { - PlanarFace::Front => Point::new(g.x, g.y), - PlanarFace::Back => Point::new(-g.x, g.y), - }; + let uv = if g.face == PlanarFace::Back { Point::new(-g.x, g.y) } else { Point::new(g.x, g.y) }; return Some((membrane.map(g.face, uv, false)?, true)); } let map = self.map(g.face)?; Some((map.to_page(self.art_point(g.face, (g.x, g.y)))?, map.visible)) } - /// The offset of a graphic on `face` whose center lands on page point `page`. On Inflate, only - /// a point on the part of the puffed face the viewer sees has one. + /// The offset of a graphic on `face` whose center lands on page point `page`. On the side, only + /// a point on the part of the side the viewer sees has one, and on Inflate only a point on the + /// part of the puffed face the viewer sees. pub fn offset_at(&self, face: PlanarFace, page: Point) -> Option<(f64, f64)> { - let (x, y) = if let Some(membrane) = &self.membrane { + let (x, y) = if face == PlanarFace::Side { + let art = self.side.as_ref()?.map(page, true)?; + (art.x, art.y) + } else if let Some(membrane) = &self.membrane { let uv = membrane.map(face, page, true)?; - match face { - PlanarFace::Front => (uv.x, uv.y), - PlanarFace::Back => (-uv.x, uv.y), - } + if face == PlanarFace::Back { (-uv.x, uv.y) } else { (uv.x, uv.y) } } else { let art = self.map(face)?.to_art(page)?; let c = self.bounds.center(); - match face { - PlanarFace::Front => (art.x - c.x, art.y - c.y), - PlanarFace::Back => (c.x - art.x, art.y - c.y), - } + if face == PlanarFace::Back { (c.x - art.x, art.y - c.y) } else { (art.x - c.x, art.y - c.y) } }; (x.abs() <= MAX_OFFSET && y.abs() <= MAX_OFFSET).then_some((x, y)) } @@ -1278,11 +1389,17 @@ impl GraphicFrame { /// The scale (percent) at which art with bounds `art` fits inside the object's bounds, at most /// 100: where a newly mapped graphic starts. pub fn fitting_scale(&self, art: Rect) -> f64 { - let fit = (self.bounds.width() / art.width().max(1e-9)).min(self.bounds.height() / art.height().max(1e-9)); - (fit * 100.0).clamp(SCALE_RANGE.0, 100.0) + fitting(self.bounds.width(), self.bounds.height(), art) } } +/// The scale (percent) at which art with bounds `art` fits inside a `width` × `height` area, at +/// most 100. +pub fn fitting(width: f64, height: f64, art: Rect) -> f64 { + let fit = (width / art.width().max(1e-9)).min(height / art.height().max(1e-9)); + (fit * 100.0).clamp(SCALE_RANGE.0, 100.0) +} + /// The symbols the graphics of `n`'s 3D effects name (its own effects and its fills' and strokes'). pub fn graphic_symbols(n: &Node) -> Vec { appearance_graphic_symbols(&n.appearance) @@ -1366,3 +1483,7 @@ pub fn with_graphic(p: &Value, g: &MappedGraphic) -> Value { #[cfg(test)] #[path = "tests_graphics.rs"] mod tests; + +#[cfg(test)] +#[path = "tests_graphics_side.rs"] +mod tests_side; diff --git a/crates/effects/src/solids/tests_graphics.rs b/crates/effects/src/solids/tests_graphics.rs index 5d98a19ff8..c03b8800cb 100644 --- a/crates/effects/src/solids/tests_graphics.rs +++ b/crates/effects/src/solids/tests_graphics.rs @@ -556,12 +556,13 @@ fn graphics_are_checked() { let n = object(EXTRUDE, json!({})); let check = |id: &str, graphics: Value| validate_three_d_in(None, &n, id, &json!({"graphics": graphics})); assert!(check(EXTRUDE, json!([{"symbol": "Mark", "face": "back", "x": 3.0, "scale": 50.0, "rotation": -90.0}])).is_ok()); + assert!(check(EXTRUDE, json!([{"symbol": "Mark", "face": "side", "x": -40.0, "y": 5.0}])).is_ok()); assert!(check(EXTRUDE, json!([])).is_ok()); for bad in [ json!("Mark"), json!([{"face": "front"}]), json!([{"symbol": ""}]), - json!([{"symbol": "Mark", "face": "side"}]), + json!([{"symbol": "Mark", "face": "top"}]), json!([{"symbol": "Mark", "scale": 0.0}]), json!([{"symbol": "Mark", "rotation": 400.0}]), json!([{"symbol": "Mark", "x": "1"}]), @@ -571,11 +572,14 @@ fn graphics_are_checked() { assert!(check(EXTRUDE, bad.clone()).is_err(), "{bad}"); } assert!(check(ROTATE, json!([{"symbol": "Mark", "face": "back"}])).is_err()); - // Inflate takes graphics on its front and its puffed back. + assert!(check(ROTATE, json!([{"symbol": "Mark", "face": "side"}])).is_err()); + // Inflate takes graphics on its front and its puffed back, and none on a side. assert!(check(INFLATE, json!([{"symbol": "Mark"}, {"symbol": "Mark", "face": "back"}])).is_ok()); + assert!(check(INFLATE, json!([{"symbol": "Mark", "face": "side"}])).is_err()); // Revolve takes graphics on its side, named the front; Revolve (Classic) takes none. assert!(validate_three_d_params(crate::REVOLVE, &json!({"graphics": [{"symbol": "Mark"}]})).is_ok()); assert!(validate_three_d_params(crate::REVOLVE, &json!({"graphics": [{"symbol": "Mark", "face": "back"}]})).is_err()); + assert!(validate_three_d_params(crate::REVOLVE, &json!({"graphics": [{"symbol": "Mark", "face": "side"}]})).is_err()); assert!(validate_three_d_params(crate::CLASSIC_REVOLVE, &json!({"graphics": [{"symbol": "Mark"}]})).is_err()); // A loaded file's invalid entries are left out when drawn. assert_eq!(mapped_graphics(&json!({"graphics": [{"symbol": "Mark"}, {"face": "back"}, 3]})).len(), 1); @@ -595,10 +599,17 @@ fn the_frame_at_an_index_is_that_effects() { #[test] fn a_change_to_a_plane_drops_the_back_caps_graphics() { - let p = json!({"graphics": [{"symbol": "Mark", "face": "front"}, {"symbol": "Mark", "face": "back"}]}); + let p = json!({"graphics": [{"symbol": "Mark", "face": "front"}, {"symbol": "Mark", "face": "back"}, {"symbol": "Mark", "face": "side"}]}); let plane = three_d_params_as(EXTRUDE, &p, ROTATE); assert_eq!(plane["graphics"], json!([{"symbol": "Mark", "face": "front"}])); assert!(validate_three_d_params(ROTATE, &plane).is_ok()); + // Revolve drops the side's graphics too; Extrude & Bevel keeps every face's. + assert_eq!(three_d_params_as(EXTRUDE, &p, crate::REVOLVE)["graphics"], json!([{"symbol": "Mark", "face": "front"}])); + assert_eq!(three_d_params_as(EXTRUDE, &p, EXTRUDE)["graphics"], p["graphics"]); + // Inflate keeps the front's and the back's graphics and drops the side's. + let inflated = three_d_params_as(EXTRUDE, &p, INFLATE); + assert_eq!(inflated["graphics"], json!([{"symbol": "Mark", "face": "front"}, {"symbol": "Mark", "face": "back"}])); + assert!(validate_three_d_params(INFLATE, &inflated).is_ok()); // Back to Extrude & Bevel, the front's graphic stays. assert_eq!(three_d_params_as(ROTATE, &plane, EXTRUDE)["graphics"], plane["graphics"]); } diff --git a/crates/effects/src/solids/tests_graphics_side.rs b/crates/effects/src/solids/tests_graphics_side.rs new file mode 100644 index 0000000000..e5390d3a47 --- /dev/null +++ b/crates/effects/src/solids/tests_graphics_side.rs @@ -0,0 +1,256 @@ +//! Graphics on Extrude & Bevel's side: its walls and bevels unrolled flat. + +use serde_json::json; +use vectorcraft_doc::color::Color; +use vectorcraft_doc::{StrokeLayer, Symbol}; +use vectorcraft_geom::shapes; + +use super::super::{EXTRUDE, graphic_frame, graphic_side_size, solid_art_in, validate_three_d_in}; +use super::*; + +fn red() -> Color { + Color::rgb(1.0, 0.0, 0.0) +} + +fn square(id: u64, r: Rect, paint: Paint) -> Node { + Node::path(NodeId(id), shapes::rectangle(r), Appearance::basic(paint, Paint::None, 0.0)) +} + +/// A document with symbol "Mark": a red 10 × 10 square. +fn document() -> Document { + let mut d = Document::new(1000.0, 1000.0); + d.symbols.push(Symbol { + dynamic: false, + name: "Mark".into(), + art: Arc::new(square(0, Rect::new(500.0, 500.0, 510.0, 510.0), Paint::solid(red()))), + }); + d +} + +/// A gray 100 × 100 square at (0, 0), extruded 50 pt, seen from above (its top wall faces the +/// viewer, its front edge at the bottom of the page), with `params` over that. +fn object(params: Value) -> Node { + let mut p = json!({"rotationX": -90.0, "rotationY": 0.0, "rotationZ": 0.0, "shade": false}); + if let (Some(p), Some(extra)) = (p.as_object_mut(), params.as_object()) { + p.extend(extra.clone()); + } + let mut n = square(7, Rect::new(0.0, 0.0, 100.0, 100.0), Paint::solid(Color::rgb(0.5, 0.5, 0.5))); + n.appearance.effects.push(crate::new_effect(EXTRUDE, &p).unwrap()); + n +} + +fn is_red(p: &Paint) -> bool { + p.color().is_some_and(|c| c.to_rgb()[0] > 0.3 && c.to_rgb()[1] < 0.1) +} + +/// The groups of a face and the parts of the side's graphics drawn on it, each part's outline. +fn faces_with_parts(art: &Node) -> Vec> { + let mut out = vec![]; + art.walk(&mut |n| { + if let NodeKind::Group { children, clip: false } = &n.kind + && let Some((face, parts)) = children.split_first() + && matches!(face.kind, NodeKind::Path { .. }) + && !parts.is_empty() + { + let red: Vec = parts + .iter() + .filter(|p| p.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Fill(f) if is_red(&f.paint)))) + .filter_map(|p| p.path_data().cloned()) + .collect(); + if red.len() == parts.len() { + out.push(red); + } + } + }); + out +} + +fn bounds(parts: &[Vec]) -> Rect { + parts.iter().flatten().filter_map(PathData::bounds).reduce(|a, b| a.union(b)).unwrap() +} + +fn near(a: Rect, b: Rect) -> bool { + [(a.x0, b.x0), (a.y0, b.y0), (a.x1, b.x1), (a.y1, b.y1)].iter().all(|(p, q)| (p - q).abs() < 1e-6) +} + +/// x runs along the outline from the top's middle, clockwise as the front is seen, and y from the +/// middle of the side toward the back. +#[test] +fn a_side_graphic_lies_on_the_wall_at_its_offset() { + let d = document(); + let n = object(json!({"graphics": [{"symbol": "Mark", "face": "side"}]})); + let art = solid_art_in(Some(&d), &n).unwrap(); + let found = faces_with_parts(&art); + assert_eq!(found.len(), 1, "drawn once, on the top wall"); + // Seen from above, the top wall runs from its front edge (page y 75) to its back (page y 25). + assert!(near(bounds(&found), Rect::new(45.0, 45.0, 55.0, 55.0)), "{:?}", bounds(&found)); + let moved = object(json!({"graphics": [{"symbol": "Mark", "face": "side", "x": 20.0, "y": 10.0, "scale": 200.0}]})); + let found = faces_with_parts(&solid_art_in(Some(&d), &moved).unwrap()); + assert!(near(bounds(&found), Rect::new(60.0, 30.0, 80.0, 50.0)), "{:?}", bounds(&found)); + // Without the document nothing is drawn; a graphic on the side leaves the caps without one. + assert!(faces_with_parts(&solid_art_in(None, &n).unwrap()).is_empty()); +} + +/// A graphic that reaches past a corner runs on around it onto the next wall. +#[test] +fn a_side_graphic_runs_around_a_corner() { + let d = document(); + // x = 50 is the top's right end. + let from_above = object(json!({"graphics": [{"symbol": "Mark", "face": "side", "x": 50.0}]})); + let found = faces_with_parts(&solid_art_in(Some(&d), &from_above).unwrap()); + assert!(near(bounds(&found), Rect::new(95.0, 45.0, 100.0, 55.0)), "only the top's part shows: {:?}", bounds(&found)); + // Turned to show the top and the right, both walls draw their part. + let turned = object(json!({"rotationX": -30.0, "rotationY": -40.0, "graphics": [{"symbol": "Mark", "face": "side", "x": 50.0}]})); + assert_eq!(faces_with_parts(&solid_art_in(Some(&d), &turned).unwrap()).len(), 2); + // Twist and taper carry the graphic; it stays on the side. + let twisted = + object(json!({"rotationX": -30.0, "rotationY": -40.0, "twist": 60.0, "taper": 50.0, "graphics": [{"symbol": "Mark", "face": "side"}]})); + let found = faces_with_parts(&solid_art_in(Some(&d), &twisted).unwrap()); + assert!(!found.is_empty() && found.iter().flatten().all(|p| p.bounds().is_some_and(|b| [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite())))); +} + +/// The handle lands where the graphic's center is on the visible side, and a page point there +/// gives back its offset; a graphic on a hidden wall has no handle. +#[test] +fn the_sides_handle_moves_the_graphic_on_its_visible_part() { + let d = document(); + let g = MappedGraphic::from_value(&json!({"symbol": "Mark", "face": "side", "x": 10.0, "y": -5.0})).unwrap(); + let n = object(json!({"graphics": [g.to_value()]})); + let frame = graphic_frame(Some(&d), &n, None).unwrap(); + let (at, visible) = frame.handle(&g).unwrap(); + assert!(visible && at.distance(Point::new(60.0, 55.0)) < 1e-6, "{at:?}"); + let (x, y) = frame.offset_at(PlanarFace::Side, Point::new(40.0, 45.0)).unwrap(); + assert!((x + 10.0).abs() < 1e-6 && (y - 5.0).abs() < 1e-6, "{x} {y}"); + // The bottom's middle, half way around, is hidden from above; so is a page point off the top. + let hidden = MappedGraphic { x: 200.0, ..g.clone() }; + assert!(frame.handle(&hidden).is_none()); + assert!(frame.offset_at(PlanarFace::Side, Point::new(50.0, 90.0)).is_none()); + // Without a graphic on the side, the frame places no handle there. + let caps = graphic_frame(Some(&d), &object(json!({"graphics": [{"symbol": "Mark"}]})), None).unwrap(); + assert!(caps.handle(&g).is_none()); +} + +/// On a curved wall, whose pieces are cut to its curved outline, the handle sits on the graphic's +/// center and a page point there gives back its offset. +#[test] +fn the_handle_follows_a_curved_side() { + let d = document(); + let g = MappedGraphic::from_value(&json!({"symbol": "Mark", "face": "side", "x": 6.0, "y": 3.0})).unwrap(); + let mut n = object(json!({"rotationX": -60.0, "graphics": [g.to_value()]})); + if let NodeKind::Path { path, .. } = &mut n.kind { + *path = shapes::ellipse(Rect::new(0.0, 0.0, 100.0, 100.0)); + } + let frame = graphic_frame(Some(&d), &n, None).unwrap(); + let (at, visible) = frame.handle(&g).unwrap(); + assert!(visible); + let (x, y) = frame.offset_at(PlanarFace::Side, at).unwrap(); + assert!((x - 6.0).abs() < 1e-6 && (y - 3.0).abs() < 1e-6, "{x} {y}"); +} + +/// A hollow object has no caps but takes graphics on its side; a stroke's solid, whose outline is +/// the longest, takes them once. +#[test] +fn a_hollow_or_stroked_object_takes_a_side_graphic() { + let d = document(); + let hollow = object(json!({"cap": false, "graphics": [{"symbol": "Mark", "face": "side"}, {"symbol": "Mark"}]})); + let art = solid_art_in(Some(&d), &hollow).unwrap(); + assert!(near(bounds(&faces_with_parts(&art)), Rect::new(45.0, 45.0, 55.0, 55.0))); + let mut stroked = object(json!({"graphics": [{"symbol": "Mark", "face": "side"}]})); + stroked.appearance.items.push(AppearanceItem::Stroke(StrokeLayer::new(Paint::solid(Color::rgb(0.2, 0.2, 0.2)), 10.0))); + let found = faces_with_parts(&solid_art_in(Some(&d), &stroked).unwrap()); + assert_eq!(found.len(), 1, "on the stroke's outer wall only"); + assert!(near(bounds(&found), Rect::new(45.0, 45.0, 55.0, 55.0)), "{:?}", bounds(&found)); + // The stroke's outer outline is 440 pt long, cut at a bottom corner 165 pt each way from the + // top's middle: a new graphic fits the 330 pt about x = 0 and the depth. + assert_eq!(graphic_side_size(Some(&d), &stroked, None, 0), Some((330.0, 50.0))); +} + +/// A stroke's face cut where it passes through a wall keeps the whole face's place on the side, and +/// each piece draws only the part of the graphic within its own outline. +#[test] +fn a_piece_cut_from_a_face_draws_its_own_part() { + let d = document(); + let facet = |x: f64, normal: [f64; 3], offset: f64| { + let square = vec![Point::new(x, 0.0), Point::new(x + 10.0, 0.0), Point::new(x + 10.0, 10.0), Point::new(x, 10.0)]; + let uv = square.iter().map(|p| Point::new(p.x - x, p.y)).collect(); + Facet { + contours: vec![square.clone()], + depth: 0.0, + brightness: 1.0, + illumination: [1.0; 3], + normal, + rgb_gradient: None, + outline: None, + side: true, + away: false, + end: None, + surface: Some(vectorcraft_three_d::SurfaceCell { page: square, uv, outward: true }), + membrane: None, + plane: Some(vectorcraft_three_d::DepthPlane { normal, offset, center: Point::ZERO, eye: None }), + } + }; + let wall = facet(0.0, [0.0, 0.0, 1.0], 0.0); + // z = x - 8: behind the wall left of x = 8, in front of it right of it. + let r = std::f64::consts::FRAC_1_SQRT_2; + let mut stroke = vec![facet(5.0, [-r, 0.0, r], -8.0 * r)]; + super::super::cut_through(std::slice::from_ref(&wall), &mut stroke, &mut 10, &mut 0); + assert_eq!(stroke.len(), 2, "cut where it passes through the wall"); + // The graphic covers the whole face, x 5 to 15 on the page. + let graphics = mapped_graphics(&json!({"graphics": [{"symbol": "Mark", "face": "side", "x": 5.0, "y": 5.0}]})); + let shade = |_: &Facet, c: Color| Paint::solid(c); + let parts = surface_parts(Some(&d), NodeId(0), (&graphics, PlanarFace::Side), &stroke, &shade, &mut 0).unwrap(); + let drawn: Vec = + parts.iter().map(|on| on.iter().filter_map(|n| n.path_data().and_then(PathData::bounds)).reduce(|a, b| a.union(b)).unwrap()).collect(); + // Each piece draws its own side of x = 8 (where the wall cuts it), together the whole graphic. + let (left, right) = (drawn[0].x0.min(drawn[1].x0), drawn[0].x1.max(drawn[1].x1)); + assert!((left - 5.0).abs() < 1e-6 && (right - 15.0).abs() < 1e-6, "{drawn:?}"); + assert!(drawn.iter().all(|b| (b.x0 - 8.0).abs() < 1e-6 || (b.x1 - 8.0).abs() < 1e-6), "{drawn:?}"); +} + +/// Commands refuse a side graphic whose curves, cut into straight pieces on the side, pass the +/// limit of points, though its own path elements are few; on a cap it is accepted. +#[test] +fn a_side_graphic_past_its_limits_is_refused() { + let mut d = document(); + // 200 circles 200,000 pt across: a few elements each, hundreds of thousands of points cut. + let mut subpaths = vec![]; + for k in 0..200 { + let x = f64::from(k); + subpaths.extend(shapes::ellipse(Rect::new(x, 0.0, x + 2e5, 2e5)).subpaths); + } + let rings = Node::path(NodeId(0), PathData::new(subpaths), Appearance::basic(Paint::solid(red()), Paint::None, 0.0)); + d.symbols.push(Symbol { dynamic: false, name: "Rings".into(), art: Arc::new(rings) }); + let n = object(json!({})); + let side = json!({"rotationX": -90.0, "graphics": [{"symbol": "Rings", "face": "side"}]}); + assert!(validate_three_d_in(Some(&d), &n, EXTRUDE, &side).is_err()); + assert!(validate_three_d_in(Some(&d), &n, EXTRUDE, &json!({"rotationX": -90.0, "graphics": [{"symbol": "Rings"}]})).is_ok()); + assert!(validate_three_d_in(Some(&d), &n, EXTRUDE, &json!({"graphics": [{"symbol": "Mark", "face": "side"}]})).is_ok()); +} + +/// With the shadow on, the solid that carries the side's graphics is built once, for both its faces +/// and its shadow: the graphic keeps its place on the wall, and the shadow is the one the object +/// casts without a graphic. +#[test] +fn a_side_graphic_keeps_its_place_with_the_shadow_on() { + let d = document(); + let shadow = |art: &Node| { + let first = &art.children().unwrap()[0]; + let [AppearanceItem::Fill(fill)] = first.appearance.items.as_slice() else { panic!("no shadow first: {first:?}") }; + assert!(fill.paint.color() == Some(Color::BLACK) && (fill.opacity - 0.5).abs() < 1e-6, "{fill:?}"); + first.path_data().and_then(PathData::bounds).unwrap() + }; + let lit = json!({"shade": true, "lightHeight": 90.0, "shadow": true, "shadowDistance": 50.0}); + let mut with_graphic = lit.clone(); + with_graphic["graphics"] = json!([{"symbol": "Mark", "face": "side"}]); + let n = object(with_graphic); + super::super::SOLID_GEOMETRY_BUILT.with(|b| b.set(0)); + super::super::SOLIDS_BUILT.with(|b| b.set(0)); + let art = solid_art_in(Some(&d), &n).unwrap(); + let builds = (super::super::SOLID_GEOMETRY_BUILT.with(std::cell::Cell::get), super::super::SOLIDS_BUILT.with(std::cell::Cell::get)); + assert_eq!(builds, (1, 1), "one build for the faces and the shadow"); + let found = faces_with_parts(&art); + assert_eq!(found.len(), 1, "drawn once, on the top wall"); + assert!(near(bounds(&found), Rect::new(45.0, 45.0, 55.0, 55.0)), "{:?}", bounds(&found)); + let without = solid_art_in(Some(&d), &object(lit)).unwrap(); + assert!(near(shadow(&art), shadow(&without)), "{:?} {:?}", shadow(&art), shadow(&without)); +} diff --git a/crates/effects/src/solids/tests_shadow.rs b/crates/effects/src/solids/tests_shadow.rs index 9652ec8f9a..12ab29423f 100644 --- a/crates/effects/src/solids/tests_shadow.rs +++ b/crates/effects/src/solids/tests_shadow.rs @@ -379,7 +379,7 @@ fn a_stroke_left_out_of_the_art_casts_no_shadow() { let p = crate::merged_params(id, &json!({"shadow": true})); let (parts, bounds) = solid_parts(&shapes, union_bounds(&shapes).unwrap()); let mut built: Vec> = - built_solids_cast(id, &p, &parts, bounds, MAX_OBJECT_FACES, true, false).map(|r| r.unwrap().and_then(|(_, faces)| faces)).collect(); + built_solids_cast(id, &p, &parts, bounds, MAX_OBJECT_FACES, true, false, None).map(|r| r.unwrap().and_then(|(_, faces)| faces)).collect(); let stroke = parts.iter().position(|(item, ..)| matches!(item, AppearanceItem::Stroke(_))).unwrap(); assert!(built.len() == 2 && built.iter().all(Option::is_some), "{id}"); let (both, _, cast) = cast_built(id, &p, &shapes, built.clone()).unwrap().unwrap(); diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 5a07a1d52b..cd29ab4154 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -407,7 +407,18 @@ pub fn command_specs() -> &'static [CommandSpec] { /// The command `id`: a built-in one, or a command an installed plug-in adds /// ([`plugin::command_specs`]). pub fn find_command(id: &str) -> Option<&'static CommandSpec> { - command_specs().iter().find(|c| c.id == id).or_else(|| plugin::find_spec(id)) + static INDEX: std::sync::OnceLock> = std::sync::OnceLock::new(); + INDEX.get_or_init(|| index_by_id(command_specs())).get(id).copied().or_else(|| plugin::find_spec(id)) +} + +/// `specs` by id. An id that more than one spec has names the first of them, as a search of +/// `specs` in order finds. +pub(crate) fn index_by_id(specs: &[CommandSpec]) -> std::collections::HashMap<&'static str, &CommandSpec> { + let mut index = std::collections::HashMap::with_capacity(specs.len()); + for spec in specs { + index.entry(spec.id).or_insert(spec); + } + index } /// Runs command `spec`'s implementation with `p`. A plug-in command's runs the plug-in @@ -829,6 +840,8 @@ pub use docmenu::guide_indexes; pub(crate) use edit::{Unrecorded, settle_interaction, typing_in_progress}; pub(crate) use object::bounds_rewrite; pub(crate) use object::{keep_aligned_in, refresh_pixel_aligned}; +/// The rules `object.scale`, `object.reflect` and `object.shear` check their params with. +pub use object::{reflect_axis, scale_factors, shear_tangent}; pub use plugin_call::{Location, ParamsPlace, key_location, location_in, location_keys}; pub use select::SIMILAR; pub(crate) use vectorcraft_doc::range::parse_range; diff --git a/crates/engine/src/cmd/addons/pathtools.rs b/crates/engine/src/cmd/addons/pathtools.rs index 1c730e02b4..2d1ded312f 100644 --- a/crates/engine/src/cmd/addons/pathtools.rs +++ b/crates/engine/src/cmd/addons/pathtools.rs @@ -3,11 +3,13 @@ //! anchor edits, Split / Add Points at Crossings, Slide Anchor Along Path, the Corner Tool's corners //! ([`corners`]), the Parametric Shape Tool's shapes ([`shape`]), the Shared Edge Merge Tool's //! merges with Keep Shared Points Together ([`shared_edge`]), Divide into Dashes, Expand Dashes -//! into Paths, Trim at Crossings ([`trim`]), Common Tangents ([`tangents`]) and Tangent Circle +//! into Paths, Trim at Crossings ([`trim`]), Smooth Bridge ([`bridge`]), Common Tangents +//! ([`tangents`]) and Tangent Circle //! ([`tangent_circle`]). //! Its tools, panels and submenu (Object › Plug-ins › Path Precision Tools) are the tools crate's //! and the UI's. +mod bridge; mod corners; #[cfg(test)] mod effect_tests; @@ -183,6 +185,7 @@ pub fn specs() -> Vec { v.extend(corners::specs()); v.extend(shared_edge::specs()); v.extend(trim::specs()); + v.extend(bridge::specs()); v.extend(tangent_circle::specs()); v.extend(tangents::specs()); v diff --git a/crates/engine/src/cmd/addons/pathtools/bridge.rs b/crates/engine/src/cmd/addons/pathtools/bridge.rs new file mode 100644 index 0000000000..2120b040e7 --- /dev/null +++ b/crates/engine/src/cmd/addons/pathtools/bridge.rs @@ -0,0 +1,95 @@ +//! Smooth Bridge: two selected circles joined into one outline by two concave arcs that touch both +//! circles, replacing the circles or added above them. + +use serde_json::{Value, json}; +use vectorcraft_doc::{NodeId, NodeKind}; +use vectorcraft_geom::PathData; +use vectorcraft_pathops::addons::pathtools as pt; + +use super::super::super::pathops::{Beside, remove_each}; +use super::super::super::{CommandSpec, bad, checked_ids_or_selection, cmd, has_selection, switch_or}; +use super::given; +use crate::{EngineError, Result, Session}; + +#[cfg(test)] +mod tests; + +/// The command, and its undo step's name. +const C: &str = "addon.pathtools.bridge"; +const LABEL: &str = "Smooth Bridge"; +/// The arcs' radius as a percentage of the smaller circle's radius: by default, and the range. +const RADIUS: f64 = 100.0; +const RADII: (f64, f64) = (1.0, 1000.0); + +pub(super) fn specs() -> Vec { + vec![cmd!( + "addon.pathtools.bridge", + "Smooth Bridge", + ["Object", "Plug-ins", "Path Precision Tools"], + None, + "{radius?: % 1..1000 (100; the radius of the bridge's two arcs as a percentage of the smaller circle's radius: larger makes a wider, gentler bridge), keepOriginals?: bool (false: the outline replaces the two circles, painted as the upper one; true: it goes directly above the upper one and the circles stay), ids?: [id, id] (default: the selection)} join two circles (paths whose outline is a circle, not hidden or locked) into one closed outline: around each circle on its side away from the other, and along two concave arcs, one on each side, that touch both circles so the outline runs on smoothly into them. Overlapping and touching circles are joined too; one circle inside the other, or circles too far apart for the radius (the arcs would not reach both, or would cross), is an error, which suggests a larger radius when one up to 1000% would bridge them. One undo step; the outline is selected → {id}", + has_selection, + bridge + )] +} + +fn bridge(s: &mut Session, p: &Value) -> Result { + let percent = given(p, "radius", Some(RADII), C)?.unwrap_or(RADIUS); + let keep = switch_or(p, "keepOriginals", false, C)?; + let roots = checked_ids_or_selection(s, p, C)?; + let circles: Vec<(NodeId, pt::Circle)> = { + let d = &s.doc()?.doc; + let editable = d.editable(); + d.paint_order(roots.iter().copied()) + .into_iter() + .filter_map(|id| match &d.node(id)?.kind { + NodeKind::Path { path, guide: false, clipping: false, .. } if editable(id) => Some((id, pt::circle_of(path)?)), + _ => None, + }) + .collect() + }; + let ([(below, a), (above, b)], 2) = (circles.as_slice(), roots.len()) else { + return Err(bad(C, "select two circles to bridge")); + }; + let (below, above) = (*below, *above); + let at = |percent: f64| pt::smooth_bridge(*a, *b, a.radius.min(b.radius) * percent / 100.0); + let outline = match at(percent) { + Ok(sp) => PathData::single(sp), + Err(pt::BridgeError::Inside) => return Err(bad(C, "one circle is inside the other")), + // A larger radius bridges circles a smaller one cannot, so only suggest one that is allowed. + Err(pt::BridgeError::TooFar) if at(RADII.1).is_ok() => { + return Err(bad(C, "the circles are too far apart for this radius: raise the radius")); + } + Err(pt::BridgeError::TooFar) => return Err(bad(C, "the circles are too far apart for this radius")), + Err(pt::BridgeError::Bad) => return Err(bad(C, "select two circles to bridge")), + }; + let id = s.edit(LABEL, |d, sel| { + let id = if keep { + // A copy of the upper circle (its appearance) with the outline as its path, right above + // it; the circles stay as they are, live shapes included. + // Fresh ids throughout, its opacity mask's art included. + let upper = d.node(above).cloned().ok_or(EngineError::NoNode(above))?; + let mut n = d.reid(&upper); + if let NodeKind::Path { path, live, .. } = &mut n.kind { + *path = outline; + *live = None; + } + let id = n.id; + let mut beside = Beside::above(d, &[above]); + beside.put(d, above, vec![n])?; + beside.finish(d)?; + id + } else { + // The upper circle becomes the outline (a plain path now) and the lower one goes. + if let Some(NodeKind::Path { path, live, .. }) = d.node_mut(above).map(|n| &mut n.kind) { + *path = outline; + *live = None; + } + remove_each(d, &[below])?; + above + }; + sel.set([id]); + Ok(id) + })?; + Ok(json!({ "id": id.0 })) +} diff --git a/crates/engine/src/cmd/addons/pathtools/bridge/tests.rs b/crates/engine/src/cmd/addons/pathtools/bridge/tests.rs new file mode 100644 index 0000000000..01320c07c1 --- /dev/null +++ b/crates/engine/src/cmd/addons/pathtools/bridge/tests.rs @@ -0,0 +1,184 @@ +//! Smooth Bridge: the outline in place of the circles or above them, one undo step, the radius, +//! and what it refuses. + +use serde_json::{Value, json}; +use vectorcraft_doc::{NodeId, NodeKind}; +use vectorcraft_geom::kurbo::Shape; + +use crate::Session; + +const BRIDGE: &str = "addon.pathtools.bridge"; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + s +} + +/// A circle about (`x`, `y`) with radius `r`. +fn circle(s: &mut Session, x: f64, y: f64, r: f64) -> NodeId { + let id = s.execute("shape.ellipse", &json!({"x": x - r, "y": y - r, "width": 2.0 * r, "height": 2.0 * r})).unwrap()["id"].as_u64().unwrap(); + NodeId(id) +} + +fn select(s: &mut Session, ids: &[NodeId]) { + s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})).unwrap(); +} + +fn top_level(s: &Session) -> Vec { + s.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|n| n.id).collect() +} + +fn area(s: &Session, id: NodeId) -> f64 { + s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().to_bezpath().area().abs() +} + +fn err(s: &mut Session, p: Value) -> String { + s.execute(BRIDGE, &p).unwrap_err().to_string() +} + +#[test] +fn two_circles_become_one_outline_in_the_upper_ones_place() { + let mut s = session(); + let a = circle(&mut s, 100.0, 100.0, 20.0); + let b = circle(&mut s, 160.0, 100.0, 20.0); + select(&mut s, &[a, b]); + let steps = s.doc().unwrap().history.undo.len(); + let r = s.execute(BRIDGE, &json!({})).unwrap(); + assert_eq!(r["id"], json!(b.0)); + assert_eq!(top_level(&s), [b]); + let d = &s.doc().unwrap().doc; + let NodeKind::Path { path, live, .. } = &d.node(b).unwrap().kind else { panic!("a path") }; + assert!(live.is_none(), "a plain path now"); + assert!(path.subpaths.len() == 1 && path.subpaths[0].closed); + let bounds = path.bounds().unwrap(); + assert!((bounds.x0 - 80.0).abs() < 1e-2 && (bounds.x1 - 180.0).abs() < 1e-2 && (bounds.height() - 40.0).abs() < 1e-2, "{bounds:?}"); + // Both circles and the bridge between them: more than the two circles' area. + assert!(area(&s, b) > 2.0 * std::f64::consts::PI * 400.0); + assert_eq!(s.doc().unwrap().selection.objects.to_vec(), [b]); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "one undo step"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(top_level(&s), [a, b]); + assert!(matches!(&s.doc().unwrap().doc.node(b).unwrap().kind, NodeKind::Path { live: Some(_), .. }), "the circle is back as it was"); +} + +#[test] +fn keep_originals_adds_the_outline_above_the_upper_circle() { + let mut s = session(); + let a = circle(&mut s, 100.0, 100.0, 30.0); + let b = circle(&mut s, 170.0, 100.0, 10.0); + let c = circle(&mut s, 300.0, 250.0, 5.0); + s.execute("paint.setFill", &json!({"ids": [b.0], "color": "#00ff00"})).unwrap(); + let steps = s.doc().unwrap().history.undo.len(); + let id = NodeId(s.execute(BRIDGE, &json!({"ids": [b.0, a.0], "keepOriginals": true, "radius": 400})).unwrap()["id"].as_u64().unwrap()); + assert_eq!(top_level(&s), [a, b, id, c]); + let d = &s.doc().unwrap().doc; + assert_eq!(d.node(id).unwrap().appearance, d.node(b).unwrap().appearance, "painted as the upper circle"); + assert!(matches!(&d.node(a).unwrap().kind, NodeKind::Path { live: Some(_), .. }), "the circles stay as they are"); + assert!(matches!(&d.node(b).unwrap().kind, NodeKind::Path { live: Some(_), .. })); + let bounds = d.node(id).unwrap().path_data().unwrap().bounds().unwrap(); + assert!((bounds.x0 - 70.0).abs() < 1e-2 && (bounds.x1 - 180.0).abs() < 1e-2 && (bounds.y0 - 70.0).abs() < 1e-2, "{bounds:?}"); + assert_eq!(s.doc().unwrap().selection.objects.to_vec(), [id]); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1); +} + +#[test] +fn a_kept_outline_gets_its_own_mask_art() { + let mut s = session(); + let a = circle(&mut s, 100.0, 100.0, 20.0); + let b = circle(&mut s, 150.0, 100.0, 20.0); + let m = NodeId(s.execute("shape.rectangle", &json!({"x": 130, "y": 80, "width": 40, "height": 40})).unwrap()["id"].as_u64().unwrap()); + s.execute("transparency.makeOpacityMask", &json!({"ids": [b.0, m.0]})).unwrap(); + let id = NodeId(s.execute(BRIDGE, &json!({"ids": [a.0, b.0], "keepOriginals": true})).unwrap()["id"].as_u64().unwrap()); + let d = &s.doc().unwrap().doc; + let art = |n: NodeId| d.node(n).unwrap().extras().mask.as_deref().map(|m| m.art.id); + let (kept, copied) = (art(b).unwrap(), art(id).unwrap()); + assert_ne!(kept, copied, "the outline's mask art has ids of its own"); +} + +#[test] +fn a_larger_radius_makes_a_wider_bridge() { + let area_at = |radius: f64| { + let mut s = session(); + let a = circle(&mut s, 100.0, 100.0, 20.0); + let b = circle(&mut s, 150.0, 100.0, 15.0); + let id = NodeId(s.execute(BRIDGE, &json!({"ids": [a.0, b.0], "radius": radius})).unwrap()["id"].as_u64().unwrap()); + area(&s, id) + }; + let (default, wider, widest) = (area_at(100.0), area_at(200.0), area_at(400.0)); + assert!(default < wider && wider < widest, "{default} {wider} {widest}"); + let (narrow, default, wide) = (area_at(65.0), default, area_at(300.0)); + assert!(narrow < default && default < wide, "{narrow} {default} {wide}"); + // The default is 100%: the smaller circle's radius. + let mut s = session(); + let a = circle(&mut s, 100.0, 100.0, 20.0); + let b = circle(&mut s, 150.0, 100.0, 15.0); + let id = NodeId(s.execute(BRIDGE, &json!({"ids": [a.0, b.0]})).unwrap()["id"].as_u64().unwrap()); + assert!((area(&s, id) - default).abs() < 1e-9); +} + +#[test] +fn overlapping_and_touching_circles_are_joined() { + for (gap, radius) in [(-15.0, 50.0), (0.0, 50.0), (0.0, 1.0)] { + let mut s = session(); + let a = circle(&mut s, 100.0, 100.0, 20.0); + let b = circle(&mut s, 140.0 + gap, 100.0, 20.0); + let id = NodeId(s.execute(BRIDGE, &json!({"ids": [a.0, b.0], "radius": radius})).unwrap()["id"].as_u64().unwrap()); + assert_eq!(top_level(&s), [id], "gap {gap}"); + } + // Unequal overlapping circles at every radius, the largest included. + for radius in [1.0, 100.0, 300.0, 1000.0] { + let mut s = session(); + let a = circle(&mut s, 100.0, 100.0, 10.0); + let b = circle(&mut s, 125.0, 100.0, 30.0); + let id = NodeId(s.execute(BRIDGE, &json!({"ids": [a.0, b.0], "radius": radius})).unwrap()["id"].as_u64().unwrap()); + assert_eq!(top_level(&s), [id], "radius {radius}"); + } +} + +#[test] +fn far_apart_nested_and_other_objects_are_refused() { + let mut s = session(); + let a = circle(&mut s, 50.0, 100.0, 10.0); + let far = circle(&mut s, 250.0, 100.0, 10.0); + let near = circle(&mut s, 110.0, 100.0, 10.0); + let inner = circle(&mut s, 52.0, 100.0, 4.0); + let square = NodeId(s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap()); + let oval = NodeId(s.execute("shape.ellipse", &json!({"x": 300, "y": 0, "width": 40, "height": 20})).unwrap()["id"].as_u64().unwrap()); + let before = top_level(&s); + let steps = s.doc().unwrap().history.undo.len(); + // 60 pt apart: the default radius (10 pt) cannot reach, the largest (100 pt) can. + assert!(err(&mut s, json!({"ids": [a.0, near.0]})).ends_with("too far apart for this radius: raise the radius")); + assert!(s.execute(BRIDGE, &json!({"ids": [a.0, near.0], "radius": 1000})).is_ok()); + s.execute("edit.undo", &json!({})).unwrap(); + // 200 pt apart even the largest radius (1000%, 100 pt) closes the neck: it stays open only above + // ((200 / 2)² − 10²) / (2 × 10) = 495 pt. No larger radius is suggested. + for radius in [100, 1000] { + let e = err(&mut s, json!({"ids": [a.0, far.0], "radius": radius})); + assert!(e.ends_with("the circles are too far apart for this radius"), "{e}"); + } + assert!(err(&mut s, json!({"ids": [a.0, inner.0]})).contains("one circle is inside the other")); + for ids in [json!([a.0, square.0]), json!([a.0, oval.0]), json!([a.0]), json!([a.0, far.0, inner.0])] { + assert!(err(&mut s, json!({ "ids": ids })).contains("select two circles to bridge"), "{ids}"); + } + assert!(err(&mut s, json!({"ids": [a.0, far.0], "radius": 0.5})).contains("`radius` must be from 1 to 1000")); + assert!(err(&mut s, json!({"ids": [a.0, far.0], "radius": 1001})).contains("`radius`")); + assert!(err(&mut s, json!({"ids": [a.0, far.0], "radius": "big"})).contains("`radius` must be a number")); + assert!(err(&mut s, json!({"ids": [a.0, far.0], "keepOriginals": "yes"})).contains("`keepOriginals` must be true or false")); + assert_eq!(top_level(&s), before); + assert_eq!(s.doc().unwrap().history.undo.len(), steps, "nothing changed, no undo step"); +} + +#[test] +fn locked_and_hidden_circles_are_not_bridged() { + let mut s = session(); + let a = circle(&mut s, 100.0, 100.0, 20.0); + let b = circle(&mut s, 150.0, 100.0, 20.0); + select(&mut s, &[b]); + s.execute("object.lock", &json!({})).unwrap(); + assert!(err(&mut s, json!({"ids": [a.0, b.0]})).contains("select two circles to bridge")); + s.execute("object.unlockAll", &json!({})).unwrap(); + select(&mut s, &[a]); + s.execute("object.hide", &json!({})).unwrap(); + assert!(err(&mut s, json!({"ids": [a.0, b.0]})).contains("select two circles to bridge")); +} diff --git a/crates/engine/src/cmd/brushsym.rs b/crates/engine/src/cmd/brushsym.rs index 57194d3d45..c026a1086e 100644 --- a/crates/engine/src/cmd/brushsym.rs +++ b/crates/engine/src/cmd/brushsym.rs @@ -165,7 +165,7 @@ pub fn specs() -> Vec { "Brush Options…", [], None, - "{name, params?: {…fields to change (brush.get shows them; values outside their ranges are clamped). calligraphic: angle −180..180° (counter-clockwise from level), roundness 0..100%, size 0..1296 pt, variation: [angle°, roundness%, size pt], modes: [fixed|random|pressure|tilt|bearing|rotation for angle, roundness, size] (pressure goes from value − variation at the lightest pen pressure to value + variation at the heaviest; tilt from value − variation with the pen lying flat to value + variation with it upright; bearing and rotation add variation × the pen's bearing (which way it leans, counter-clockwise from leaning right) or its barrel's counter-clockwise rotation over 180°; the angle turns on past ±180°). scatter: size [a, b] 1..10000%, spacing [a, b] 1..10000%, scatter [a, b] −1000..1000%, rotation [a, b] −180..180° (counter-clockwise), modes: [fixed|random|pressure|tilt|bearing|rotation for size, spacing, scatter, rotation] (fixed: a; random: between a and b; pressure: a at the lightest pen pressure to b at the heaviest; tilt: a with the pen lying flat to b upright; bearing and rotation: a at −180° to b at 180°), rotation_relative_to_path. art: width 1..1000%, width_mode: null (fixed)|pressure|tilt|bearing|rotation, width_max 1..1000% (pressure: width at the lightest pen pressure to width_max at the heaviest; tilt: width with the pen lying flat to width_max upright; bearing and rotation: width at −180° to width_max at 180°; half way on a stroke drawn without that input), scale: {mode: proportional|stretch|betweenGuides, start, end: 0..1 of the art length}, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flip_along, flip_across, overlap. pattern: scale 1..10000%, spacing 0..10000%, fit: stretch|addSpace|approximate, flip_along, flip_across, outer_corner and inner_corner: corner tile art (drawn as the corner that joins a side tile on its right to one below it) or null, outer_source and inner_source: what that kind of corner draws without its art: none|autoCentered|autoBetween|autoSliced|autoOverlap (a tile made from the side tile), or null (the other kind of corner's art); side_tile, outer_corner_tile, inner_corner_tile, start_tile, end_tile: a document pattern name, original, or none (side refuses none); corner tiles also take autoCentered|autoBetween|autoSliced|autoOverlap. Each tile also accepts {pattern: name} to select a swatch whose name is a reserved choice. scatter, art and pattern: colorization: {method: none|tints|tintsAndShades|hueShift, key: colour (hueShift: the art colour that becomes the stroke colour; without a key: the solid color the art's fills and strokes use most, black when they use none)}; colorization and the art brush's scale change only the fields given}, newName? (trimmed; blank: the name is kept; a new bristle brush name has at most 31 characters, and a longer name the brush has is kept)} edit a brush definition (strokes using it update) → {name}", + "{name, params?: {…fields to change (brush.get shows them; values outside their ranges are clamped). calligraphic: angle −180..180° (counter-clockwise from level), roundness 0..100%, size 0..1296 pt, variation: [angle°, roundness%, size pt], modes: [fixed|random|pressure|tilt|bearing|rotation for angle, roundness, size] (pressure goes from value − variation at the lightest pen pressure to value + variation at the heaviest; tilt from value − variation with the pen lying flat to value + variation with it upright; bearing and rotation add variation × the pen's bearing (which way it leans, counter-clockwise from leaning right) or its barrel's counter-clockwise rotation over 180°; the angle turns on past ±180°). scatter: size [a, b] 1..10000%, spacing [a, b] 1..10000%, scatter [a, b] −1000..1000%, rotation [a, b] −180..180° (counter-clockwise), modes: [fixed|random|pressure|tilt|bearing|rotation for size, spacing, scatter, rotation] (fixed: a; random: between a and b; pressure: a at the lightest pen pressure to b at the heaviest; tilt: a with the pen lying flat to b upright; bearing and rotation: a at −180° to b at 180°), rotation_relative_to_path, hue_jitter 0..180° (each copy turns the hue of its solid colors, after the colorization, by its own amount up to this far either way, the same on every redraw; colors without a hue stay; 0: off). art: width 1..1000%, width_mode: null (fixed)|pressure|tilt|bearing|rotation, width_max 1..1000% (pressure: width at the lightest pen pressure to width_max at the heaviest; tilt: width with the pen lying flat to width_max upright; bearing and rotation: width at −180° to width_max at 180°; half way on a stroke drawn without that input), scale: {mode: proportional|stretch|betweenGuides, start, end: 0..1 of the art length}, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flip_along, flip_across, overlap. pattern: scale 1..10000%, spacing 0..10000%, fit: stretch|addSpace|approximate, flip_along, flip_across, outer_corner and inner_corner: corner tile art (drawn as the corner that joins a side tile on its right to one below it) or null, outer_source and inner_source: what that kind of corner draws without its art: none|autoCentered|autoBetween|autoSliced|autoOverlap (a tile made from the side tile), or null (the other kind of corner's art); side_tile, outer_corner_tile, inner_corner_tile, start_tile, end_tile: a document pattern name, original, or none (side refuses none); corner tiles also take autoCentered|autoBetween|autoSliced|autoOverlap. Each tile also accepts {pattern: name} to select a swatch whose name is a reserved choice. scatter, art and pattern: colorization: {method: none|tints|tintsAndShades|hueShift, key: colour (hueShift: the art colour that becomes the stroke colour; without a key: the solid color the art's fills and strokes use most, black when they use none)}; colorization and the art brush's scale change only the fields given}, newName? (trimmed; blank: the name is kept; a new bristle brush name has at most 31 characters, and a longer name the brush has is kept)} edit a brush definition (strokes using it update) → {name}", has_doc, brush_options ), @@ -211,7 +211,7 @@ pub fn specs() -> Vec { "New Symbol…", [], None, - "{name?, ids?|id?, registration?: 0..8 (9-point grid, 4 = centre; Symbol Options › Registration), exportType?: movieClip (default)|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static (default)|dynamic (Symbol Options › Symbol Type), alignToPixelGrid?: bool (default false; Symbol Options › Align to Pixel Grid)} make a symbol from the selection and replace it with an instance; a frame of threaded text in the selection leaves its thread with the text it shows, which the symbol's art holds; nineSlice is Symbol Options › Enable Guides for 9-Slice Scaling, nineSliceGuides [left, top, right, bottom] as fractions of the natural size in from each edge, each -16..16 (below 0 or above 1 puts a guide outside the art), with left + right < 1 and top + bottom < 1 (default a quarter each); an instance of a symbol with guides keeps its corners' size when scaled, its edges stretch along their length and its center in both directions; alignToPixelGrid keeps the symbol's instances on the pixel grid as symbol.options describes → {name, id, registration, exportType, nineSlice, type, alignToPixelGrid}", + "{name?, ids?|id?, registration?: 0..8 (9-point grid, 4 = centre; Symbol Options › Registration), exportType?: movieClip (default)|graphic, nineSlice?: bool, nineSliceGuides?: array, type?: static (default)|dynamic (Symbol Options › Symbol Type), alignToPixelGrid?: bool (default false; Symbol Options › Align to Pixel Grid), keepArt?: false} make a symbol from the selection and replace it with an instance, or with keepArt: true leave the selection as ordinary art where it is, still selected, with id null; a frame of threaded text in the selection that becomes an instance leaves its thread with the text it shows, which the symbol's art holds; nineSlice is Symbol Options › Enable Guides for 9-Slice Scaling, nineSliceGuides [left, top, right, bottom] as fractions of the natural size in from each edge, each -16..16 (below 0 or above 1 puts a guide outside the art), with left + right < 1 and top + bottom < 1 (default a quarter each); an instance of a symbol with guides keeps its corners' size when scaled, its edges stretch along their length and its center in both directions; alignToPixelGrid keeps the symbol's instances on the pixel grid as symbol.options describes → {name, id, registration, exportType, nineSlice, type, alignToPixelGrid}", has_selection, symbol_new ), @@ -265,7 +265,7 @@ pub fn specs() -> Vec { "Redefine Symbol", [], None, - "{name, ids?|id?} replace the symbol's art with the selection (instances update, keeping their appearance changes to the objects at paths the new art still has; the selection becomes an instance; a frame of threaded text in the selection leaves its thread with the text it shows, which the symbol's art holds) → {name, id}", + "{name, ids?|id?, keepArt?: false} replace the symbol's art with the selection (instances update, keeping their appearance changes to the objects at paths the new art still has; the selection becomes an instance, or with keepArt: true stays ordinary art where it is, still selected, and id is null; a frame of threaded text in the selection that becomes an instance leaves its thread with the text it shows, which the symbol's art holds; art that holds an instance of the symbol (opacity masks included), directly or through the symbols it nests, is refused) → {name, id}", has_selection, symbol_update ), diff --git a/crates/engine/src/cmd/brushsym/brushes.rs b/crates/engine/src/cmd/brushsym/brushes.rs index c980f44adf..b0ab4366d2 100644 --- a/crates/engine/src/cmd/brushsym/brushes.rs +++ b/crates/engine/src/cmd/brushsym/brushes.rs @@ -32,7 +32,12 @@ pub(super) fn brush_list(s: &mut Session, _: &Value) -> Result { pub(super) fn brush_get(s: &mut Session, p: &Value) -> Result { let name = name_param(p, "brush.get")?; let b = brush::find(&s.doc()?.doc, name).ok_or_else(|| EngineError::Other(format!("no brush named `{name}`")))?; - Ok(serde_json::to_value(b).unwrap_or_default()) + let mut v = serde_json::to_value(&b).unwrap_or_default(); + // A scatter brush saves its hue jitter only when it is not 0; brush.get shows it either way. + if let (BrushKind::Scatter(sc), Some(o)) = (&b.kind, v.as_object_mut()) { + o.entry("hue_jitter").or_insert(json!(sc.hue_jitter)); + } + Ok(v) } /// The art `brush.new` takes from `ids` or `id`, else from the selection ([`selection_art`]). diff --git a/crates/engine/src/cmd/brushsym/symbols.rs b/crates/engine/src/cmd/brushsym/symbols.rs index cecd314858..f5245bc9af 100644 --- a/crates/engine/src/cmd/brushsym/symbols.rs +++ b/crates/engine/src/cmd/brushsym/symbols.rs @@ -253,6 +253,9 @@ pub(super) fn symbol_new(s: &mut Session, p: &Value) -> Result { let nine = nine_slice_param(p, C, None)?.flatten(); let dynamic = type_param(p, C)?.unwrap_or(false); let pixel = pixel_grid_param(p, C)?.unwrap_or(false); + // `keepArt` leaves the art as ordinary art instead of replacing it with an instance. + let keep_art = switch_or(p, "keepArt", false, C)?; + let iso = s.doc()?.isolation; // Keep the art where it was: the geometric centre stays at `c`, whatever the registration is. let place = place_xf(c + reg.offset_from_center(size.0, size.1), size, reg); let id = s.edit("New Symbol", |d, sel| { @@ -264,13 +267,20 @@ pub(super) fn symbol_new(s: &mut Session, p: &Value) -> Result { d.set_symbol_export_type(&name, export); d.set_symbol_nine_slice(&name, nine); d.set_symbol_pixel_aligned(&name, pixel); + if keep_art { + // The art stays where it is and stays selected, apart from art that is hidden or + // locked, in a hidden or locked group or layer, or on a locked artboard. + let locks = d.locked_artboards(); + sel.set(ids.iter().copied().filter(|i| crate::cmd::select::is_selectable(d, iso, &locks, *i))); + return Ok(None); + } let id = instance_in_place(d, &ids, &name, place)?; sel.set([id]); - Ok(id) + Ok(Some(id)) })?; Ok(json!({ "name": name, - "id": id.0, + "id": id.map(|i| i.0), "registration": reg.0, "exportType": export.id(), "nineSlice": nine.map_or(Value::Null, SymbolNineSlice::to_value), @@ -612,6 +622,8 @@ pub(super) fn symbol_update(s: &mut Session, p: &Value) -> Result { } // Redefining the symbol being edited leaves symbol editing mode in the same step. let session = s.doc()?.doc.symbol_edit.clone().filter(|e| e.symbol == name); + // `keepArt` leaves the art as ordinary art instead of replacing it with an instance. + let keep_art = switch_or(p, "keepArt", false, C)?; if session.is_some() { crate::cmd::settle_interaction(s)?; s.end_text_edit(); @@ -625,10 +637,20 @@ pub(super) fn symbol_update(s: &mut Session, p: &Value) -> Result { } } let mut art = selection_art(s, p)?.ok_or_else(|| EngineError::Other("nothing selected".into()))?; + // Nor can art that holds an instance of it, directly or through the symbols it nests. + if crate::cmd::symboledit::holds_symbol(&s.doc()?.doc, &art, &name, &mut Default::default()) { + return Err(EngineError::Other("a symbol can't hold an instance of itself".into())); + } crate::cmd::threads::keep_shown_text(&s.doc()?.doc, &mut art); let (art, size, c) = normalize(art)?; let old = natural_size(&s.doc()?.doc, &name); let editing = session.is_some(); + // The isolation the kept art is selected in: the one from before symbol editing mode when + // the step leaves it. + let iso = match &session { + Some(se) => se.back_isolation, + None => s.doc()?.isolation, + }; let id = s.edit("Redefine Symbol", |d, sel| { if editing { crate::cmd::symboledit::finish(d, sel); @@ -647,15 +669,22 @@ pub(super) fn symbol_update(s: &mut Session, p: &Value) -> Result { } // Each instance keeps its appearance changes to the objects the new art still has. fit_overrides(d, &instances); + if keep_art { + // The art stays where it is and stays selected, apart from art that is hidden or + // locked, in a hidden or locked group or layer, or on a locked artboard. + let locks = d.locked_artboards(); + sel.set(ids.iter().copied().filter(|i| crate::cmd::select::is_selectable(d, iso, &locks, *i))); + return Ok(None); + } let reg = d.symbol_registration(&name); let id = instance_in_place(d, &ids, &name, place_xf(c + reg.offset_from_center(size.0, size.1), size, reg))?; sel.set([id]); - Ok(id) + Ok(Some(id)) })?; if let Some(se) = &session { crate::cmd::symboledit::leave_editing(s, se)?; } - Ok(json!({ "name": name, "id": id.0 })) + Ok(json!({ "name": name, "id": id.map(|i| i.0) })) } /// How many levels of nested instances Delete Symbol expands before it gives up. diff --git a/crates/engine/src/cmd/create.rs b/crates/engine/src/cmd/create.rs index e9fcad8883..803057885a 100644 --- a/crates/engine/src/cmd/create.rs +++ b/crates/engine/src/cmd/create.rs @@ -126,7 +126,7 @@ pub fn specs() -> Vec { "Create Text", [], None, - "{x, y, text, rotation?: deg clockwise about x, y (0: level), vertical?: bool = false, size?: pt 0.1..1296 (outside it: an error, and no type is made), font?: family, style? (default Regular, or the family's closest style when it has no Regular), color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), area?: {width, height, fit?: none|autoHeight|shrinkText|block, fitMinPercent?, wordGap?, lineGap? (as text.areaOptions)}, placeholder?: bool (fill it with placeholder text instead, as the Type tools do with prefs placeholderText), justify?: \"auto\" (default: the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\" (point type: aligned on x, so \"center\" centres each line on the point and \"right\" ends it there; text.setStyle changes it later), leadingModel?: \"romanBaseline\"|\"emBoxTop\", charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (default: emBoxTop and emBoxCenter while the interface is in Japanese, else romanBaseline)} → {id, bounds: {x, y, width, height} (the new type's box as document.inspect reports it, after justify), overflow?: [id] (area type whose text doesn't fit its frame: the lines past it aren't drawn; left out when it fits), warning?: text (the font or style given isn't available: the type is drawn in the fallback font or the family's closest style)}; new area type gets Auto Size (fit autoHeight) when the autoSizeAreaType preference is on", + "{x, y, text, rotation?: deg clockwise about x, y (0: level), vertical?: bool = false, size?: pt 0.1..1296 (outside it: an error, and no type is made), font?: family, style? (default Regular, or the family's closest style when it has no Regular), color? (#rrggbbaa and #rgba are refused; size, font, style and color left out come from [Normal Character Style], the defaults unless the document redefined it), keepModel?: bool (as paint.setFill), area?: {width, height, fit?: none|autoHeight|shrinkText|block, fitMinPercent?, wordGap?, lineGap? (as text.areaOptions)}, placeholder?: bool (fill it with placeholder text instead, as the Type tools do with prefs placeholderText), justify?: \"auto\" (default: the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\" (point type: aligned on x, so \"center\" centres each line on the point and \"right\" ends it there; text.setStyle changes it later), leadingModel?: \"romanBaseline\"|\"emBoxTop\", charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (default: emBoxTop and emBoxCenter while the interface is in Japanese, else romanBaseline)} → {id, bounds: {x, y, width, height} (the new type's box as document.inspect reports it, after justify), overflow?: [id] (area type whose text doesn't fit its frame: the lines past it aren't drawn; left out when it fits), warning?: text (the font or style given isn't available: the type is drawn in the fallback font or the family's closest style)}; new area type gets Auto Size (fit autoHeight) when the autoSizeAreaType preference is on", has_doc, text_create ), @@ -940,7 +940,13 @@ fn text_create(s: &mut Session, p: &Value) -> Result { let id = made.get("id").and_then(Value::as_u64).map(NodeId); let made = super::typecmd::with_bounds(s, id, made); let mut made = super::typecmd::with_overflow(s, id.as_slice(), made); - if p.get("font").is_some() || p.get("style").is_some() { + // A face from a redefined [Normal Character Style] is checked too, as one given here is. + let normal_face = s + .doc() + .ok() + .and_then(|d| super::textstyles::style_attrs(&d.doc, false, super::textstyles::NORMAL_CHAR)) + .is_some_and(|m| m.contains_key("font_family") || m.contains_key("font_style")); + if p.get("font").is_some() || p.get("style").is_some() || normal_face { let runs = match id.and_then(|i| s.doc().ok()?.doc.node(i)).map(|n| &n.kind) { Some(NodeKind::Text(t)) => t.runs.iter().flat_map(super::fonts::run_fonts).collect(), _ => Default::default(), @@ -968,8 +974,9 @@ pub(crate) fn new_type_para() -> vectorcraft_doc::ParaStyle { /// The paragraph alignment, leading model and character alignment new type starts with (`t`'s /// paragraph and runs): `justify` from `p` (else as [`new_type_para`] left it), `leadingModel` -/// and `charAlign` from `p`, else em box top to top and em box centre while the -/// interface is in Japanese (#432), else the Roman baseline for both. Noted in the journal, so a +/// and `charAlign` from `p` (`charAlign` else from a redefined `[Normal Character Style]` that +/// sets it), else em box top to top and em box centre while the interface is in Japanese (#432), +/// else the Roman baseline for both. Noted in the journal, so a /// replay sets the same whatever the interface. pub(crate) fn new_type_alignment(s: &mut Session, p: &Value, cmd: &str, t: &mut TextObject) -> Result<()> { use vectorcraft_doc::{CharAlign, LeadingModel}; @@ -989,7 +996,14 @@ pub(crate) fn new_type_alignment(s: &mut Session, p: &Value, cmd: &str, t: &mut l } }; - let align = match super::textedit::char_align_param(p, cmd)? { + // A redefined [Normal Character Style] that sets Character Alignment gives it to new type. + let normal_align = s + .doc() + .ok() + .and_then(|d| super::textstyles::style_attrs(&d.doc, false, super::textstyles::NORMAL_CHAR)) + .filter(|m| m.contains_key("charAlign")) + .and(t.runs.first().map(|r| r.style.char_align)); + let align = match super::textedit::char_align_param(p, cmd)?.or(normal_align) { Some(a) => a, None => { let a = if japanese { CharAlign::EmBoxCenter } else { CharAlign::RomanBaseline }; @@ -1017,17 +1031,25 @@ pub(crate) fn new_area_fit(s: &Session, p: &Value, c: &str, t: &mut TextObject) } /// The character style new type gets: `size`, `font`, `style` and `color` from `p` (an RGB -/// `color` in a CMYK document as [`super::paint::new_color`] stores it), else the defaults, -/// filled as `[Normal Character Style]` is (black unless redefined; never the current fill, -/// #7975), in the document's -/// language. A `size` outside [`super::typecmd::TYPE_SIZES`] is an error. +/// `color` in a CMYK document as [`super::paint::new_color`] stores it), else +/// `[Normal Character Style]`'s (the default font, size and black fill unless redefined; +/// never the current fill, #7975), in the style's language, else the document's. A `size` outside +/// [`super::typecmd::TYPE_SIZES`] is an error. pub(crate) fn new_type_style(s: &Session, p: &Value, cmd: &str) -> Result { - let mut style = CharStyle::default(); + let mut style = s.doc().map_or_else(|_| CharStyle::default(), |d| super::textstyles::normal_char_style(&d.doc)); if let Some(sz) = p.get("size").and_then(Value::as_f64) { style.size = super::typecmd::given_type_size(sz, cmd)?; } + if str_param(p, "font").is_some() || str_param(p, "style").is_some() { + // A face given to the command takes its own version and axis settings, as a font change + // does, not those [Normal Character Style] gave another face. + style.font_version = None; + style.font_axes.clear(); + } if let Some(f) = str_param(p, "font") { style.font_family = f.to_string(); + // A family alone starts in Regular, whatever style [Normal Character Style] has. + style.font_style = CharStyle::default().font_style; } if let Some(f) = str_param(p, "style") { style.font_style = f.to_string(); @@ -1037,12 +1059,15 @@ pub(crate) fn new_type_style(s: &Session, p: &Value, cmd: &str) -> Result vectorcraft_color::Paint::solid(super::paint::new_color(s, p, c)), - None => s.doc().map_or_else(|_| CharStyle::default().fill, |d| super::textstyles::normal_char_fill(&d.doc)), + None => style.fill, }; - // In the language Document Setup chose, else Preferences › Hyphenation › Default Language; none - // for the default. Type already in a document keeps its own. - let chosen = |name: &str| vectorcraft_doc::setup::char_language(name).ok().flatten(); - let document = s.doc().ok().and_then(|d| chosen(&d.doc.setup.language)); - style.language = document.or_else(|| chosen(&s.prefs.hyphenation_language)).map(str::to_string); + // In the language a redefined [Normal Character Style] gives, else the one Document Setup chose, + // else Preferences › Hyphenation › Default Language; none for the default. Type already in a + // document keeps its own. + if style.language.is_none() { + let chosen = |name: &str| vectorcraft_doc::setup::char_language(name).ok().flatten(); + let document = s.doc().ok().and_then(|d| chosen(&d.doc.setup.language)); + style.language = document.or_else(|| chosen(&s.prefs.hyphenation_language)).map(str::to_string); + } Ok(style) } diff --git a/crates/engine/src/cmd/dimension.rs b/crates/engine/src/cmd/dimension.rs index 183cbd3746..955401b923 100644 --- a/crates/engine/src/cmd/dimension.rs +++ b/crates/engine/src/cmd/dimension.rs @@ -3,10 +3,8 @@ use super::{CommandSpec, EngineError, Result, Session, cmd, has_doc}; use serde_json::{Value, json}; use std::sync::Arc; use vectorcraft_color::{Color, Paint}; -use vectorcraft_doc::dimension::{ - ArrowStyle, Dimension, DimensionMode, DimensionOptions, DimensionSource, LineType, Orientation, TextAlignment, TextPosition, -}; -use vectorcraft_doc::{Appearance, Arrowhead, CharStyle, ColorMode, Dash, Document, Node, NodeId, NodeKind, TextObject}; +use vectorcraft_doc::dimension::{Dimension, DimensionMode, DimensionOptions, DimensionSource, LineType, Orientation, TextAlignment, TextPosition}; +use vectorcraft_doc::{Appearance, CharStyle, ColorMode, Dash, Document, Node, NodeId, NodeKind, TextObject}; use vectorcraft_geom::{Affine, BezPath, PathData, Point, Vec2}; pub fn specs() -> Vec { @@ -567,12 +565,7 @@ fn appearance(o: &DimensionOptions, mode: ColorMode, ext: bool, arrows: bool) -> LineType::Solid => None, }; if arrows { - let head = match o.arrow_style { - ArrowStyle::Filled => Some(Arrowhead::Triangle), - ArrowStyle::Open => Some(Arrowhead::TriangleOpen), - ArrowStyle::Tick => Some(Arrowhead::Slash), - ArrowStyle::None => None, - }; + let head = o.arrow_style.arrowhead(); st.start_arrow = head.clone(); st.end_arrow = head; st.arrow_scale = (o.arrow_scale, o.arrow_scale); diff --git a/crates/engine/src/cmd/docmenu.rs b/crates/engine/src/cmd/docmenu.rs index 709b4cda65..717c9cdc14 100644 --- a/crates/engine/src/cmd/docmenu.rs +++ b/crates/engine/src/cmd/docmenu.rs @@ -238,7 +238,7 @@ pub fn specs() -> Vec { "Move Guide", [], None, - "{index, pos: pt} | {dx?, dy?: pt, copy?: bool} put ruler guide `index` at `pos`, or move the selected guides (vertical ones by dx, horizontal ones by dy); copy leaves them and selects the moved copies", + "{index, pos: pt} | {dx?, dy?: pt, copy?: bool, interpolate?: bool (with art selected too: as object.move's)} put ruler guide `index` at `pos`, or move the selected guides (vertical ones by dx, horizontal ones by dy); copy leaves them and selects the moved copies", guides_unlocked, guide_move ), @@ -990,6 +990,7 @@ pub(crate) fn guide_move(s: &mut Session, p: &Value) -> Result { let dx = number_or(p, "dx", 0.0, "guide.move")?; let dy = number_or(p, "dy", 0.0, "guide.move")?; let copy = switch_or(p, "copy", false, "guide.move")?; + switch_or(p, "interpolate", false, "guide.move")?; if !s.doc()?.selection.is_empty() { let ids = super::edit::selected_roots(s)?; return super::object::apply_transform( diff --git a/crates/engine/src/cmd/effectcmd/graphics.rs b/crates/engine/src/cmd/effectcmd/graphics.rs index 1c9d3e2afa..498f322e91 100644 --- a/crates/engine/src/cmd/effectcmd/graphics.rs +++ b/crates/engine/src/cmd/effectcmd/graphics.rs @@ -29,7 +29,7 @@ pub(super) fn specs() -> Vec { "Map Graphic", [], None, - "{symbol: name of a document symbol, face?: front|back (front; Plane has only a front; the back reads left to right as seen from behind; on Revolve the front is its swept side, which is the only face; on Inflate the back takes graphics only with Both sides and Cap on), x?: pt, y?: pt (0, 0: the offset of the graphic's center from the center of the object's bounds, in the face's own plane; on Inflate in the art's plane, the graphic carried straight out onto the puffed face; on Revolve from the middle of the side unrolled flat, x around the axis and y along the profile), scale?: % (1..10000; default 100, or less so the graphic fits inside the object, on Revolve inside the half of the side seen from the front), rotation?: degrees (-360..360, 0; counterclockwise), index?: int (the 3D effect's position; default: each object's first 3D effect, its own before its fills' and strokes'), item?: appearance item index|null (refused without index; as effect.setParams), ids?|id?} add a graphic to the 3D effect of each selected object, drawn on that face turned, foreshortened and shaded with it and clipped to it (on Revolve wrapped around the side, and on Inflate following the puff, Twist and Taper carrying the back's, each drawn only where its outside faces the viewer); every object's 3D effect must be Extrude & Bevel (on a solid cap), Rotate (the Plane type), Revolve or Inflate; one undo step → {ids, graphic}", + "{symbol: name of a document symbol, face?: front|back|side (front; Plane has only a front; the back reads left to right as seen from behind; side is Extrude & Bevel's walls and bevels; on Revolve the front is its swept side, which is the only face; on Inflate the back takes graphics only with Both sides and Cap on), x?: pt, y?: pt (0, 0: the offset of the graphic's center from the center of the object's bounds, in the face's own plane; on Inflate in the art's plane, the graphic carried straight out onto the puffed face; on a side from the middle of the side unrolled flat: on Extrude & Bevel x along the outline, clockwise from its top, and y from the front toward the back; on Revolve x around the axis and y along the profile), scale?: % (1..10000; default 100, or less so the graphic fits inside the object, on Extrude & Bevel's side inside the side unrolled about x = 0, short of its cut, on Revolve inside the half of the side seen from the front), rotation?: degrees (-360..360, 0; counterclockwise), index?: int (the 3D effect's position; default: each object's first 3D effect, its own before its fills' and strokes'), item?: appearance item index|null (refused without index; as effect.setParams), ids?|id?} add a graphic to the 3D effect of each selected object, drawn on that face turned, foreshortened and shaded with it and clipped to it (on a side wrapped around it, and on Inflate following the puff, Twist and Taper carrying the back's, each drawn only where its outside faces the viewer); every object's 3D effect must be Extrude & Bevel (on a solid cap, or on the side, hollow or not), Rotate (the Plane type), Revolve or Inflate; one undo step → {ids, graphic}", has_doc, map_graphic ), @@ -114,15 +114,16 @@ fn map_graphic(s: &mut Session, p: &Value) -> Result { if !effects::takes_graphics(&effect.id) { return Err(bad(C, format!("object {}: {}", id.0, effects::GRAPHICS_NOT_TAKEN))); } - // A hollow Extrude & Bevel keeps the graphics it has, to show when Cap is turned on again, - // but has no cap to show a new one on. + // A hollow Extrude & Bevel keeps the graphics it has on its caps, to show when Cap is turned + // on again, but has no cap to show a new one on. Its side takes graphics. let merged = effects::merged_params(&effect.id, &effect.params); let extrude = (effect.id == effects::EXTRUDE).then(|| effects::extrude_options(&merged)); - if extrude.is_some_and(|o| o.depth > 0.0 && !o.cap) { + let side = base.face == effects::PlanarFace::Side; + if !side && extrude.is_some_and(|o| o.depth > 0.0 && !o.cap) { return Err(bad(C, format!("object {}: a hollow Extrude & Bevel has no caps: turn on Cap to map a graphic", id.0))); } // With a depth of 0 the art is a plane, which has only a front. - if base.face == effects::PlanarFace::Back && extrude.is_some_and(|o| o.depth <= 0.0) { + if base.face != effects::PlanarFace::Front && extrude.is_some_and(|o| o.depth <= 0.0) { return Err(bad(C, format!("object {}: with a depth of 0 the object has one face: map its graphics onto the front", id.0))); } // Inflate's back takes graphics where it puffs out: with Both sides and Cap on. @@ -134,9 +135,18 @@ fn map_graphic(s: &mut Session, p: &Value) -> Result { } let mut graphic = base.clone(); if p.get("scale").is_none() - && let (Some(frame), Some(art)) = (effects::graphic_frame_at(Some(d), n, item, index), effects::graphic_bounds(d, &graphic.symbol)) + && let Some(art) = effects::graphic_bounds(d, &graphic.symbol) { - graphic.scale = frame.fitting_scale(art); + // A graphic on the side starts fitting inside the side unrolled about x = 0, short of + // its cut; one on a cap inside the object's bounds. + let fit = if side { + effects::graphic_side_size(Some(d), n, item, index).map(|(w, h)| effects::graphic_fitting_scale(w, h, art)) + } else { + effects::graphic_frame_at(Some(d), n, item, index).map(|frame| frame.fitting_scale(art)) + }; + if let Some(fit) = fit { + graphic.scale = fit; + } } let params = effects::with_graphic(&effects::merged_params(&effect.id, &effect.params), &graphic); effects::validate_three_d_at_in(Some(d), n, &effect.id, ¶ms, (item, index)).map_err(|e| bad(C, e))?; diff --git a/crates/engine/src/cmd/effectcmd/graphics_tests.rs b/crates/engine/src/cmd/effectcmd/graphics_tests.rs index dcd4c1e99c..ca8ae77e68 100644 --- a/crates/engine/src/cmd/effectcmd/graphics_tests.rs +++ b/crates/engine/src/cmd/effectcmd/graphics_tests.rs @@ -135,6 +135,47 @@ fn map_graphic_refuses_what_cannot_take_it_and_changes_nothing() { assert!(s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "ids": [id.0]})).is_ok()); } +#[test] +fn map_graphic_puts_a_graphic_on_the_side_of_an_extrude() { + let (mut s, id) = setup("threeD.extrude"); + // A hollow Extrude & Bevel takes a graphic on its side. + s.execute("effect.setParams", &json!({"index": 0, "item": null, "params": {"cap": false}})).unwrap(); + s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "face": "side", "y": 4.0, "ids": [id.0]})).unwrap(); + assert_eq!(graphics(&s, id), json!([{"symbol": "Mark", "face": "side", "x": 0.0, "y": 4.0, "scale": 100.0, "rotation": 0.0}])); + // A plane, and a depth of 0, have no side. + let (mut s, plane) = setup("threeD.rotate"); + let history = undo_len(&s); + let e = s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "face": "side", "ids": [plane.0]})).unwrap_err().to_string(); + assert!(e.contains("one face"), "{e}"); + assert_eq!(undo_len(&s), history); + let (mut s, flat) = setup("threeD.extrude"); + s.execute("effect.setParams", &json!({"index": 0, "item": null, "params": {"depth": 0.0}})).unwrap(); + let history = undo_len(&s); + let e = s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "face": "side", "ids": [flat.0]})).unwrap_err().to_string(); + assert!(e.contains("one face"), "{e}"); + assert_eq!(undo_len(&s), history); + // A graphic taller than the side starts scaled to fit it: the side of the 100 × 100 square is + // about 300 pt wide short of its cut and 10 pt deep here, and the graphic with its stroke is + // 11 × 21. + let (mut s, id) = setup("threeD.extrude"); + s.execute("effect.setParams", &json!({"index": 0, "item": null, "params": {"depth": 10.0}})).unwrap(); + s.execute("threeD.mapGraphic", &json!({"symbol": "Mark", "face": "side", "ids": [id.0]})).unwrap(); + let scale = graphics(&s, id)[0]["scale"].as_f64().unwrap(); + assert!((scale - 1000.0 / 21.0).abs() < 1e-9, "{scale}"); + // A graphic wider than the side is kept short of the cut, at a bottom corner of the square: the + // part about x = 0 is three quarters of the outline. + let (mut s, id) = setup("threeD.extrude"); + let wide = s.execute("path.create", &json!({"d":"M0 380L400 380L400 390L0 390Z"})).unwrap()["id"].clone(); + s.execute("threeD.addGraphic", &json!({"name": "Wide", "ids": [wide]})).unwrap(); + s.execute("threeD.mapGraphic", &json!({"symbol": "Wide", "face": "side", "ids": [id.0]})).unwrap(); + let d = &s.doc().unwrap().doc; + let (span, _) = vectorcraft_render::effects::graphic_side_size(Some(d), d.node(id).unwrap(), None, 0).unwrap(); + let art = vectorcraft_render::effects::graphic_bounds(d, "Wide").unwrap(); + assert!((span - 300.0).abs() < 1e-6 || (span - 303.0).abs() < 1e-6, "{span}"); + let scale = graphics(&s, id)[0]["scale"].as_f64().unwrap(); + assert!((scale - 100.0 * span / art.width()).abs() < 1e-9, "{scale}"); +} + #[test] fn set_params_edits_graphics_and_checks_them() { let (mut s, id) = setup("threeD.extrude"); diff --git a/crates/engine/src/cmd/fileio/access.rs b/crates/engine/src/cmd/fileio/access.rs index 1ded8d1f0b..bd55624b32 100644 --- a/crates/engine/src/cmd/fileio/access.rs +++ b/crates/engine/src/cmd/fileio/access.rs @@ -144,8 +144,9 @@ pub(crate) fn check_scripts_of(cmd: &str, doc: &vectorcraft_doc::Document, doc_p } /// Does a file of a document with `artboards` artboards, written in format `format` with options -/// `p`, name the JavaScript files the document links? SVG, SVGZ, native files, native templates and -/// EPS files always do. A `.ai` or `.ait` file does unless it is a legacy version 7 `.ai` file or `p` +/// `p`, name the JavaScript files the document links? SVG, SVGZ, native files, native templates, +/// EPS files and the files of an exporter plug-in's format (`plugin.`, whose plug-in is given +/// the native document's JSON) always do. A `.ai` or `.ait` file does unless it is a legacy version 7 `.ai` file or `p` /// picks only some of the artboards; a PDF does with Preserve Editing on (as its preset, standard and /// options leave it) unless `p` picks only some of the artboards. Neither a `.ai` file nor a PDF /// does when `useArtboards` is false in `p` (one page, the bounds of the art). Options the encoder @@ -159,6 +160,7 @@ pub(crate) fn names_linked_scripts(cmd: &str, format: &str, p: &Value, artboards let art_page = || super::encode::use_artboards(cmd, p).is_ok_and(|u| u == Some(false)); match format { "svg" | "svgz" | "vectorcraft" | "template" | "eps" => true, + _ if vectorcraft_plugins::export::plugin_id(format).is_some() => true, "ai" | "ait" => { let legacy = super::format(format).is_some_and(|f| super::legacy_ai::wanted(cmd, f, p).unwrap_or(false)); !legacy && !(format == "ai" && art_page()) && every_artboard() @@ -228,7 +230,8 @@ pub(crate) fn check_images_in(cmd: &str, format: &str, d: &vectorcraft_doc::Docu /// `cmd` may write `d` in format `format` (a format id other than SVG and SVGZ) with options `p`: /// always, unless read roots are in force, the file carries the native document (a native file or -/// template, an EPS file, a `.ai` or `.ait` file or a PDF with Preserve Editing, as +/// template, an EPS file, a `.ai` or `.ait` file, a PDF with Preserve Editing or an exporter +/// plug-in's file, as /// [`names_linked_scripts`] counts them with `d`'s artboards) and that document names a file /// outside them ([`crate::cmd::links::names_hidden_file`]: a linked image or placed file, the /// relative path kept of one taken from `base`, a data set's image, or stored brushes that can't be diff --git a/crates/engine/src/cmd/fileio/encode.rs b/crates/engine/src/cmd/fileio/encode.rs index 3e34dae7f2..8b5cd9fe6f 100644 --- a/crates/engine/src/cmd/fileio/encode.rs +++ b/crates/engine/src/cmd/fileio/encode.rs @@ -1053,12 +1053,14 @@ fn encode_all_of(doc: &Document, format: &str, p: &Value) -> Result { /// The file exporter plug-in `plugin` writes of `doc` in its format `f` /// ([`vectorcraft_plugins::export`]). The plug-in is given the native file's JSON -/// ([`vectorcraft_format::json_part`]) and `p`'s `params`, for the file `p`'s `path` names (else -/// one named after the document) with that path's extension when the plug-in lists it, else its -/// first. Its warnings come back with the file, as losses (the plug-in gives them no kind). +/// ([`vectorcraft_format::json_part`]), without an Export for Screens folder outside the read roots +/// ([`super::access::with_readable_settings_folder`]), and `p`'s `params`, for the file `p`'s `path` +/// names (else one named after the document) with that path's extension when the plug-in lists it, +/// else its first. Its warnings come back with the file, as losses (the plug-in gives them no kind). fn plugin_file(doc: &Document, plugin: &vectorcraft_plugins::Plugin, f: &Format, p: &Value) -> Result { use vectorcraft_plugins::{Error, export}; - let doc = &*doc.without_edit_modes(); + let doc = doc.without_edit_modes(); + let doc = &*super::access::with_readable_settings_folder(&doc); let file = vectorcraft_format::save_with(doc, &vectorcraft_format::SaveOptions::default()).map_err(|e| EngineError::Other(e.to_string()))?; let path = p.get("path").and_then(Value::as_str); let listed = path.map(super::extension).and_then(|e| f.extensions.iter().copied().find(|x| *x == e)); diff --git a/crates/engine/src/cmd/live.rs b/crates/engine/src/cmd/live.rs index 618865cede..1d23d07792 100644 --- a/crates/engine/src/cmd/live.rs +++ b/crates/engine/src/cmd/live.rs @@ -29,6 +29,8 @@ mod commands; mod common; mod envelope; mod mesh; +#[cfg(test)] +mod selected_tests; pub(crate) use blend::expand_blends; pub use commands::specs; diff --git a/crates/engine/src/cmd/live/blend.rs b/crates/engine/src/cmd/live/blend.rs index 5334311789..a2cb0e3f91 100644 --- a/crates/engine/src/cmd/live/blend.rs +++ b/crates/engine/src/cmd/live/blend.rs @@ -657,9 +657,8 @@ pub(super) fn blend_replace_spine(s: &mut Session, _: &Value) -> Result { } /// Is any selected blend one made without a spine? -fn any_without_spine(s: &Session) -> bool { - let Ok(st) = s.doc() else { return false }; - selected_of(s, is_blend).iter().any(|b| matches!(st.doc.node(*b).map(|n| &n.kind), Some(NodeKind::Blend { spec, .. }) if spec.no_spine)) +pub(super) fn any_without_spine(s: &Session) -> bool { + super::common::any_selected_of(s, is_blend, |n| matches!(&n.kind, NodeKind::Blend { spec, .. } if spec.no_spine)) } pub(super) fn blend_reverse_spine(s: &mut Session, _: &Value) -> Result { diff --git a/crates/engine/src/cmd/live/common.rs b/crates/engine/src/cmd/live/common.rs index cfa3f32076..661d574b58 100644 --- a/crates/engine/src/cmd/live/common.rs +++ b/crates/engine/src/cmd/live/common.rs @@ -1,3 +1,5 @@ +use std::collections::HashSet; + use super::mesh::whole; use super::{ Arc, BlendEase, BlendEaseType, BlendOrientation, BlendSpacing, Document, EngineError, Node, NodeId, NodeKind, Result, Selection, Session, Value, @@ -20,13 +22,14 @@ pub(super) fn roots_param(s: &Session, p: &Value) -> Result> { let mut sel = Selection::default(); sel.set(ids.iter().copied().filter(|id| st.doc.node(*id).is_some_and(|n| !n.is_layer()))); let ordered = sel.in_paint_order(&st.doc); + let given: HashSet = ordered.iter().copied().collect(); // Drop ids nested inside other given ids. return Ok(ordered .iter() .copied() .filter(|id| { let anc = st.doc.ancestry(*id).unwrap_or_default(); - !anc[..anc.len().saturating_sub(1)].iter().any(|a| ordered.contains(a)) + !anc[..anc.len().saturating_sub(1)].iter().any(|a| given.contains(a)) }) .collect()); } @@ -37,20 +40,27 @@ pub(super) fn roots_param(s: &Session, p: &Value) -> Result> { /// dynamic symbol instance's art is selected. pub(super) fn selected_of(s: &Session, pred: fn(&Node) -> bool) -> Vec { let Some(st) = s.active().filter(|st| st.selection.symbol_part.is_none()) else { return vec![] }; + let mut find = st.doc.nearest_finder(); + let mut seen = HashSet::new(); let mut out = vec![]; for id in &st.selection.objects { - for a in st.doc.ancestry(*id).unwrap_or_default().into_iter().rev() { - if st.doc.node(a).is_some_and(pred) { - if !out.contains(&a) { - out.push(a); - } - break; - } + if let Some(n) = find.nearest(*id, pred) + && seen.insert(n.id) + { + out.push(n.id); } } out } +/// Whether some selected object's node of a kind ([`selected_of`]) passes `test`; stops at the +/// first one that does. +pub(super) fn any_selected_of(s: &Session, pred: fn(&Node) -> bool, test: impl Fn(&Node) -> bool) -> bool { + let Some(st) = s.active().filter(|st| st.selection.symbol_part.is_none()) else { return false }; + let mut find = st.doc.nearest_finder(); + st.selection.objects.iter().any(|id| find.nearest(*id, pred).is_some_and(&test)) +} + pub(super) fn is_blend(n: &Node) -> bool { matches!(n.kind, NodeKind::Blend { .. }) } @@ -66,19 +76,19 @@ pub(super) fn is_mesh(n: &Node) -> bool { pub(super) fn has_blend(s: &Session) -> std::result::Result<(), String> { has_selection(s)?; crate::cmd::edit::no_symbol_part(s)?; - if selected_of(s, is_blend).is_empty() { Err("select a blend".into()) } else { Ok(()) } + if any_selected_of(s, is_blend, |_| true) { Ok(()) } else { Err("select a blend".into()) } } pub(super) fn has_envelope(s: &Session) -> std::result::Result<(), String> { has_selection(s)?; crate::cmd::edit::no_symbol_part(s)?; - if selected_of(s, is_envelope).is_empty() { Err("select an envelope".into()) } else { Ok(()) } + if any_selected_of(s, is_envelope, |_| true) { Ok(()) } else { Err("select an envelope".into()) } } pub(super) fn has_mesh(s: &Session) -> std::result::Result<(), String> { has_selection(s)?; crate::cmd::edit::no_symbol_part(s)?; - if selected_of(s, is_mesh).is_empty() { Err("select a gradient mesh".into()) } else { Ok(()) } + if any_selected_of(s, is_mesh, |_| true) { Ok(()) } else { Err("select a gradient mesh".into()) } } /// Wrap `roots` (paint order) into a new node built by `make`, placed where the topmost root was. diff --git a/crates/engine/src/cmd/live/selected_tests.rs b/crates/engine/src/cmd/live/selected_tests.rs new file mode 100644 index 0000000000..b1250e2560 --- /dev/null +++ b/crates/engine/src/cmd/live/selected_tests.rs @@ -0,0 +1,324 @@ +//! The selected blend, envelope and mesh ([`selected_of`] and the checks built on it) are the ones +//! the lookup of every ancestor by id found: the same ids in the same order, the same availability +//! and errors, on selections with keys, nested blends, stale and repeated ids and a damaged tree. + +use std::sync::atomic::{AtomicUsize, Ordering}; + +use serde_json::json; +use vectorcraft_doc::{Node, NodeId, NodeKind, SymbolPart}; + +use super::Session; +use super::blend::any_without_spine; +use super::common::{any_selected_of, has_blend, has_envelope, has_mesh, is_blend, is_envelope, is_mesh, selected_of}; + +/// [`selected_of`] as each ancestor was looked up by id: `ancestry`, then `node` for each id from +/// the object up, repeats dropped by a scan of the list. +fn selected_of_by_ids(s: &Session, pred: fn(&Node) -> bool) -> Vec { + let Some(st) = s.active().filter(|st| st.selection.symbol_part.is_none()) else { return vec![] }; + let mut out = vec![]; + for id in &st.selection.objects { + for a in st.doc.ancestry(*id).unwrap_or_default().into_iter().rev() { + if st.doc.node(a).is_some_and(pred) { + if !out.contains(&a) { + out.push(a); + } + break; + } + } + } + out +} + +/// The availability [`has_blend`] and the others gave, from [`selected_of_by_ids`]. +fn has_by_ids(s: &Session, pred: fn(&Node) -> bool, msg: &str) -> std::result::Result<(), String> { + super::has_selection(s)?; + crate::cmd::edit::no_symbol_part(s)?; + if selected_of_by_ids(s, pred).is_empty() { Err(msg.into()) } else { Ok(()) } +} + +/// The no-spine check [`any_without_spine`] made, from [`selected_of_by_ids`]. +fn without_spine_by_ids(s: &Session) -> bool { + let Ok(st) = s.doc() else { return false }; + selected_of_by_ids(s, is_blend).iter().any(|b| matches!(st.doc.node(*b).map(|n| &n.kind), Some(NodeKind::Blend { spec, .. }) if spec.no_spine)) +} + +/// Every check on the current selection gives what the lookups by id gave. +fn agree(s: &Session, what: &str) { + type Has = fn(&Session) -> std::result::Result<(), String>; + for (name, pred, has, msg) in [ + ("blend", is_blend as fn(&Node) -> bool, has_blend as Has, "select a blend"), + ("envelope", is_envelope, has_envelope, "select an envelope"), + ("mesh", is_mesh, has_mesh, "select a gradient mesh"), + ] { + let want = selected_of_by_ids(s, pred); + assert_eq!(selected_of(s, pred), want, "{what}: selected {name}s"); + assert_eq!(any_selected_of(s, pred, |_| true), !want.is_empty(), "{what}: any {name}"); + assert_eq!(has(s), has_by_ids(s, pred, msg), "{what}: has {name}"); + } + assert_eq!(any_without_spine(s), without_spine_by_ids(s), "{what}: a blend without a spine"); +} + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap(); + s +} + +fn id_of(v: &serde_json::Value) -> NodeId { + NodeId(v["id"].as_u64().unwrap()) +} + +fn rect(s: &mut Session, x: f64) -> NodeId { + id_of(&s.execute("shape.rectangle", &json!({"x": x, "y": 10, "width": 20, "height": 20})).unwrap()) +} + +fn select(s: &mut Session, ids: &[NodeId]) { + s.execute("select.set", &json!({"ids": ids.iter().map(|i| i.0).collect::>()})).unwrap(); +} + +fn run(s: &mut Session, cmd: &str, ids: &[NodeId], p: serde_json::Value) -> NodeId { + select(s, ids); + id_of(&s.execute(cmd, &p).unwrap()) +} + +/// Every node id under the layers, parents before children (as Direct Selection can pick them). +fn all_ids(s: &Session) -> Vec { + fn walk(nodes: &[std::sync::Arc], out: &mut Vec) { + for n in nodes { + out.push(n.id); + if let Some(ch) = n.children() { + walk(ch, out); + } + } + } + let mut out = vec![]; + for l in &s.doc().unwrap().doc.layers { + walk(l.children().map_or(&[][..], |c| c.as_slice()), &mut out); + } + out +} + +/// The active document, to change in place. +fn doc_mut(s: &mut Session) -> &mut vectorcraft_doc::Document { + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc) +} + +/// Set the selection's objects as given, stale and repeated ids included. +fn set_objects(s: &mut Session, ids: Vec) { + s.doc_mut().unwrap().selection.objects = ids; +} + +/// Two blends, a blend in a key group of a third, an envelope and a mesh; one blend has no spine. +/// Returns the blends `a`, `b` and `c`, the group `g` of `c` that holds `a`, the envelope, and a key +/// of `a`. +fn document() -> (Session, [NodeId; 6]) { + let mut s = session(); + let r: Vec = (0..10).map(|i| rect(&mut s, 40.0 * i as f64)).collect(); + let a = run(&mut s, "object.blend.make", &[r[0], r[1]], json!({})); + let b = run(&mut s, "object.blend.make", &[r[2], r[3]], json!({})); + let g = run(&mut s, "object.group", &[a, r[4]], json!({})); + let c = run(&mut s, "object.blend.make", &[g, r[5]], json!({})); + let e = run(&mut s, "object.envelope.makeWithWarp", &[r[6]], json!({"style": "arch", "bend": 50})); + select(&mut s, &[r[7]]); + s.execute("object.mesh.create", &json!({"ids": [r[7].0], "rows": 1, "cols": 1})).unwrap(); + if let Some(NodeKind::Blend { spec, .. }) = doc_mut(&mut s).node_mut(b).map(|n| &mut n.kind) { + spec.no_spine = true; + } + (s, [a, b, c, g, e, r[0]]) +} + +#[test] +fn selected_blends_envelopes_and_meshes_match_the_lookups_by_id() { + let (mut s, [a, b, c, g, e, inner_key]) = document(); + s.execute("select.all", &json!({})).unwrap(); + agree(&s, "select all"); + let all = all_ids(&s); + let keys: Vec = all.iter().copied().filter(|id| ![a, b, c, g, e].contains(id)).collect(); + set_objects(&mut s, keys.clone()); + agree(&s, "keys, as Direct Selection picks them"); + set_objects(&mut s, all.iter().rev().copied().collect()); + agree(&s, "every node, children first"); + set_objects(&mut s, vec![a, keys[0], b, keys[1], keys[0], NodeId(999_999), a]); + agree(&s, "repeated and stale ids, in first-seen order"); + assert_eq!(selected_of(&s, is_blend), vec![a, b], "the blend with no spine is listed once, in order"); + set_objects(&mut s, vec![NodeId(999_999)]); + agree(&s, "only a stale id"); + set_objects(&mut s, vec![]); + agree(&s, "nothing"); + // A blend in another blend's key group: the inner one. + set_objects(&mut s, vec![inner_key]); + agree(&s, "a key of a blend nested in another's key group"); + assert_eq!(selected_of(&s, is_blend), vec![a]); + // An object of a dynamic symbol instance's art: nothing. + set_objects(&mut s, all.clone()); + s.doc_mut().unwrap().selection.symbol_part = Some(SymbolPart { instance: a, path: vec![0] }); + agree(&s, "a symbol part"); + assert!(selected_of(&s, is_blend).is_empty()); +} + +/// A damaged tree: an earlier node of another kind with the id of a blend on the selected key's +/// path. `node` gives the earlier node, so that blend does not count, before and after the cache is +/// built again. +#[test] +fn a_repeated_id_counts_as_its_first_node() { + let (mut s, [a, _, c, _, _, inner_key]) = document(); + let all = all_ids(&s); + s.doc().unwrap().doc.node(a); + let doc = doc_mut(&mut s); + if let Some(ch) = std::sync::Arc::make_mut(&mut doc.layers[0]).children_mut() { + ch.insert(0, std::sync::Arc::new(Node::group(a, vec![]))); + } + set_objects(&mut s, all.clone()); + agree(&s, "a repeated id, the cache older than the tree"); + s.doc().unwrap().doc.drop_lookup_cache(); + agree(&s, "a repeated id, no cache"); + s.doc().unwrap().doc.node(a); + agree(&s, "a repeated id, cached afresh"); + set_objects(&mut s, vec![inner_key]); + assert_eq!(selected_of(&s, is_blend), vec![c], "the nested blend's id is the group's, so the outer blend counts"); +} + +/// Large selections: with the lookup cache built, finding the selected blends looks no id up, and +/// the checks stop at the first selected object that has one. +#[test] +fn selected_blends_take_no_lookups_by_id() { + let mut s = session(); + let mut keys = vec![]; + for i in 0..300 { + let (x, y) = (rect(&mut s, i as f64), rect(&mut s, i as f64 + 30.0)); + run(&mut s, "object.blend.make", &[x, y], json!({})); + keys.extend([x, y]); + } + for i in 0..1_000 { + rect(&mut s, i as f64); + } + s.execute("select.all", &json!({})).unwrap(); + s.doc().unwrap().doc.drop_lookup_cache(); + s.doc().unwrap().doc.node(keys[0]); + let before = vectorcraft_doc::path_lookups(); + assert_eq!(selected_of(&s, is_blend).len(), 300); + assert!(!any_selected_of(&s, is_mesh, |_| true)); + set_objects(&mut s, keys.clone()); + assert_eq!(selected_of(&s, is_blend).len(), 300, "each blend once from its two keys"); + assert_eq!(vectorcraft_doc::path_lookups() - before, 0, "lookups by id"); + // The first key is in a blend: the check tests that key and its blend only. + static TESTED: AtomicUsize = AtomicUsize::new(0); + fn counted(n: &Node) -> bool { + TESTED.fetch_add(1, Ordering::Relaxed); + is_blend(n) + } + assert!(any_selected_of(&s, counted, |_| true)); + assert_eq!(TESTED.load(Ordering::Relaxed), 2, "nodes tested"); +} + +/// `n` and everything under it with new ids. +fn renumber(d: &mut vectorcraft_doc::Document, n: &Node) -> Node { + let mut n = n.clone(); + n.id = d.alloc_id(); + if let Some(ch) = n.children_mut() { + for c in ch.iter_mut() { + *c = std::sync::Arc::new(renumber(d, c)); + } + } + n +} + +/// This thread's CPU time in nanoseconds, where the system reports it (Linux). +fn cpu_ns() -> Option { + std::fs::read_to_string("/proc/thread-self/schedstat").ok()?.split_whitespace().next()?.parse().ok() +} + +/// Milliseconds one call of `f` takes over `calls` calls, in CPU time where the system reports it, +/// otherwise in wall-clock time. +fn ms_per_call(calls: u32, f: &dyn Fn()) -> f64 { + let (cpu, wall) = (cpu_ns(), std::time::Instant::now()); + for _ in 0..calls { + f(); + } + let ms = match (cpu, cpu_ns()) { + (Some(a), Some(b)) => b.saturating_sub(a) as f64 / 1e6, + _ => wall.elapsed().as_secs_f64() * 1e3, + }; + ms / f64::from(calls) +} + +/// The medians of 7 runs of `a` and of `b`, the runs taking turns. +fn medians(calls: u32, a: &dyn Fn(), b: &dyn Fn()) -> (f64, f64) { + let (mut ta, mut tb) = (vec![], vec![]); + for _ in 0..7 { + ta.push(ms_per_call(calls, a)); + tb.push(ms_per_call(calls, b)); + } + ta.sort_by(f64::total_cmp); + tb.sort_by(f64::total_cmp); + (ta[3], tb[3]) +} + +/// Timings of the lookups by id and of the one-path lookup on 100,000 rectangles in 10 layers, +/// 2,000 two-key blends (every fourth one in a group) and 200 envelopes, all selected. Run with +/// `cargo test --release -p vectorcraft-engine --lib selected_tests::timing -- --ignored --nocapture`. +#[test] +#[ignore = "timing; run by hand"] +fn timing_of_the_selected_blend_checks() { + let mut s = session(); + let (a, b, c) = (rect(&mut s, 0.0), rect(&mut s, 40.0), rect(&mut s, 80.0)); + let square = rect(&mut s, 120.0); + let blend = run(&mut s, "object.blend.make", &[a, b], json!({})); + let envelope = run(&mut s, "object.envelope.makeWithWarp", &[c], json!({"style": "arch", "bend": 50})); + let doc = doc_mut(&mut s); + let templates: Vec = [square, blend, envelope].iter().map(|id| doc.node(*id).cloned().unwrap()).collect(); + let mut layers = vec![]; + for l in 0..10 { + let mut layer = Node::layer(doc.alloc_id(), &format!("Layer {l}"), vectorcraft_doc::LayerColor::Preset(0)); + let mut kids = vec![]; + for _ in 0..10_000 { + kids.push(std::sync::Arc::new(renumber(doc, &templates[0]))); + } + for i in 0..200 { + let b = renumber(doc, &templates[1]); + let b = if i % 4 == 0 { Node::group(doc.alloc_id(), vec![std::sync::Arc::new(b)]) } else { b }; + kids.push(std::sync::Arc::new(b)); + } + for _ in 0..20 { + kids.push(std::sync::Arc::new(renumber(doc, &templates[2]))); + } + if let Some(ch) = layer.children_mut() { + *ch = kids; + } + layers.push(std::sync::Arc::new(layer)); + } + doc.layers = layers; + s.execute("select.all", &json!({})).unwrap(); + let first = s.doc().unwrap().selection.objects[0]; + s.doc().unwrap().doc.drop_lookup_cache(); + s.doc().unwrap().doc.node(first); + println!("{} objects selected", s.doc().unwrap().selection.objects.len()); + type Check = fn(&Session) -> bool; + let checks: [(&str, Check, Check); 5] = [ + ("has_blend", |s| has_by_ids(s, is_blend, "").is_ok(), |s| has_blend(s).is_ok()), + ("has_envelope", |s| has_by_ids(s, is_envelope, "").is_ok(), |s| has_envelope(s).is_ok()), + ("has_mesh", |s| has_by_ids(s, is_mesh, "").is_ok(), |s| has_mesh(s).is_ok()), + ( + "selected blends (object.blend.info and the Blend commands)", + |s| !selected_of_by_ids(s, is_blend).is_empty(), + |s| !selected_of(s, is_blend).is_empty(), + ), + ("a blend without a spine (Reverse Spine, the Blend panel)", without_spine_by_ids, any_without_spine), + ]; + assert_eq!(selected_of(&s, is_blend), selected_of_by_ids(&s, is_blend)); + println!("| Check | Lookups by id (ms) | One path (ms) |"); + println!("|---|---:|---:|"); + for (name, by_ids, one_path) in checks { + assert_eq!(by_ids(&s), one_path(&s), "{name}"); + let (old, new) = medians( + 15, + &|| { + std::hint::black_box(by_ids(&s)); + }, + &|| { + std::hint::black_box(one_path(&s)); + }, + ); + println!("| {name} | {old:.3} | {new:.3} |"); + } +} diff --git a/crates/engine/src/cmd/object.rs b/crates/engine/src/cmd/object.rs index a58f206c84..fd0aece164 100644 --- a/crates/engine/src/cmd/object.rs +++ b/crates/engine/src/cmd/object.rs @@ -42,3 +42,4 @@ pub(crate) use pixelgrid::{ }; pub(super) use shape::recut; pub(crate) use transform::{apply_transform, preview_copies, scaling, transform_node, transform_patterns, transforms_objects}; +pub use transform::{reflect_axis, scale_factors, shear_tangent}; diff --git a/crates/engine/src/cmd/object/bounds.rs b/crates/engine/src/cmd/object/bounds.rs index cf0473f353..a24e71c9a6 100644 --- a/crates/engine/src/cmd/object/bounds.rs +++ b/crates/engine/src/cmd/object/bounds.rs @@ -59,7 +59,7 @@ fn bounds_transform(s: &Session, p: &Value, ids: Vec, least: f64, anchor let refi = reference_index(p)?; let st = s.doc()?; check_switches(p, &TRANSFORM_SWITCHES, "object.setBounds")?; - check_switches(p, &["proportional"], "object.setBounds")?; + check_switches(p, &["proportional", "interpolate"], "object.setBounds")?; let how = s.bounds_measure(); if anchors && transforms_objects(p) diff --git a/crates/engine/src/cmd/object/commands.rs b/crates/engine/src/cmd/object/commands.rs index 41902d7420..4be83d7da6 100644 --- a/crates/engine/src/cmd/object/commands.rs +++ b/crates/engine/src/cmd/object/commands.rs @@ -16,7 +16,7 @@ pub fn specs() -> Vec { "Transform", [], None, - "{matrix: [a,b,c,d,e,f], copy?: bool, ids?, strokes?: bool, corners?: bool, typeAreas?: bool, anchors?: bool, objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), releaseOutside?: bool} apply an affine to the selection (or ids); anchors (without ids or copy): paths with anchors selected with Direct Selection have only those anchors and their handles transformed, as the Transform tools and object.move/rotate/scale/reflect/shear do (default: the whole objects); strokes/corners: Scale Strokes & Effects / Scale Corners (default: the preferences); typeAreas: area type among them (not type inside a group) reshapes its frame by the matrix and its text reflows at its size, as a bounding-box handle drag does (default: the type transforms too); releaseOutside (without copy or anchors): a Shaper Group's original shape that ends wholly outside the bounds the group's original shapes had before takes shaper.releaseSource in the same undo step, named Remove from Shaper Group, as the Selection tool's moves in Construction mode do", + "{matrix: [a,b,c,d,e,f], copy?: bool, ids?, strokes?: bool, corners?: bool, typeAreas?: bool, anchors?: bool, objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), releaseOutside?: bool, interpolate?: bool (with anchors and a matrix that only moves them: the handles of each segment with one moved end are re-mapped, as path.moveAnchors's; default: prefs interpolateControlPoints)} apply an affine to the selection (or ids); anchors (without ids or copy): paths with anchors selected with Direct Selection have only those anchors and their handles transformed, as the Transform tools and object.move/rotate/scale/reflect/shear do (default: the whole objects); strokes/corners: Scale Strokes & Effects / Scale Corners (default: the preferences); typeAreas: area type among them (not type inside a group) reshapes its frame by the matrix and its text reflows at its size, as a bounding-box handle drag does (default: the type transforms too); releaseOutside (without copy or anchors): a Shaper Group's original shape that ends wholly outside the bounds the group's original shapes had before takes shaper.releaseSource in the same undo step, named Remove from Shaper Group, as the Selection tool's moves in Construction mode do", has_doc, transform ), @@ -25,7 +25,7 @@ pub fn specs() -> Vec { "Move…", ["Object", "Transform"], Some("Cmd+Shift+M"), - "{ids?: [id…] (selected first; default: the selection), dx, dy, copy?, objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size)}. With anchors selected with Direct Selection (and no copy), only those anchors and their handles transform, about the centre of their own box.", + "{ids?: [id…] (selected first; default: the selection), dx, dy, copy?, objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size), interpolate?: bool (as path.moveAnchors's; default: prefs interpolateControlPoints)}. With anchors selected with Direct Selection (and no copy), only those anchors and their handles transform, about the centre of their own box.", has_selection_or_guides, move_cmd ), @@ -61,7 +61,7 @@ pub fn specs() -> Vec { "Shear…", ["Object", "Transform"], None, - "{ids?: [id…] (selected first; default: the selection), angle: deg (positive turns the vertical edges clockwise with the horizontal axis, the top to the right; the horizontal edges clockwise with the vertical axis, the right side down), axis?: \"horizontal\"|\"vertical\", origin?, copy?, objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size)}. With anchors selected with Direct Selection (and no copy), only those anchors and their handles transform, about the centre of their own box.", + "{ids?: [id…] (selected first; default: the selection), angle: deg (-359 to 359, sheared by its tangent, so 120 slants as -60; 0 and ±180 have no slant and, without copy, change nothing; ±90 and ±270 are an error; positive turns the vertical edges clockwise with the horizontal axis, the top to the right; the horizontal edges clockwise with the vertical axis, the right side down), axis?: \"horizontal\"|\"vertical\"|deg (the line the art slides along, counter-clockwise from horizontal on the page, -359 to 359; 0: horizontal, 90: vertical; omitted: horizontal), origin?, copy?, objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size)}. With anchors selected with Direct Selection (and no copy), only those anchors and their handles transform, about the centre of their own box.", has_selection, shear ), @@ -70,7 +70,7 @@ pub fn specs() -> Vec { "Transform Again", ["Object", "Transform"], Some("Cmd+D"), - "{copy?, strokes?, corners?, patterns?, typeAreas?: bool (as object.transform's; default: the value the transform it repeats used, else object.transform's default)} the last transform's matrix on the selection (after a perspective move or scale: that plane-space transform, without these params)", + "{copy?, strokes?, corners?, patterns?, typeAreas?, interpolate?: bool (as object.transform's; default: the value the transform it repeats used, else object.transform's default)} the last transform's matrix on the selection (after a perspective move or scale: that plane-space transform, without these params)", has_selection, transform_again ), @@ -79,7 +79,7 @@ pub fn specs() -> Vec { "Nudge", [], None, - "{dx: -1|0|1, dy: -1|0|1, big?: bool (×10), copy?: bool, patterns?: bool (Transform Patterns: pattern fills and strokes transform with the objects that move whole; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size), objects?: bool (Transform Objects, as object.move)} arrow-key nudge by the keyboard increment (the selected anchors, else objects, along the x and y axes turned by the constrainAngle preference; else ruler guides, along the page axes)", + "{dx: -1|0|1, dy: -1|0|1, big?: bool (×10), copy?: bool, patterns?: bool (Transform Patterns: pattern fills and strokes transform with the objects that move whole; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size), objects?: bool (Transform Objects, as object.move), interpolate?: bool (as path.moveAnchors's; default: prefs interpolateControlPoints)} arrow-key nudge by the keyboard increment (the selected anchors, else objects, along the x and y axes turned by the constrainAngle preference; else ruler guides, along the page axes)", has_selection_or_guides, nudge ), @@ -295,7 +295,7 @@ pub fn specs() -> Vec { "Set Bounds", [], None, - "{x?, y?, width?, height?, reference?: whole number >= 0 (9-point grid 0..8; 0.0 equals 0; a whole number past 8 is read as 8; omitted/null: center, 4), proportional?, strokes?, corners?, copy?: bool, patterns?: bool (Transform Patterns), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size), objects?: bool (Transform Objects, as object.move)} (Transform panel; width/height and the reference point follow the bounding box, rotated with rotated objects; x, y are page coordinates; with Use Preview Bounds the values measure the visual bounds; with the typeGlyphBounds preference, each point type object selected as an object (not inside a selected group) is measured by its glyphs' ink (underline and strikethrough included), which the scale gives the size asked for; strokes/corners as object.scale; with anchor points selected (Direct Selection) and no copy, the values are the box around those points, square to the page, and only they move or scale, as with object.move (#1824))", + "{x?, y?, width?, height?, reference?: whole number >= 0 (9-point grid 0..8; 0.0 equals 0; a whole number past 8 is read as 8; omitted/null: center, 4), proportional?, strokes?, corners?, copy?: bool, patterns?: bool (Transform Patterns), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size), objects?: bool (Transform Objects, as object.move), interpolate?: bool (with anchor points selected and only x or y changed: as path.moveAnchors's; default: prefs interpolateControlPoints)} (Transform panel; width/height and the reference point follow the bounding box, rotated with rotated objects; x, y are page coordinates; with Use Preview Bounds the values measure the visual bounds; with the typeGlyphBounds preference, each point type object selected as an object (not inside a selected group) is measured by its glyphs' ink (underline and strikethrough included), which the scale gives the size asked for; strokes/corners as object.scale; with anchor points selected (Direct Selection) and no copy, the values are the box around those points, square to the page, and only they move or scale, as with object.move (#1824))", has_selection, set_bounds ), @@ -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), 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)} (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…], 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)} (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 053cc3b36d..02edf6193b 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, &["invertPie", "makeSidesEqual", "relativeRadii"], "object.setLiveShape")?; + check_switches(p, &["constrainPie", "invertPie", "makeSidesEqual", "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()) { @@ -193,6 +193,12 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result { // An ellipse's pie (Ellipse Properties: Pie Start and End Angle, degrees; Invert Pie swaps them). let (pie_start, pie_end) = (angle("pieStart")?, angle("pieEnd")?); let invert = p.get("invertPie").and_then(Value::as_bool) == Some(true); + // Constrain Pie Angle: the one angle given moves the other by as much, so each ellipse keeps + // its span (its end angle less its start angle, counterclockwise). + let constrain = p.get("constrainPie").and_then(Value::as_bool) == Some(true); + if constrain && (invert || pie_start.is_some() == pie_end.is_some()) { + return Err(bad("object.setLiveShape", "`constrainPie` needs one of `pieStart` and `pieEnd`, without `invertPie`")); + } // A polygon's Polygon Properties: its angle, radius or side length, Make Sides Equal. let (polygon_angle, polygon_radius, side) = (angle("polygonAngle")?, length("polygonRadius")?, length("sideLength")?); let equal = p.get("makeSidesEqual").and_then(Value::as_bool) == Some(true); @@ -204,7 +210,16 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result { // ellipse as 0° to 360°). let end_of = |a: f64| if a == 0.0 { 360.0 } else { a }; let pie_of = |pie: (f64, f64)| { - let pie = (pie_start.unwrap_or(pie.0), pie_end.map_or(pie.1, end_of)); + let span = (pie.1 - pie.0).rem_euclid(360.0); + let pie = match (constrain, pie_start, pie_end) { + // The angle it already has: nothing moves. + (true, Some(a), _) if a == pie.0 => pie, + (true, _, Some(a)) if end_of(a) == pie.1 => pie, + // A whole ellipse (a span of 0) stays whole. + (true, Some(a), _) => (a, end_of((a + span).rem_euclid(360.0))), + (true, _, Some(a)) => ((a - span).rem_euclid(360.0), end_of(a)), + _ => (pie_start.unwrap_or(pie.0), pie_end.map_or(pie.1, end_of)), + }; if invert { (pie.1.rem_euclid(360.0), end_of(pie.0)) } else { pie } }; // When every value given is the current one, the document and its undo history stay as they diff --git a/crates/engine/src/cmd/object/transform.rs b/crates/engine/src/cmd/object/transform.rs index 25a831622e..7b1a97b4b3 100644 --- a/crates/engine/src/cmd/object/transform.rs +++ b/crates/engine/src/cmd/object/transform.rs @@ -125,9 +125,14 @@ fn apply_transform_moving_guides( let d = &s.doc()?.doc; let paths = d.index_paths(ids.iter().copied()); let none = paths.is_empty() && !has_guides; + // A move of direct-selected anchors may re-map the handles beside them (`interpolate`). + let mut interpolate = None; let ids = if anchors && objects && !copy && !s.doc()?.selection.anchors.is_empty() { + if c[..4] == [1.0, 0.0, 0.0, 1.0] { + interpolate = Some(crate::cmd::path::interpolates_handles(s, p, label)?); + } if xf != Affine::IDENTITY { - crate::cmd::path::transform_anchors(s, label, xf, sc)?; + crate::cmd::path::transform_anchors(s, label, xf, sc, interpolate.unwrap_or(false))?; } ids } else if none || (!copy && xf == Affine::IDENTITY) { @@ -195,6 +200,9 @@ fn apply_transform_moving_guides( options["strokes"] = json!(sc.strokes); options["corners"] = json!(!sc.keep_corners); } + if let Some(on) = interpolate { + options["interpolate"] = json!(on); + } st.last_transform = Some(LastTransform::Matrix(xf, options)); st.last_perspective = None; } @@ -248,7 +256,7 @@ fn resize_type_area(n: &mut Node, xf: Affine) -> bool { pub(super) fn transform(s: &mut Session, p: &Value) -> Result { check_switches(p, &TRANSFORM_SWITCHES, "object.transform")?; - check_switches(p, &["anchors", "releaseOutside"], "object.transform")?; + check_switches(p, &["anchors", "releaseOutside", "interpolate"], "object.transform")?; let m = matrix_param(p, "matrix").ok_or_else(|| bad("object.transform", "missing matrix [a,b,c,d,e,f]"))?; // An object selected in a symbol instance's art stays where the symbol puts it: the selection // is left as it is, and the reply's warning goes to the status bar. @@ -292,6 +300,7 @@ pub(super) fn transform(s: &mut Session, p: &Value) -> Result { pub(super) fn move_cmd(s: &mut Session, p: &Value) -> Result { check_numbers(p, &["dx", "dy"], "object.move")?; check_switches(p, &TRANSFORM_SWITCHES, "object.move")?; + check_switches(p, &["interpolate"], "object.move")?; let ids = selected_roots_to_transform(s)?; apply_transform(s, "Move", ids, Affine::translate((f64_or(p, "dx", 0.0), f64_or(p, "dy", 0.0))), p, true) } @@ -311,7 +320,7 @@ pub(crate) fn along_constrain_angle(dx: f64, dy: f64, deg: f64) -> (f64, f64) { pub(super) fn nudge(s: &mut Session, p: &Value) -> Result { check_numbers(p, &["dx", "dy"], "object.nudge")?; check_switches(p, &TRANSFORM_SWITCHES, "object.nudge")?; - check_switches(p, &["big"], "object.nudge")?; + check_switches(p, &["big", "interpolate"], "object.nudge")?; let k = s.prefs.keyboard_increment * if bool_or(p, "big", false) { 10.0 } else { 1.0 }; let (dx, dy) = (f64_or(p, "dx", 0.0) * k, f64_or(p, "dy", 0.0) * k); // Guides keep to the page's axes; art and anchors move along the constrain angle's. @@ -322,7 +331,7 @@ pub(super) fn nudge(s: &mut Session, p: &Value) -> Result { if dx == 0.0 && dy == 0.0 { return ok(); } - return crate::cmd::path::move_anchors(s, &json!({ "dx": dx, "dy": dy, "patterns": p.get("patterns") })); + return crate::cmd::path::move_anchors(s, &json!({ "dx": dx, "dy": dy, "patterns": p.get("patterns"), "interpolate": p.get("interpolate") })); } if s.doc()?.selection.is_empty() { let copy = bool_or(p, "copy", false); @@ -360,15 +369,22 @@ pub(super) fn scale(s: &mut Session, p: &Value) -> Result { check_switches(p, &TRANSFORM_SWITCHES, "object.scale")?; let ids = selected_roots_to_transform(s)?; let o = origin_of(s, p, &ids)?; - let sx = f64_req(p, "sx", "object.scale")? / 100.0; - let sy = f64_or(p, "sy", sx * 100.0) / 100.0; - if sx == 0.0 || sy == 0.0 { - return Err(bad("object.scale", "scale must be non-zero")); - } + let sx = f64_req(p, "sx", "object.scale")?; + let (sx, sy) = scale_factors(sx, f64_or(p, "sy", sx)).map_err(|e| bad("object.scale", e))?; let frame = basis_frame(s, p, "object.scale", &ids)?; apply_transform(s, "Scale", ids, about(o, frame.conjugate(Affine::scale_non_uniform(sx, sy))), p, true) } +/// The factors `object.scale` applies for `sx` and `sy` in percent, or the error it returns when +/// either factor is 0. +pub fn scale_factors(sx: f64, sy: f64) -> std::result::Result<(f64, f64), String> { + let (sx, sy) = (sx / 100.0, sy / 100.0); + if sx == 0.0 || sy == 0.0 { + return Err("scale must be non-zero".into()); + } + Ok((sx, sy)) +} + /// The frame that `object.scale` and a named `object.reflect` act in, from the `basis` param: /// `"box"` (the default) is the bounding box of `ids`, turned with rotated objects until Reset /// Bounding Box ([`Document::bbox_angle`]); `"page"` is the page's axes. Anchors selected with @@ -393,16 +409,7 @@ pub(super) fn reflect(s: &mut Session, p: &Value) -> Result { let ids = selected_roots_to_transform(s)?; let o = origin_of(s, p, &ids)?; // A named axis is the bounding box's own (see [`basis_frame`]); an angle is a line on the page. - let named = match p.get("axis") { - Some(Value::String(a)) if a == "horizontal" => Some(Affine::scale_non_uniform(1.0, -1.0)), - Some(Value::Number(_)) => None, - None | Some(Value::Null) => Some(Affine::scale_non_uniform(-1.0, 1.0)), - Some(Value::String(a)) if a == "vertical" => Some(Affine::scale_non_uniform(-1.0, 1.0)), - Some(v) => { - let given = v.as_str().map_or_else(|| v.to_string(), str::to_string); - return Err(bad("object.reflect", format!("axis must be \"vertical\", \"horizontal\" or an angle in degrees, not `{given}`"))); - } - }; + let named = reflect_axis(p.get("axis")).map_err(|e| bad("object.reflect", e))?; let m = match named { Some(m) => basis_frame(s, p, "object.reflect", &ids)?.conjugate(m), None => { @@ -414,22 +421,76 @@ pub(super) fn reflect(s: &mut Session, p: &Value) -> Result { apply_transform(s, "Reflect", ids, about(o, m), p, true) } +/// The reflection `object.reflect` applies for its `axis` param: the matrix for a named axis +/// (`"vertical"`, the default, or `"horizontal"`), in the bounding box's frame; `None` for an angle, +/// which is a line on the page; or the error for any other value. +pub fn reflect_axis(axis: Option<&Value>) -> std::result::Result, String> { + match axis { + Some(Value::String(a)) if a == "horizontal" => Ok(Some(Affine::scale_non_uniform(1.0, -1.0))), + Some(Value::Number(_)) => Ok(None), + None | Some(Value::Null) => Ok(Some(Affine::scale_non_uniform(-1.0, 1.0))), + Some(Value::String(a)) if a == "vertical" => Ok(Some(Affine::scale_non_uniform(-1.0, 1.0))), + Some(v) => { + let given = v.as_str().map_or_else(|| v.to_string(), str::to_string); + Err(format!("axis must be \"vertical\", \"horizontal\" or an angle in degrees, not `{given}`")) + } + } +} + +/// Angles closer than this many degrees to ±90 or ±270, or to 0 or ±180, count as those angles. It +/// is far above the rounding error of an angle up to 359° and below any angle a field shows. +const SHEAR_ANGLE_TOLERANCE: f64 = 1e-9; + +/// The slant `object.shear` applies for `angle` in degrees: its tangent, and 0 for 0 and ±180. An +/// angle outside -359 to 359, or ±90 or ±270, is an error. +pub fn shear_tangent(angle: f64) -> std::result::Result { + if !(-359.0..=359.0).contains(&angle) { + return Err(format!("`angle` must be from -359 to 359 degrees, not {angle}")); + } + // ±90 and ±270 slant an edge onto the shear axis: their tangent is unbounded. + let flat = angle.rem_euclid(180.0); + if (flat - 90.0).abs() < SHEAR_ANGLE_TOLERANCE { + return Err(format!("`angle` cannot be {angle}: ±90 and ±270 degrees have no shear")); + } + // 0 and ±180 have no slant, but the tangent of ±180° in radians is about 1e-16, not 0. + Ok(if flat < SHEAR_ANGLE_TOLERANCE || 180.0 - flat < SHEAR_ANGLE_TOLERANCE { 0.0 } else { angle.to_radians().tan() }) +} + pub(super) fn shear(s: &mut Session, p: &Value) -> Result { check_numbers(p, &["angle"], "object.shear")?; check_switches(p, &TRANSFORM_SWITCHES, "object.shear")?; + let t = shear_tangent(f64_or(p, "angle", 0.0)).map_err(|e| bad("object.shear", e))?; let ids = selected_roots_to_transform(s)?; let o = origin_of(s, p, &ids)?; - let t = f64_or(p, "angle", 0.0).clamp(-89.0, 89.0).to_radians().tan(); - let vertical = choice(p, "object.shear", "axis", &["horizontal", "vertical"])? == Some("vertical"); - let m = if vertical { Affine::new([1.0, t, 0.0, 1.0, 0.0, 0.0]) } else { Affine::new([1.0, 0.0, -t, 1.0, 0.0, 0.0]) }; + let horizontal = Affine::new([1.0, 0.0, -t, 1.0, 0.0, 0.0]); + // A named axis, or a line on the page at an angle in degrees, counter-clockwise from horizontal. + let m = match p.get("axis") { + None | Some(Value::Null) => horizontal, + Some(Value::String(a)) if a == "horizontal" => horizontal, + Some(Value::String(a)) if a == "vertical" => Affine::new([1.0, t, 0.0, 1.0, 0.0, 0.0]), + Some(Value::Number(n)) if n.as_f64().is_some_and(|a| (-SHEAR_AXIS_MAX..=SHEAR_AXIS_MAX).contains(&a)) => { + // y is down, so the page's counter-clockwise angle turns the other way on screen. + let r = -n.as_f64().unwrap_or(0.0).to_radians(); + Affine::rotate(r) * horizontal * Affine::rotate(-r) + } + Some(v) => { + let given = v.as_str().map_or_else(|| v.to_string(), str::to_string); + let range = format!("from -{SHEAR_AXIS_MAX} to {SHEAR_AXIS_MAX}"); + return Err(bad("object.shear", format!("axis must be \"horizontal\", \"vertical\" or an angle in degrees {range}, not `{given}`"))); + } + }; apply_transform(s, "Shear", ids, about(o, m), p, true) } +/// The largest angle, either way from horizontal, of the axis `object.shear` takes in degrees. +const SHEAR_AXIS_MAX: f64 = 359.0; + /// The last transform on the selection, with the options `last_transform` keeps for it; an option /// that `p` sets to true or false (a recorded Transform Again's) takes precedence. A Transform /// Each is repeated by running it again (its transform is per object, about each one's bounds). pub(super) fn transform_again(s: &mut Session, p: &Value) -> Result { check_switches(p, &TRANSFORM_SWITCHES, "object.transformAgain")?; + check_switches(p, &["interpolate"], "object.transformAgain")?; if let Some(again) = s.doc()?.last_perspective.clone() { return crate::cmd::distortcmds::transform_again(s, &again); } diff --git a/crates/engine/src/cmd/package.rs b/crates/engine/src/cmd/package.rs index 04c0d2ba51..e959f126c0 100644 --- a/crates/engine/src/cmd/package.rs +++ b/crates/engine/src/cmd/package.rs @@ -24,7 +24,7 @@ pub fn specs() -> Vec { "Package", [], None, - "{folder?, name?: (default: \" Folder\"), copyLinks?: true, linksFolder?: true (the linked files go in Links/, else next to the document), relink?: true (the packaged document links to the copies), copyFonts?: true (the fonts its type uses go in Fonts/; fonts whose licence doesn't allow embedding are left out), report?: true ( Report.txt)} copy the saved document as it is now into folder/name as .vectorcraft with its linked files and fonts; the open document doesn't change → {folder, files: [paths relative to folder/name], links, fonts (counts copied), missingLinks: [file names not found], skippedFonts: [{font, reason}], warnings: [nested files copied unchanged or cycles/depth stopped]}; no folder → the same with {name: \".zip\", dataBase64} (a zip of the files in /) instead of folder. The warnings and the report name a file outside the automation read roots by its file name. Under automation read roots, the package is refused, before any file is written, while the document, or a linked native document or a linked PDF, .ai or EPS file's native document, links a JavaScript file outside them (svgInteractivity; a URL is not checked)", + "{folder?, name?: (default: \" Folder\"), copyLinks?: true, linksFolder?: true (the linked files go in Links/, else next to the document), relink?: true (the packaged document links to the copies), copyFonts?: true (the fonts its type uses go in Fonts/; fonts whose licence doesn't allow embedding are left out), report?: true ( Report.txt)} copy the saved document as it is now into folder/name as .vectorcraft with its linked files and fonts; the open document doesn't change → {folder, files: [paths relative to folder/name], links, fonts (counts copied), missingLinks: [file names not found], skippedFonts: [{font, reason}], warnings: [nested files copied unchanged or cycles/depth stopped]}; no folder → the same with {name: \".zip\", dataBase64} (a zip of the files in /) instead of folder. The warnings and the report name a file outside the automation read roots by its file name. Under automation read roots, the package is refused, before any file is written, while the document, or a linked native document or a linked PDF, .ai or EPS file's native document, links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while a linked native document, or a linked PDF, .ai or EPS file that carries one, can't be read to check it (a damaged file, or a PDF that needs a password to open); a PDF or EPS file without editing data is copied", has_doc, package )] @@ -113,27 +113,65 @@ thread_local! { pub(crate) static PARTS_READ: std::cell::Cell = const { std::cell::Cell::new(0) }; } -/// The native document that the linked file `name` (`bytes`) is, or carries as the editing data of -/// a PDF, `.ai` or EPS file; `None` for other files and for data that can't be read. -fn carried_document(name: &str, bytes: &[u8]) -> Option { - if super::place::document::is_native(name, bytes) { - return vectorcraft_format::load_file(bytes).ok().map(|f| f.doc); - } - let data = - if super::place::document::is_pdf(name, bytes) { vectorcraft_pdf::editing(bytes).map(|e| e.data) } else { vectorcraft_eps::native(bytes) }; - vectorcraft_format::load(&data?).ok() +/// The native document a linked file is or carries ([`carried_document`]). +enum Carried { + /// The file is no native document and carries none: an image, or a PDF, `.ai` or EPS file + /// without editing data. + Absent, + /// The native document, read. + Readable(Box), + /// The file is a native document, or carries one, that can't be read: a damaged native file, + /// a PDF or `.ai` file that can't be opened without a password or can't be read at all, a PDF + /// or `.ai` file listing an editing file whose data can't be resolved, a PDF or `.ai` file + /// whose attachments are too many to search to their end, or editing data that doesn't read as + /// a native document. + Unreadable, } +/// The native document that the linked file `name` (`bytes`) is, or carries as the editing data of +/// a PDF, `.ai` or EPS file. +fn carried_document(name: &str, bytes: &[u8]) -> Carried { + let read = |data: &[u8]| vectorcraft_format::load(data).map_or(Carried::Unreadable, |d| Carried::Readable(Box::new(d))); + if super::place::document::is_native(name, bytes) { + return vectorcraft_format::load_file(bytes).map_or(Carried::Unreadable, |f| Carried::Readable(Box::new(f.doc))); + } + if super::place::document::is_pdf(name, bytes) { + // A PDF that can't be opened may carry editing data all the same. + return match vectorcraft_pdf::open_pdf(bytes, None) { + // Attachments left unsearched may list another editing file, which can't be checked. + Ok(opened) if opened.editing_search_cut() => Carried::Unreadable, + // An editing file listed whose data can't be resolved can't be checked either. + Ok(opened) => match opened.editing() { + Some(e) => read(&e.data), + None if opened.has_editing_file() => Carried::Unreadable, + None => Carried::Absent, + }, + Err(_) => Carried::Unreadable, + }; + } + if !vectorcraft_eps::has_native(bytes) { + return Carried::Absent; + } + vectorcraft_eps::native(bytes).map_or(Carried::Unreadable, |data| read(&data)) +} + +/// The error for a linked file the package would copy whose native document can't be read to +/// check the files and folders it names against the read roots. +const UNREADABLE: &str = "a linked file's editing data can't be read to check it against the read roots"; + /// Under read roots, the linked file `name` (`bytes`, found at `path`) is copied only when the -/// native document it is or carries ([`carried_document`]) links no JavaScript file outside them (a -/// relative path taken from the file's folder): the copy would name it. +/// native document it is or carries ([`carried_document`]) can be read and links no JavaScript file +/// outside them (a relative path taken from the file's folder): the copy would name it. A file +/// whose native document can't be read is refused, as its links can't be checked. The error names +/// no file or folder. fn check_carried_scripts(name: &str, bytes: &[u8], path: &str) -> Result<()> { if crate::file_access::current().is_none() { return Ok(()); } match carried_document(name, bytes) { - Some(carried) => super::fileio::check_scripts_of(C, &carried, Some(path), || true), - None => Ok(()), + Carried::Readable(carried) => super::fileio::check_scripts_of(C, &carried, Some(path), || true), + Carried::Unreadable => Err(bad(C, UNREADABLE)), + Carried::Absent => Ok(()), } } @@ -150,7 +188,10 @@ fn check_carried_folder(name: &str, bytes: &[u8]) -> Result<()> { return Ok(()); } match carried_document(name, bytes) { - Some(carried) if matches!(super::fileio::with_readable_settings_folder(&carried), std::borrow::Cow::Owned(_)) => Err(bad(C, FOLDER_OUTSIDE)), + Carried::Readable(carried) if matches!(super::fileio::with_readable_settings_folder(&carried), std::borrow::Cow::Owned(_)) => { + Err(bad(C, FOLDER_OUTSIDE)) + } + Carried::Unreadable => Err(bad(C, UNREADABLE)), _ => Ok(()), } } @@ -498,6 +539,9 @@ pub struct Package { root: Option, info: Option, doc: std::sync::Arc, + /// The read roots in force where the package was prepared: [`Package::write`] collects under + /// them. + scope: crate::file_access::ScopeHandle, } impl Session { @@ -544,21 +588,22 @@ fn prepare(s: &mut Session, p: &Value) -> Result { let doc = s.doc()?.doc.clone(); let doc = if let std::borrow::Cow::Owned(kept) = super::fileio::with_readable_settings_folder(&doc) { std::sync::Arc::new(kept) } else { doc }; let links_from = s.doc()?.links_from.clone().unwrap_or_else(|| doc_path.clone()); - Ok(Package { o, doc_path, links_from, stem, name, root, info, doc }) + let scope = crate::file_access::ScopeHandle::capture(); + Ok(Package { o, doc_path, links_from, stem, name, root, info, doc, scope }) } impl Package { /// Collect the linked files and fonts and write the package's files with `write` into /// `folder/name`, making its folders first, or into the zip without a folder → the reply of - /// `file.package`. + /// `file.package`, with the read roots in force where it was prepared, on any thread. pub fn write(self, write: &mut dyn FnMut(&str, &[u8]) -> Result<()>) -> Result { - collect_and_write(self, write) + self.scope.clone().run(|| collect_and_write(self, write)) } } /// [`Package::write`]. fn collect_and_write(package: Package, write: &mut dyn FnMut(&str, &[u8]) -> Result<()>) -> Result { - let Package { o, doc_path, links_from, stem, name, root, info, doc: original } = package; + let Package { o, doc_path, links_from, stem, name, root, info, doc: original, scope: _ } = package; let mut doc = (*original).clone(); let doc_name = format!("{stem}.{}", vectorcraft_format::EXTENSION); let base = LinkBase { doc: Some(&doc_path), relative: Some(&links_from) }; diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs index 20b3f18de2..fddd6cdd9c 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/paint.rs @@ -274,8 +274,9 @@ impl DocState { /// Whether the selected objects' fills and strokes differ as the proxies show them (a "?" /// proxy; a group whose contents differ counts). `item` (the Appearance panel's active item) /// stands for the proxy of its kind, as in [`Session::proxy_paints`]: that fill or stroke of - /// each selected object's own stack is compared. One walk of the document, so callers that ask - /// every frame cache it by revision. + /// each selected object's own stack is compared. The selected objects are found through the id + /// cache ([`vectorcraft_doc::Document::nodes_in_order`]); a large selection takes one walk + /// of the document, so callers that ask every frame cache it by revision. pub fn proxy_mixed(&self, item: Option) -> (bool, bool) { self.proxy_mixed_with(item, &[]) } @@ -290,15 +291,17 @@ impl DocState { if self.selection.symbol_part.is_some() { return (false, false); } - let ids: std::collections::HashSet = self.selection.objects.iter().copied().collect(); - let (mut selected, mut nodes) = (vec![], vec![]); - self.doc.walk(|n| { - if ids.contains(&n.id) { - selected.push(n); - painted(n, true, &mut nodes); - } - }); + // Looking the first object up builds the id cache when there is none. let first = self.selection.objects.first().and_then(|id| self.doc.node(*id)); + let (mut selected, mut nodes) = (vec![], vec![]); + // Every node with a selected id, in tree order: a repeated id (a damaged file) counts at each + // place it appears. + for n in self.doc.nodes_in_order(self.selection.objects.iter().copied()) { + #[cfg(test)] + tests::note_gathered(); + selected.push(n); + painted(n, true, &mut nodes); + } let differ = |stroke: bool| { let item = first.and_then(|f| f.appearance.item_of_kind(item, !stroke)); let set = if item.is_some() { &selected } else { &nodes }; @@ -1323,3 +1326,6 @@ fn transparency(s: &mut Session, p: &Value) -> Result { } s.execute("object.setProps", &Value::Object(q)) } + +#[cfg(test)] +mod tests; diff --git a/crates/engine/src/cmd/paint/tests.rs b/crates/engine/src/cmd/paint/tests.rs new file mode 100644 index 0000000000..3da5d73d9e --- /dev/null +++ b/crates/engine/src/cmd/paint/tests.rs @@ -0,0 +1,335 @@ +//! The Fill/Stroke proxies' "?" ([`DocState::proxy_mixed`]) finds the selected objects through the +//! id cache: it answers as a walk of the whole document does, and with a few objects selected it +//! reads only those. + +use std::cell::Cell; +use std::collections::HashSet; +use std::sync::Arc; + +use serde_json::json; +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::{Appearance, Document, LayerColor, Node, NodeId, NodeKind}; +use vectorcraft_geom::{Rect, shapes}; + +use super::{painted, picked_colors, proxy_paint, same_in_proxy}; +use crate::{DocState, Session}; + +thread_local! { + /// [`gathered`] of this thread. + static GATHERED: Cell = const { Cell::new(0) }; +} + +/// Adds one to [`gathered`]: `proxy_mixed_with` read a node while looking for the selected ones. +pub(super) fn note_gathered() { + GATHERED.set(GATHERED.get() + 1); +} + +/// How many nodes `proxy_mixed_with` has read on this thread while looking for the selected ones. +fn gathered() -> u64 { + GATHERED.get() +} + +/// `proxy_mixed_with` as it was when it found the selected objects by walking the whole document. +fn walked(st: &DocState, item: Option, points: &[(NodeId, Vec)]) -> (bool, bool) { + if st.selection.is_empty() { + return (false, false); + } + if st.selection.symbol_part.is_some() { + return (false, false); + } + let ids: HashSet = st.selection.objects.iter().copied().collect(); + let (mut selected, mut nodes) = (vec![], vec![]); + st.doc.walk(|n| { + if ids.contains(&n.id) { + selected.push(n); + painted(n, true, &mut nodes); + } + }); + let first = st.selection.objects.first().and_then(|id| st.doc.node(*id)); + let differ = |stroke: bool| { + let item = first.and_then(|f| f.appearance.item_of_kind(item, !stroke)); + let set = if item.is_some() { &selected } else { &nodes }; + let mut paints = set.iter().flat_map(|n| match picked_colors(n, if stroke || item.is_some() { &[] } else { points }) { + c if c.is_empty() => vec![proxy_paint(n, stroke, item)], + c => c.into_iter().map(Paint::solid).collect(), + }); + let Some(p0) = paints.next() else { return false }; + paints.any(|p| !same_in_proxy(&p0, &p)) + }; + (differ(false), differ(true)) +} + +/// `proxy_mixed_with` answers as [`walked`] does for `st`'s selection, for every Appearance item +/// and with and without `points`, with the id cache built and without it. +fn agree(st: &DocState, points: &[(NodeId, Vec)], what: &str) { + for cold in [true, false] { + if cold { + st.doc.drop_lookup_cache(); + } + for item in [None, Some(0), Some(1), Some(2), Some(3)] { + for points in [points, &[]] { + assert_eq!( + st.proxy_mixed_with(item, points), + walked(st, item, points), + "{what}: item {item:?}, {} picked points, cold cache {cold}", + points.len() + ); + } + } + } +} + +fn id_of(v: &serde_json::Value) -> NodeId { + NodeId(v["id"].as_u64().unwrap()) +} + +fn rect(s: &mut Session, x: f64, fill: &str, stroke: &str) -> NodeId { + let id = id_of(&s.execute("shape.rectangle", &json!({"x": x, "y": 10, "width": 20, "height": 20})).unwrap()); + s.execute("paint.setFill", &json!({"ids": [id.0], "color": fill})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [id.0], "color": stroke})).unwrap(); + id +} + +/// Every case of [`DocState::proxy_mixed`]'s rule, each answered as a walk answers it: one object, +/// different fills or strokes, a group with different contents, a group with one of its objects, +/// objects on two layers, a hidden object, an object with two fills under an Appearance item, a +/// gradient mesh with points picked beside another object, ids not in the document and an id that +/// appears twice (a damaged file) with different paints. +#[test] +fn the_question_marks_match_a_walk_of_the_document() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap(); + let a = rect(&mut s, 10.0, "#ff0000", "#000000"); + let b = rect(&mut s, 40.0, "#0000ff", "#000000"); + let c = rect(&mut s, 70.0, "#ff0000", "#00ff00"); + // Two fills: [Fill, Stroke, Fill]. + s.execute("select.set", &json!({"ids": [c.0]})).unwrap(); + s.execute("appearance.addFill", &json!({})).unwrap(); + s.execute("appearance.setItem", &json!({"index": 2, "color": "#0000ff"})).unwrap(); + let e = rect(&mut s, 100.0, "#ff0000", "#000000"); + let f = rect(&mut s, 130.0, "#00ff00", "#000000"); + let g = id_of(&s.execute("object.group", &json!({"ids": [e.0, f.0]})).unwrap()); + let mesh = rect(&mut s, 160.0, "#ff0000", "#000000"); + s.execute("object.mesh.create", &json!({"ids": [mesh.0], "rows": 2, "cols": 2})).unwrap(); + let hidden = rect(&mut s, 190.0, "#0000ff", "#000000"); + s.execute("object.hide", &json!({"ids": [hidden.0]})).unwrap(); + s.execute("layer.new", &json!({})).unwrap(); + let h = rect(&mut s, 220.0, "#ff0000", "#000000"); + let missing = NodeId(999_999); + let Some(NodeKind::Mesh(m)) = s.doc().unwrap().doc.node(mesh).map(|n| &n.kind) else { panic!("a gradient mesh") }; + let (p00, p01, p11) = (m.idx(0, 0), m.idx(0, 1), m.idx(1, 1)); + s.execute("object.mesh.setPointColor", &json!({"id": mesh.0, "index": p00, "color": "#00ff00"})).unwrap(); + let points = vec![(mesh, vec![p00, p01])]; + let points_alike = vec![(mesh, vec![p01, p11])]; + + let selections = [ + vec![a], + vec![a, b], + vec![b, a], + vec![a, h], + vec![g], + vec![g, e], + vec![e, g], + vec![f, e], + vec![c], + vec![c, a], + vec![a, c], + vec![mesh], + vec![mesh, a], + vec![a, mesh, h], + vec![hidden], + vec![hidden, b], + vec![missing], + vec![missing, a], + vec![a, missing, b], + vec![a, a], + ]; + let check = |s: &mut Session, what: &str| { + for sel in &selections { + let st = s.active_mut().unwrap(); + st.selection.objects = sel.clone(); + let st = s.active().unwrap(); + agree(st, &points, &format!("{what}: {sel:?}")); + agree(st, &points_alike, &format!("{what}: {sel:?}, alike points")); + } + s.execute("select.all", &json!({})).unwrap(); + agree(s.active().unwrap(), &points, &format!("{what}: Select All")); + }; + check(&mut s, "unique ids"); + + // A second node with a's id and another fill, at the end of the tree. + let st = s.active_mut().unwrap(); + let mut copy = st.doc.node(a).unwrap().clone(); + copy.appearance.set_fill(Paint::solid(Color::rgb(0.0, 0.0, 1.0))); + let doc = Arc::make_mut(&mut st.doc); + let last = doc.layers.len() - 1; + Arc::make_mut(&mut doc.layers[last]).children_mut().unwrap().push(Arc::new(copy)); + doc.drop_lookup_cache(); + check(&mut s, "a repeated id"); + let st = s.active_mut().unwrap(); + st.selection.objects = vec![a]; + assert_eq!(st.proxy_mixed_with(None, &[]), (true, false), "the two places of a's id differ in fill"); +} + +/// A document of `layers` layers, each with `groups` groups of `per_group` rectangles; every other +/// rectangle red, the rest blue. Returns it with the rectangles' ids, in tree order. +fn big(layers: usize, groups: usize, per_group: usize) -> (Document, Vec) { + let mut d = Document::new(612.0, 792.0); + d.layers.clear(); + let mut rects = vec![]; + for l in 0..layers { + let mut layer = Node::layer(d.alloc_id(), &format!("L{l}"), LayerColor::Preset(0)); + for _ in 0..groups { + let children = (0..per_group) + .map(|_| { + let id = d.alloc_id(); + let mut ap = Appearance::default_art(); + let red = rects.len() % 2 == 0; + ap.set_fill(Paint::solid(if red { Color::rgb(1.0, 0.0, 0.0) } else { Color::rgb(0.0, 0.0, 1.0) })); + rects.push(id); + Arc::new(Node::path(id, shapes::rectangle(Rect::new(0.0, 0.0, 5.0, 5.0)), ap)) + }) + .collect(); + let group = Node::group(d.alloc_id(), children); + layer.children_mut().unwrap().push(Arc::new(group)); + } + d.layers.push(Arc::new(layer)); + } + (d, rects) +} + +fn state(doc: Document) -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 612, "height": 792})).unwrap(); + s.active_mut().unwrap().doc = Arc::new(doc); + s +} + +/// With one object selected, the "?" reads only that object, not every node of the document, and +/// does not walk the tree once the id cache is built; with every object selected it walks the tree +/// once. +#[test] +fn the_question_marks_read_only_the_selected_objects() { + let (doc, rects) = big(2, 40, 25); + let mut s = state(doc); + let st = s.active_mut().unwrap(); + st.selection.objects = vec![rects[777]]; + assert_eq!(st.proxy_mixed(None), (false, false)); + let (read, walks) = (gathered(), vectorcraft_doc::tree_walks()); + assert_eq!(st.proxy_mixed(None), (false, false)); + assert_eq!(gathered() - read, 1, "only the selected object is read"); + assert_eq!(vectorcraft_doc::tree_walks() - walks, 0, "the cached path answers"); + + st.selection.objects = vec![rects[3], rects[1500]]; + let (read, walks) = (gathered(), vectorcraft_doc::tree_walks()); + assert_eq!(st.proxy_mixed(None), (true, false)); + assert_eq!((gathered() - read, vectorcraft_doc::tree_walks() - walks), (2, 0)); + + st.selection.objects = rects.clone(); + let (read, walks) = (gathered(), vectorcraft_doc::tree_walks()); + assert_eq!(st.proxy_mixed(None), (true, false)); + assert_eq!(gathered() - read, rects.len() as u64); + assert!(vectorcraft_doc::tree_walks() - walks <= 1, "one walk for a large selection"); +} + +/// Random selections of a document with nested groups answer as a walk does. +#[test] +fn random_selections_match_a_walk_of_the_document() { + let (doc, rects) = big(3, 12, 6); + let mut s = state(doc); + let groups: Vec = s.active().unwrap().doc.layers.iter().flat_map(|l| l.children().unwrap().iter().map(|g| g.id)).collect(); + let layers: Vec = s.active().unwrap().doc.layers.iter().map(|l| l.id).collect(); + let all: Vec = rects.iter().chain(&groups).chain(&layers).copied().chain([NodeId(999_999)]).collect(); + let mut r = 0x2545_f491_4f6c_dd1d_u64; + let mut next = |n: usize| { + r ^= r << 13; + r ^= r >> 7; + r ^= r << 17; + (r % n as u64) as usize + }; + for round in 0..200 { + let count = 1 + next(if round % 10 == 0 { all.len() } else { 6 }); + let sel: Vec = (0..count).map(|_| all[next(all.len())]).collect(); + let st = s.active_mut().unwrap(); + st.selection.objects = sel.clone(); + agree(s.active().unwrap(), &[], &format!("round {round}: {sel:?}")); + } +} + +/// The CPU time this thread has used, from Linux's scheduler statistics; `None` elsewhere. +fn thread_cpu() -> Option { + let stat = std::fs::read_to_string("/proc/thread-self/schedstat").ok()?; + stat.split_whitespace().next()?.parse().ok().map(std::time::Duration::from_nanos) +} + +/// The time `f` takes: this thread's CPU time where Linux reports it, otherwise the wall clock. +fn time(f: impl FnOnce()) -> std::time::Duration { + match thread_cpu() { + Some(before) => { + f(); + thread_cpu().map_or(std::time::Duration::ZERO, |after| after.saturating_sub(before)) + } + None => { + let start = std::time::Instant::now(); + f(); + start.elapsed() + } + } +} + +/// The time of `proxy_mixed` against a walk of the document, on 50,000 rectangles in 500 groups on +/// 5 layers: `cargo test --release -p vectorcraft-engine --lib proxy_mixed_timing -- --ignored --nocapture`. +#[test] +#[ignore = "timing; run by hand"] +fn proxy_mixed_timing() { + let (doc, rects) = big(5, 100, 100); + let mut s = state(doc); + let groups: Vec = s.active().unwrap().doc.layers.iter().flat_map(|l| l.children().unwrap().iter().map(|g| g.id)).collect(); + let cases: [(&str, Vec); 5] = [ + ("1 object", vec![rects[25_000]]), + ("2 objects, different fills", vec![rects[10], rects[40_001]]), + ("a group of 100", vec![groups[250]]), + ("all 500 groups", groups.clone()), + ("all 50,000 objects", rects.clone()), + ]; + const CALLS: usize = 200; + let median = |mut v: Vec| { + v.sort_by(f64::total_cmp); + v[v.len() / 2] + }; + println!("proxy_mixed_timing: {}", if thread_cpu().is_some() { "thread CPU time" } else { "wall clock" }); + println!("| Selection | Id cache | Walk (µs/call) | Id cache (µs/call) | Runs (walk / id cache, µs) |"); + println!("|---|---|---|---|---|"); + for (name, sel) in &cases { + for cold in [false, true] { + let st = s.active_mut().unwrap(); + st.selection.objects = sel.clone(); + let st = s.active().unwrap(); + assert_eq!(st.proxy_mixed_with(None, &[]), walked(st, None, &[]), "{name}"); + let (mut old, mut new) = (vec![], vec![]); + let calls = if cold { CALLS / 10 } else { CALLS }; + for _ in 0..7 { + for (times, use_walk) in [(&mut old, true), (&mut new, false)] { + let d = time(|| { + for _ in 0..calls { + if cold { + st.doc.drop_lookup_cache(); + } + std::hint::black_box(if use_walk { walked(st, None, &[]) } else { st.proxy_mixed_with(None, &[]) }); + } + }); + times.push(d.as_secs_f64() * 1e6 / calls as f64); + } + } + let runs = |v: &[f64]| v.iter().map(|x| format!("{x:.1}")).collect::>().join(" "); + println!( + "| {name} | {} | {:.1} | {:.1} | {} / {} |", + if cold { "dropped before each call" } else { "built" }, + median(old.clone()), + median(new.clone()), + runs(&old), + runs(&new) + ); + } + } +} diff --git a/crates/engine/src/cmd/path.rs b/crates/engine/src/cmd/path.rs index 6c06b52c6c..0960e5ca28 100644 --- a/crates/engine/src/cmd/path.rs +++ b/crates/engine/src/cmd/path.rs @@ -1,10 +1,10 @@ //! Path editing commands (used by the Pen and Direct Selection tools and Object → Path). -use std::collections::BTreeSet; +use std::collections::{BTreeMap, BTreeSet}; use std::sync::Arc; use serde_json::{Value, json}; -use vectorcraft_doc::{Document, Node, NodeId, NodeKind, Scaling, Selection}; +use vectorcraft_doc::{AnchorRef, Document, Node, NodeId, NodeKind, Scaling, Selection}; use vectorcraft_geom::{Anchor, AnchorKind, Anchors, PathData, Point, SubPath, Vec2}; use super::create::anchor_from_json; @@ -41,7 +41,7 @@ pub fn specs() -> Vec { "Move Anchors", [], None, - "{dx, dy, patterns?: bool (Transform Patterns: pattern fills and strokes transform with the objects that move whole; default: prefs transformPatternTiles)} move direct-selected anchors (whole paths if fully selected); refused while an object of a symbol instance's art is selected", + "{dx, dy, patterns?: bool (Transform Patterns: pattern fills and strokes transform with the objects that move whole; default: prefs transformPatternTiles), interpolate?: bool (Interpolate Control Points: the handles of each segment with one moved end are re-mapped by the turn, scale and move that take its old ends to its new ends; default: prefs interpolateControlPoints)} move direct-selected anchors (whole paths if fully selected); refused while an object of a symbol instance's art is selected", has_selection, move_anchors ), @@ -245,28 +245,43 @@ fn close(s: &mut Session, p: &Value) -> Result { pub(crate) fn move_anchors(s: &mut Session, p: &Value) -> Result { let d = Vec2::new(number_or(p, "dx", 0.0, "path.moveAnchors")?, number_or(p, "dy", 0.0, "path.moveAnchors")?); - check_switches(p, &["patterns"], "path.moveAnchors")?; + check_switches(p, &["patterns", "interpolate"], "path.moveAnchors")?; // An object selected in a symbol instance's art stays where the symbol puts it. super::edit::refuse_symbol_part(s)?; // Objects selected whole move as objects, and their pattern tiles move with them when // `patterns` (default: General › Transform Pattern Tiles) is on. let whole = s.doc()?.selection.whole(); let sc = Scaling { patterns: super::object::transform_patterns(s, p, &whole)?, ..Scaling::default() }; - transform_anchors(s, "Move", vectorcraft_geom::Affine::translate(d), sc)?; + let interpolate = interpolates_handles(s, p, "path.moveAnchors")?; + transform_anchors(s, "Move", vectorcraft_geom::Affine::translate(d), sc, interpolate)?; // Transform Again repeats a move that moved something; a drag records it when it commits. let st = s.doc_mut()?; if st.interaction.is_none() && (d.x != 0.0 || d.y != 0.0) { - let options = json!({ "copy": false, "patterns": sc.patterns }); + let options = json!({ "copy": false, "patterns": sc.patterns, "interpolate": interpolate }); st.last_transform = Some(crate::LastTransform::Matrix(vectorcraft_geom::Affine::translate(d), options)); st.last_perspective = None; } ok() } +/// Interpolate Control Points: does a move of direct-selected anchors re-map the handles of the +/// segments beside them (`interpolate` param, else General › Interpolate Control Points When +/// Moving Anchors)? Noted in the journal, so a replay re-maps them alike whatever the preference +/// is then. A saved step without `interpolate` ([`Session::replay`]) was recorded before the +/// preference existed, so it moves the handles as it did then, without re-mapping them. +pub(crate) fn interpolates_handles(s: &mut Session, p: &Value, cmd: &str) -> Result { + let default = s.prefs.interpolate_control_points && !s.replaying(); + let on = switch_or(p, "interpolate", default, cmd)?; + s.note_journal("interpolate", json!(on)); + Ok(on) +} + /// Apply `xf` to the direct-selected anchors, their handles with them, and (with `sc`) to the /// objects selected whole (those with no entry in the selection's `anchors`). An object inside /// another selected object, such as a path in a selected group, moves once, with that object. -pub(crate) fn transform_anchors(s: &mut Session, label: &str, xf: vectorcraft_geom::Affine, sc: Scaling) -> Result<()> { +/// When `xf` is a move and `interpolate` is on, the handles of each segment with one moved end +/// are re-mapped ([`move_interpolating_handles`]). +pub(crate) fn transform_anchors(s: &mut Session, label: &str, xf: vectorcraft_geom::Affine, sc: Scaling, interpolate: bool) -> Result<()> { let sel = s.doc()?.selection.clone(); let ids = super::edit::outermost(&s.doc()?.doc, sel.objects.clone()); let c = xf.as_coeffs(); @@ -277,9 +292,15 @@ pub(crate) fn transform_anchors(s: &mut Session, label: &str, xf: vectorcraft_ge match sel.anchors.get(id) { Some(set) => { let path = path_mut(doc, *id)?; - for &(si, ai) in set { - if let Some(a) = path.anchor_mut(si, ai) { - *a = a.transform(xf); + // Only an exact move takes the interpolating path: a near-identity scale or + // turn still transforms the anchors as asked. + if interpolate && c[..4] == [1.0, 0.0, 0.0, 1.0] { + move_interpolating_handles(path, set, delta); + } else { + for &(si, ai) in set { + if let Some(a) = path.anchor_mut(si, ai) { + *a = a.transform(xf); + } } } // A pixel-aligned path, or the pixel-aligned compound path that holds it, snaps @@ -307,6 +328,129 @@ pub(crate) fn transform_anchors(s: &mut Session, label: &str, xf: vectorcraft_ge }) } +/// Move the anchors `set` of `path` by `d`, their handles with them, then re-map the two handles +/// of each segment with exactly one moved end by the map that takes the segment's old ends to its +/// new ends: a turn, a uniform scale and a move. Between two corner anchors the segment keeps its +/// shape relative to its ends. A segment with both ends moved, or with its ends at the same place +/// before or after the move, moves as it does without the preference. A smooth anchor keeps its +/// two handles in line ([`line_up_handles`]). +fn move_interpolating_handles(path: &mut PathData, set: &BTreeSet, d: Vec2) { + // (subpath, anchor, outgoing handle?, new position) + let mut placed: Vec<(usize, usize, bool, Point)> = Vec::new(); + if d != Vec2::ZERO { + // Only the segments beside a moved anchor can have one moved end: (subpath, first anchor). + let mut segments: BTreeSet = BTreeSet::new(); + for &(si, ai) in set { + let Some(sp) = path.subpaths.get(si) else { continue }; + let n = sp.anchors.len(); + if ai >= n || n < 2 { + continue; + } + if ai > 0 || sp.closed { + segments.insert((si, (ai + n - 1) % n)); + } + if ai + 1 < n || sp.closed { + segments.insert((si, ai)); + } + } + for (si, from) in segments { + let Some(sp) = path.subpaths.get(si) else { continue }; + let to = (from + 1) % sp.anchors.len().max(1); + let (moved_from, moved_to) = (set.contains(&(si, from)), set.contains(&(si, to))); + if moved_from == moved_to { + continue; + } + let (Some(a), Some(b)) = (sp.anchors.get(from), sp.anchors.get(to)) else { continue }; + let old = b.p - a.p; + let len2 = old.hypot2(); + if len2 <= 1e-12 || !len2.is_finite() { + continue; + } + let start = if moved_from { a.p + d } else { a.p }; + let end = if moved_to { b.p + d } else { b.p }; + let new = end - start; + // A move that puts the two ends at the same place would collapse both handles onto + // them, past recovering by moving back. + if new.hypot2() <= 1e-12 { + continue; + } + // `new / old` as complex numbers: the turn and scale between the two chords. + let (re, im) = ((new.x * old.x + new.y * old.y) / len2, (new.y * old.x - new.x * old.y) / len2); + let map = |h: Point| { + let v = h - a.p; + start + Vec2::new(v.x * re - v.y * im, v.x * im + v.y * re) + }; + // A retracted handle goes to its anchor's new place exactly: mapped, it could land a + // rounding error away, which `line_up_handles` would read as a direction. + let h_out = if a.h_out == a.p { start } else { map(a.h_out) }; + let h_in = if b.h_in == b.p { end } else { map(b.h_in) }; + if h_out.is_finite() && h_in.is_finite() { + placed.push((si, from, true, h_out)); + placed.push((si, to, false, h_in)); + } + } + } + for &(si, ai) in set { + if let Some(a) = path.anchor_mut(si, ai) { + a.translate(d); + } + } + // For each anchor with a re-mapped handle: its handles as the plain move left them, and which + // of them (outgoing, incoming) were re-mapped. + let mut touched: BTreeMap = BTreeMap::new(); + for &(si, ai, out, pos) in &placed { + if let Some(a) = path.anchor_mut(si, ai) { + let e = touched.entry((si, ai)).or_insert((a.h_out, a.h_in, false, false)); + if out { + a.h_out = pos; + e.2 = true; + } else { + a.h_in = pos; + e.3 = true; + } + } + } + for ((si, ai), (rigid_out, rigid_in, out, inn)) in touched { + let Some(a) = path.anchor_mut(si, ai) else { continue }; + if a.kind == AnchorKind::Smooth && !line_up_handles(a, out, inn) { + a.h_out = rigid_out; + a.h_in = rigid_in; + } + } +} + +/// Put the handles of the smooth anchor `a` back in line after [`move_interpolating_handles`] +/// re-mapped its outgoing handle (`out`), its incoming handle (`inn`) or both. A re-mapped handle +/// turns to point away from the other handle, at its own new length; when both were re-mapped, +/// both point along the mean of their directions. A retracted handle is left as it is. False when +/// both were re-mapped to point the same way, which has no mean direction: the caller then moves +/// both handles with the anchor. +fn line_up_handles(a: &mut Anchor, out: bool, inn: bool) -> bool { + let (v_out, v_in) = (a.h_out - a.p, a.h_in - a.p); + let (l_out, l_in) = (v_out.hypot(), v_in.hypot()); + if l_out <= 0.0 || l_in <= 0.0 || !l_out.is_finite() || !l_in.is_finite() { + return true; + } + let dir = match (out, inn) { + (true, true) => v_out / l_out - v_in / l_in, + (true, false) => -v_in / l_in, + (false, true) => v_out / l_out, + (false, false) => return true, + }; + let l = dir.hypot(); + if l <= 1e-12 || !l.is_finite() { + return false; + } + let dir = dir / l; + if out { + a.h_out = a.p + dir * l_out; + } + if inn { + a.h_in = a.p - dir * l_in; + } + true +} + fn set_handle(s: &mut Session, p: &Value) -> Result { let id = object_param(p, "id", "path.setHandle")?.ok_or_else(|| bad("path.setHandle", "missing id"))?; let si = usize_opt(p, "subpath", "path.setHandle")?.unwrap_or(0); diff --git a/crates/engine/src/cmd/plugin.rs b/crates/engine/src/cmd/plugin.rs index 48a6649d77..5570dc6a81 100644 --- a/crates/engine/src/cmd/plugin.rs +++ b/crates/engine/src/cmd/plugin.rs @@ -161,6 +161,8 @@ pub struct FilterRun { parent: Option, /// The document it was made from, and that document's revision then. document: (u64, u64), + /// The plug-in's limits with the Plug-in Instruction Budget in force when it was made. + limits: vectorcraft_plugins::Limits, } /// A filter's output handed in by a [`FilterRun`] made away from `plugin.run`, with what the run @@ -245,7 +247,11 @@ impl FilterRun { let capacity = (plugin.limits().max_memory_bytes / 2).min(i32::MAX as usize).saturating_sub(params.len()); let (input, read_only) = objects::encode_input_with(&st.doc, &inputs, &kinds, capacity).map_err(err)?; let document = (st.uid, st.revision); - Ok(FilterRun { plugin, command, input, params, inputs, read_only, parent, document }) + let limits = match s.prefs.plugin_instruction_budget { + crate::PluginBudget::Normal => plugin.limits().clone(), + crate::PluginBudget::Large => plugin.large_limits(), + }; + Ok(FilterRun { plugin, command, input, params, inputs, read_only, parent, document, limits }) } /// The plug-in, for its name and budget. @@ -274,7 +280,13 @@ impl FilterRun { /// can run on any thread; inside a [`vectorcraft_doc::cancel::scope`] Cancel stops it between /// two slices of its budget. pub fn run(&self) -> Result> { - self.plugin.run(&self.input, &self.params).map_err(err) + self.plugin.run_limited(&self.input, &self.params, &self.limits).map_err(err) + } + + /// The limits it runs under: the plug-in's, with the Plug-in Instruction Budget in force when + /// it was made. + pub fn limits(&self) -> &vectorcraft_plugins::Limits { + &self.limits } /// Does the plug-in call commands (its manifest's `commandAllowlist`)? Then it runs only in the @@ -289,7 +301,7 @@ impl FilterRun { let may = self.plugin.manifest().permissions(); let calls = super::plugin_call::Calls::of(s, may.contains(&Permission::DocRead), may.contains(&Permission::DocWrite)); let mut bridge = |id: &str, args: &Value| super::plugin_call::call(s, &calls, id, args); - self.plugin.run_calling(&self.input, &self.params, self.plugin.limits(), &mut bridge).0.map_err(err) + self.plugin.run_calling(&self.input, &self.params, &self.limits, &mut bridge).0.map_err(err) } /// Runs a plug-in that calls commands and applies its output: the calls and the output are one diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index 12cf0740f0..80c8e7f2bf 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -46,6 +46,7 @@ pub(super) const ALLOWED: &[&str] = &[ "addon.packaging.setRole", "addon.packaging.setRoleSwatch", "addon.pathtools.addPoints", + "addon.pathtools.bridge", "addon.pathtools.close", "addon.pathtools.commonTangents", "addon.pathtools.corner", diff --git a/crates/engine/src/cmd/prefscmds.rs b/crates/engine/src/cmd/prefscmds.rs index 03d770ac0e..774c450065 100644 --- a/crates/engine/src/cmd/prefscmds.rs +++ b/crates/engine/src/cmd/prefscmds.rs @@ -139,6 +139,7 @@ pub const PREF_SPECS: &[PrefSpec] = &[ p!("cornerRadius", "General", "", "Corner Radius", len(0.0, 1296.0, General)), p!("pasteOffset", "General", "", "Paste Offset", len(0.0, 1296.0, General)), p!("disableAutoAddDelete", "General", "Options", "Disable Auto Add/Delete", bool), + p!("interpolateControlPoints", "General", "Options", "Interpolate Control Points When Moving Anchors", bool), p!("usePreciseCursors", "General", "Options", "Use Precise Cursors", bool), p!("showToolTips", "General", "Options", "Show Tool Tips", bool), p!("showExternalScriptWarning", "General", "Options", "Show External Script Warning", bool), @@ -323,6 +324,14 @@ pub const PREF_SPECS: &[PrefSpec] = &[ p!("hyphenationExceptions", "Hyphenation", "", "Exceptions (comma separated)", text), // Plug-ins & Scratch Disks p!("pluginsFolder", "Plug-ins & Scratch Disks", "Plug-ins", "Additional Plug-ins Folder", text), + // The instructions each object filter run gets: Large gives at least 250 M besides those for each byte of input. + p!( + "pluginInstructionBudget", + "Plug-ins & Scratch Disks", + "Plug-ins", + "Plug-in Instruction Budget", + choice(&[("normal", "Normal"), ("large", "Large")]) + ), p!("scratchPrimary", "Plug-ins & Scratch Disks", "Scratch Disks", "Primary", text), p!("scratchSecondary", "Plug-ins & Scratch Disks", "Scratch Disks", "Secondary", text), // User Interface diff --git a/crates/engine/src/cmd/select.rs b/crates/engine/src/cmd/select.rs index ea3181faf9..b7a6043a98 100644 --- a/crates/engine/src/cmd/select.rs +++ b/crates/engine/src/cmd/select.rs @@ -375,6 +375,59 @@ fn is_selectable_within(d: &Document, iso: Option, locks: Option<&Locked } } +/// The object Next Object Above (`dir` > 0) or Next Object Below selects from `cur`: the nearest +/// sibling of `cur` in that direction that [`walk_selectable`] visits. Hidden and locked objects +/// and sublayers are passed over. Only the siblings are read, not the rest of the document. +fn step_target(d: &Document, iso: Option, cur: NodeId, dir: i64) -> Option { + let path = d.index_path(cur)?; + let (&idx, up) = path.split_last()?; + // The objects that hold `cur` and its siblings, from the top-level layer down. + let mut holders = Vec::with_capacity(up.len()); + let mut siblings = &d.layers; + for &i in up { + let n = siblings.get(i)?; + holders.push(n.as_ref()); + siblings = n.children()?; + } + let iso = iso.and_then(|i| d.node(i)); + let locks = d.locked_artboards(); + let visits = |n: &Node| walk_visits(&holders, n, iso, &locks); + let next = if dir > 0 { siblings.iter().skip(idx + 1).find(|n| visits(n)) } else { siblings.iter().take(idx).rev().find(|n| visits(n)) }; + next.map(|n| n.id) +} + +/// Whether [`walk_selectable`] visits `n`, read from the objects that hold it: `holders` are its +/// layer and the sublayers, groups and other containers inside it that hold `n`, outermost first +/// (its [`Document::ancestry`] without `n`). `iso` is the isolated object. Unlike +/// [`is_selectable`], it passes over sublayers and the ruler guides of a layer, which the walk +/// looks through or leaves out. +fn walk_visits(holders: &[&Node], n: &Node, iso: Option<&Node>, locks: &LockedArtboards) -> bool { + let len = holders.len() + 1; + let at = |i: usize| holders.get(i).copied().unwrap_or(n); + let open = |i: usize| at(i).visible && !at(i).locked; + let start = match iso { + Some(c) => { + let Some(p) = (0..len).find(|&i| at(i).id == c.id) else { return false }; + if !(0..=p).all(|i| open(i) && !at(i).is_template()) { + return false; + } + // A single object isolated is all there is to select. + if !c.is_container() { + return p + 1 == len; + } + p + 1 + } + None => 0, + }; + // The object Select All takes: the first one that is not a layer, inside visible, unlocked + // layers and sublayers that are not template layers. + let Some(top) = (start..len).find(|&i| !at(i).is_layer()) else { return false }; + (start..top).all(|i| open(i) && !at(i).is_template()) + && !at(top).is_ruler_guide() + && (top..len).all(open) + && (iso.is_some() || locks.is_empty() || !locks.holds(at(top))) +} + /// The first selected object, in selection order, that [`is_selectable`] accepts. pub(crate) fn first_selectable(st: &DocState) -> Option<&Node> { let locks = st.doc.locked_artboards(); @@ -475,17 +528,7 @@ fn inverse(s: &mut Session, _: &Value) -> Result { fn step(s: &mut Session, dir: i64) -> Result { let st = s.doc()?; let Some(cur) = st.selection.objects.first().copied() else { return ok() }; - let Some((par, idx, _)) = st.doc.position(cur) else { return ok() }; - let Some(siblings) = st.doc.children(par) else { return ok() }; - // The nearest sibling in that direction that `walk_selectable` visits: hidden and locked - // objects and sublayers are passed over. - let can = selectable_ids(&st.doc, st.isolation); - let next = if dir > 0 { - siblings.iter().skip(idx + 1).find(|n| can.contains(&n.id)) - } else { - siblings.iter().take(idx).rev().find(|n| can.contains(&n.id)) - }; - let Some(id) = next.map(|n| n.id) else { return ok() }; + let Some(id) = step_target(&st.doc, st.isolation, cur, dir) else { return ok() }; s.select(|_, sel| sel.set([id]))?; ok() } @@ -1399,5 +1442,8 @@ fn not_pixel_aligned(s: &mut Session, _: &Value) -> Result { #[cfg(test)] mod same_tests; +#[cfg(test)] +mod step_tests; + #[cfg(test)] mod tests; diff --git a/crates/engine/src/cmd/select/step_tests.rs b/crates/engine/src/cmd/select/step_tests.rs new file mode 100644 index 0000000000..0a43cc0cf0 --- /dev/null +++ b/crates/engine/src/cmd/select/step_tests.rs @@ -0,0 +1,347 @@ +//! Select > Next Object Above and Below through [`step_target`], which reads only the siblings of +//! the selected object, against a copy of the search that collected every object +//! [`walk_selectable`] visits on each step. + +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use serde_json::json; +use vectorcraft_doc::{Appearance, Document, LayerColor, Node, NodeId, NodeKind}; +use vectorcraft_geom::{Rect, shapes}; + +use super::{selectable_ids, step_target, walk_visits}; +use crate::Session; + +/// The search as it was before it read only the siblings: the nearest sibling in that direction +/// that `walk_selectable` visits, from the set of every object it visits. +fn step_base(d: &Document, iso: Option, cur: NodeId, dir: i64) -> Option { + let (par, idx, _) = d.position(cur)?; + let siblings = d.children(par)?; + let can = selectable_ids(d, iso); + let next = if dir > 0 { + siblings.iter().skip(idx + 1).find(|n| can.contains(&n.id)) + } else { + siblings.iter().take(idx).rev().find(|n| can.contains(&n.id)) + }; + next.map(|n| n.id) +} + +/// A small xorshift generator, so that each seed gives the same document every run. +struct Rng(u64); + +impl Rng { + fn next(&mut self) -> u64 { + self.0 ^= self.0 << 13; + self.0 ^= self.0 >> 7; + self.0 ^= self.0 << 17; + self.0 + } + + fn below(&mut self, n: u64) -> u64 { + self.next() % n + } + + /// True `pct` times in 100. + fn chance(&mut self, pct: u64) -> bool { + self.below(100) < pct + } +} + +fn rect_node(d: &mut Document, x: f64, y: f64) -> Node { + Node::path(d.alloc_id(), shapes::rectangle(Rect::new(x, y, x + 40.0, y + 40.0)), Appearance::default()) +} + +fn layer_node(d: &mut Document, children: Vec) -> Node { + let mut l = Node::layer(d.alloc_id(), "Layer", LayerColor::Preset(0)); + if let Some(ch) = l.children_mut() { + ch.extend(children.into_iter().map(Arc::new)); + } + l +} + +fn ruler_guide(d: &mut Document, pos: f64) -> Node { + Node::new(d.alloc_id(), NodeKind::RulerGuide { vertical: pos > 300.0, pos, artboard: None }) +} + +/// Up to six objects: rectangles on and off the artboard, guides made from paths, ruler guides, +/// groups, and sublayers, some hidden, locked or template layers. Groups and sublayers hold more +/// below `depth`. Sublayers and ruler guides also go inside groups, which the app does not make, +/// so that every shape of tree is compared. +fn objects(r: &mut Rng, d: &mut Document, depth: u32) -> Vec { + (0..r.below(7)) + .map(|_| { + let (x, y) = (r.below(1400) as f64 - 300.0, r.below(1000) as f64 - 200.0); + let mut n = match r.below(if depth == 0 { 6 } else { 10 }) { + 0..=3 => rect_node(d, x, y), + 4 => { + let mut n = rect_node(d, x, y); + if let NodeKind::Path { guide, .. } = &mut n.kind { + *guide = true; + } + n + } + 5 => ruler_guide(d, x), + 6 | 7 => { + let kids = objects(r, d, depth - 1); + Node::group(d.alloc_id(), kids.into_iter().map(Arc::new).collect()) + } + _ => { + let kids = objects(r, d, depth - 1); + layer_node(d, kids) + } + }; + n.visible = !r.chance(10); + n.locked = r.chance(10); + if let NodeKind::Layer { template, .. } = &mut n.kind { + *template = r.chance(15); + } + n + }) + .collect() +} + +/// A document of one to three layers, some hidden, locked or template layers, holding +/// [`objects`], with its artboard locked in some seeds. +fn random_document(seed: u64) -> Document { + let mut r = Rng(seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1); + let mut d = Document::new(800.0, 600.0); + let layers = (0..1 + r.below(3)) + .map(|_| { + let kids = objects(&mut r, &mut d, 3); + let mut l = layer_node(&mut d, kids); + l.visible = !r.chance(10); + l.locked = r.chance(10); + if let NodeKind::Layer { template, .. } = &mut l.kind { + *template = r.chance(10); + } + Arc::new(l) + }) + .collect(); + d.layers = layers; + if let Some(a) = d.artboards.first_mut() { + a.locked = r.chance(40); + } + d +} + +/// Every node of `d`, layers included, in tree order. +fn all_ids(d: &Document) -> Vec { + let mut ids = vec![]; + d.walk(|n| ids.push(n.id)); + ids +} + +/// The objects that hold `id`, outermost first, and the node itself. +fn holders(d: &Document, id: NodeId) -> (Vec<&Node>, &Node) { + let a = d.ancestry(id).unwrap(); + let (last, up) = a.split_last().unwrap(); + (up.iter().map(|i| d.node(*i).unwrap()).collect(), d.node(*last).unwrap()) +} + +/// For every node of random documents, outside isolation mode and with each of several nodes +/// isolated, `walk_visits` says what the set of the objects `walk_selectable` visits says, and +/// Next Object Above and Below from it give what the search over that set gave. +#[test] +fn next_object_gives_what_the_search_over_every_selectable_object_gave() { + let (mut steps, mut moved, mut isolated) = (0, 0, 0); + for seed in 0..300 { + let d = random_document(seed); + let ids = all_ids(&d); + let mut r = Rng(seed + 7); + let mut isos = vec![None]; + isos.extend((0..10).map(|_| Some(ids[r.below(ids.len() as u64) as usize]))); + let locks = d.locked_artboards(); + for iso in isos { + let can = selectable_ids(&d, iso); + let iso_node = iso.and_then(|i| d.node(i)); + for &id in &ids { + let (up, n) = holders(&d, id); + assert_eq!(walk_visits(&up, n, iso_node, &locks), can.contains(&id), "seed {seed}, isolating {iso:?}, node {id:?}"); + } + for &cur in &ids { + for dir in [1, -1] { + let want = step_base(&d, iso, cur, dir); + assert_eq!(step_target(&d, iso, cur, dir), want, "seed {seed}, isolating {iso:?}, from {cur:?}, direction {dir}"); + steps += 1; + moved += usize::from(want.is_some()); + isolated += usize::from(want.is_some() && iso.is_some()); + } + } + } + } + // The documents give many steps that select something, inside isolation mode too. + eprintln!("{moved} of {steps} steps select an object, {isolated} of them in isolation mode"); + assert!(moved > 5_000, "{moved} of {steps} steps select an object"); + assert!(isolated > 500, "{isolated} steps select an object in isolation mode"); +} + +/// A session holding `d`, with `iso` isolated and `cur` selected. +fn session(d: Document, iso: Option, cur: NodeId) -> Session { + let mut s = Session::new(); + s.add_document(d, None); + let st = s.doc_mut().unwrap(); + st.isolation = iso; + st.selection.set([cur]); + s +} + +fn selected(s: &Session) -> Vec { + s.doc().unwrap().selection.objects.to_vec() +} + +/// In an isolated layer, Next Object Above and Below pass over a sublayer beside the selected object, +/// as the walk looks through it. +#[test] +fn next_object_passes_over_a_sublayer_in_an_isolated_layer() { + let mut d = Document::new(800.0, 600.0); + let a = rect_node(&mut d, 0.0, 0.0); + let inner = rect_node(&mut d, 100.0, 0.0); + let b = rect_node(&mut d, 200.0, 0.0); + let sub = layer_node(&mut d, vec![inner]); + let (a_id, b_id) = (a.id, b.id); + let l = layer_node(&mut d, vec![a, sub, b]); + let layer = l.id; + d.layers = vec![Arc::new(l)]; + assert_eq!(step_base(&d, Some(layer), a_id, 1), Some(b_id)); + let mut s = session(d, Some(layer), a_id); + s.execute("select.nextAbove", &json!({})).unwrap(); + assert_eq!(selected(&s), vec![b_id]); + s.execute("select.nextBelow", &json!({})).unwrap(); + assert_eq!(selected(&s), vec![a_id]); +} + +/// Next Object Above passes over a ruler guide of the layer, which the walk leaves out, unless the +/// guide is the object isolated. +#[test] +fn next_object_passes_over_a_ruler_guide_of_the_layer() { + let mut d = Document::new(800.0, 600.0); + let a = rect_node(&mut d, 0.0, 0.0); + let b = rect_node(&mut d, 200.0, 0.0); + let guide = ruler_guide(&mut d, 100.0); + let (a_id, b_id, guide_id) = (a.id, b.id, guide.id); + let l = layer_node(&mut d, vec![a, b, guide]); + d.layers = vec![Arc::new(l)]; + // Nothing above the rectangle but the guide: the selection stays. + assert_eq!(step_base(&d, None, b_id, 1), None); + let mut s = session(d.clone(), None, b_id); + s.execute("select.nextAbove", &json!({})).unwrap(); + assert_eq!(selected(&s), vec![b_id]); + s.execute("select.nextBelow", &json!({})).unwrap(); + assert_eq!(selected(&s), vec![a_id]); + // The guide isolated on its own is what there is to select. + assert_eq!(step_base(&d, Some(guide_id), b_id, 1), Some(guide_id)); + assert_eq!(step_target(&d, Some(guide_id), b_id, 1), Some(guide_id)); +} + +/// The first selected object anchors the search even when it can no longer be selected itself. +#[test] +fn next_object_steps_from_a_hidden_first_selected_object() { + let mut d = Document::new(800.0, 600.0); + let mut a = rect_node(&mut d, 0.0, 0.0); + a.visible = false; + let b = rect_node(&mut d, 200.0, 0.0); + let (a_id, b_id) = (a.id, b.id); + let l = layer_node(&mut d, vec![a, b]); + d.layers = vec![Arc::new(l)]; + assert_eq!(step_base(&d, None, a_id, 1), Some(b_id)); + let mut s = session(d, None, a_id); + s.execute("select.nextAbove", &json!({})).unwrap(); + assert_eq!(selected(&s), vec![b_id]); +} + +/// The CPU time this thread has used, from Linux's scheduler statistics; `None` elsewhere. +fn thread_cpu() -> Option { + let stat = std::fs::read_to_string("/proc/thread-self/schedstat").ok()?; + stat.split_whitespace().next()?.parse().ok().map(Duration::from_nanos) +} + +/// The time `f` takes: this thread's CPU time where Linux reports it, otherwise the wall clock. +fn time(f: impl FnOnce()) -> Duration { + match thread_cpu() { + Some(before) => { + f(); + thread_cpu().map_or(Duration::ZERO, |after| after.saturating_sub(before)) + } + None => { + let start = Instant::now(); + f(); + start.elapsed() + } + } +} + +/// A document of `groups` groups of `per` rectangles on one layer, or of `per` rectangles when +/// `groups` is 0 → the document and the object in the middle of the layer. +fn wide(groups: usize, per: usize) -> (Document, NodeId) { + let mut d = Document::new(800.0, 600.0); + let mut top = vec![]; + if groups == 0 { + top.extend((0..per).map(|i| rect_node(&mut d, (i % 200) as f64 * 4.0, (i / 200 % 150) as f64 * 4.0))); + } else { + for g in 0..groups { + let kids: Vec> = (0..per).map(|i| Arc::new(rect_node(&mut d, (i % 20) as f64 * 4.0, (g % 150) as f64 * 4.0))).collect(); + top.push(Node::group(d.alloc_id(), kids)); + } + } + let mid = top[top.len() / 2].id; + let l = layer_node(&mut d, top); + d.layers = vec![Arc::new(l)]; + (d, mid) +} + +/// A search for the object Next Object Above or Below selects: [`step_base`] or [`step_target`]. +type Step = fn(&Document, Option, NodeId, i64) -> Option; + +/// Timings of Next Object Above and Below, stepping up and down from the object in the middle of +/// the layer, by the search over every selectable object (200 steps a run) and by the siblings +/// alone (200,000 steps a run, as one step takes too little time to measure), on 100,000 +/// rectangles and on 1,000 groups of 100, run in turn on the same document, 7 runs each. Ignored by +/// default; it prints the median, fastest and slowest time per step and sets no bound on them: +/// `cargo test --release -p vectorcraft-engine --lib next_object_perf -- --ignored --nocapture`. +#[test] +#[ignore = "a benchmark: run with --ignored --nocapture"] +fn next_object_perf() { + const RUNS: usize = 7; + const OLD_STEPS: usize = 200; + const NEW_STEPS: usize = 200_000; + let per_step = |d: Duration, steps: usize| d.as_secs_f64() * 1e6 / steps as f64; + eprintln!("next_object_perf: {}", if thread_cpu().is_some() { "thread CPU time" } else { "wall clock" }); + eprintln!("next_object_perf: {:<26} {:>32} {:>32}", "document", "every object µs/step (min-max)", "siblings µs/step (min-max)"); + for (name, groups, per) in [("100,000 rectangles", 0, 100_000), ("1,000 groups of 100", 1_000, 100)] { + let (d, mid) = wide(groups, per); + let walk = |f: Step, steps: usize| { + let mut cur = mid; + let mut seen = Vec::with_capacity(steps); + for i in 0..steps { + cur = f(&d, None, cur, if i % 2 == 0 { 1 } else { -1 }).unwrap_or(cur); + seen.push(cur); + } + std::hint::black_box(seen) + }; + let (mut old, mut new) = (Vec::new(), Vec::new()); + let (mut a, mut b) = (vec![], vec![]); + for run in 0..RUNS { + // The two take turns going first. + if run % 2 == 0 { + old.push(time(|| a = walk(step_base, OLD_STEPS))); + new.push(time(|| b = walk(step_target, NEW_STEPS))); + } else { + new.push(time(|| b = walk(step_target, NEW_STEPS))); + old.push(time(|| a = walk(step_base, OLD_STEPS))); + } + assert_eq!(a[..], b[..OLD_STEPS], "{name}"); + assert_ne!(a[0], mid, "{name}: the first step selects another object"); + } + old.sort(); + new.sort(); + eprintln!( + "next_object_perf: {name:<26} {:>12.3} ({:>8.3}-{:>9.3}) {:>12.3} ({:>8.3}-{:>9.3})", + per_step(old[RUNS / 2], OLD_STEPS), + per_step(old[0], OLD_STEPS), + per_step(old[RUNS - 1], OLD_STEPS), + per_step(new[RUNS / 2], NEW_STEPS), + per_step(new[0], NEW_STEPS), + per_step(new[RUNS - 1], NEW_STEPS), + ); + } +} diff --git a/crates/engine/src/cmd/style.rs b/crates/engine/src/cmd/style.rs index 76287e490d..1b5fec0a3b 100644 --- a/crates/engine/src/cmd/style.rs +++ b/crates/engine/src/cmd/style.rs @@ -76,7 +76,7 @@ pub fn specs() -> Vec { "Redefine Graphic Style", ["Window", "Appearance"], None, - "{name?, id?} replace the style (default: the one the object was last linked to) with the look of object `id` or the first selected object (a graph series group with no fill, stroke, effect, opacity, blend mode, isolation, knockout or style link of its own: the topmost path directly in it; a graph's Axes or Legend group: its topmost line or label); the objects still linked to it update, and that object becomes linked. The art of a graph design in a series keeps its look and is unlinked, as the source or as a linked object. A linked graph series group passes the style to the paths directly in it, a linked Axes group to its lines and labels and a linked Legend group to its labels, other than the source and paths linked to the style whose look was edited, and is left cleared (as appearance.clear) and unlinked. On a linked path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind → {name}", + "{name?, id?} | {name, from} replace the style (default: the one the object was last linked to) with the look of object `id` or the first selected object (a graph series group with no fill, stroke, effect, opacity, blend mode, isolation, knockout or style link of its own: the topmost path directly in it; a graph's Axes or Legend group: its topmost line or label); the objects still linked to it update, and that object becomes linked. With `from`, the style takes the look of the style named `from` (its fills, strokes, effects, opacity, blend mode, isolate and knockout) and keeps its own name and place; `from` and the objects linked to it stay as they are, `from` naming the style itself or a style with the same look changes nothing, and `from` with `id` is an error. The art of a graph design in a series keeps its look and is unlinked, as the source or as a linked object. A linked graph series group passes the style to the paths directly in it, a linked Axes group to its lines and labels and a linked Legend group to its labels, other than the source and paths linked to the style whose look was edited, and is left cleared (as appearance.clear) and unlinked. On a linked path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke and the object's opacity and blend mode (exceptions: docs/mcp.md); on a graph label, or a graph's axis line, tick mark or radar ring (a graph's Axes group stands for the lines and labels directly in it, its Legend group for the labels), the graph stores that object's topmost visible fill and stroke rows and object opacity and blend mode for every label or line of its kind → {name}", has_doc, style_redefine ), @@ -489,22 +489,43 @@ pub(crate) fn style_json(g: &GraphicStyle) -> Value { fn style_redefine(s: &mut Session, p: &Value) -> Result { let cmd = "graphicStyle.redefine"; - let (src, n) = source(s, p, cmd)?; - let d = &s.doc()?.doc; - // A series group that holds nothing of its own is redefined from the topmost of its paths, which a style links. - let n = super::appearance::look_holder(d, n); - let src = if n.id == src { src } else { n.id }; - let i = match str_param(p, "name") { - Some(name) => style_index(d, name)?, - None => n - .extras() - .graphic_style - .and_then(|id| d.graphic_style_by_id(id)) - .and_then(|g| d.graphic_style_index(&g.name)) - .ok_or_else(|| bad(cmd, "the object has no graphic style (pass `name`)"))?, + // The style to replace, its new look, and the object that look comes from (none for another style's look). + let (i, look, src) = match p.get("from") { + Some(from) => { + let from = from.as_str().ok_or_else(|| bad(cmd, "`from` must be a graphic style name"))?; + if p.get("id").is_some() { + return Err(bad(cmd, "pass `id` or `from`, not both")); + } + let name = str_param(p, "name").ok_or_else(|| bad(cmd, "missing name (the style `from` replaces)"))?; + let d = &s.doc()?.doc; + let (i, j) = (style_index(d, name)?, style_index(d, from)?); + // A style dropped on itself, or on a style with the same look, stays as it is. + let target = &d.graphic_styles[i]; + let look = GraphicStyle { name: target.name.clone(), id: target.id, ..d.graphic_styles[j].clone() }; + if i == j || look == *target { + return Ok(json!({ "name": name })); + } + (i, look, None) + } + None => { + let (src, n) = source(s, p, cmd)?; + let d = &s.doc()?.doc; + // A series group that holds nothing of its own is redefined from the topmost of its paths, which a style links. + let n = super::appearance::look_holder(d, n); + let src = if n.id == src { src } else { n.id }; + let i = match str_param(p, "name") { + Some(name) => style_index(d, name)?, + None => n + .extras() + .graphic_style + .and_then(|id| d.graphic_style_by_id(id)) + .and_then(|g| d.graphic_style_index(&g.name)) + .ok_or_else(|| bad(cmd, "the object has no graphic style (pass `name`)"))?, + }; + (i, GraphicStyle::of(String::new(), captured(n), n), Some(src)) + } }; - let look = GraphicStyle::of(String::new(), captured(n), n); - let name = d.graphic_styles[i].name.clone(); + let name = s.doc()?.doc.graphic_styles[i].name.clone(); let chars = s.prefs.override_char_color; let before = s.doc()?.doc.clone(); s.edit_named("Redefine Graphic Style “{name}”", &name, false, |d, _| { @@ -513,7 +534,7 @@ fn style_redefine(s: &mut Session, p: &Value) -> Result { // Objects still linked follow the new definition; edited ones are unlinked (they keep their look), and the // source keeps its own. The art of a graph design in a series is unlinked and keeps its look too, as the // source or as a linked object: the graph draws it again from the design. - let linked = objects_where(d, |n| n.extras().graphic_style == Some(id) && n.id != src); + let linked = objects_where(d, |n| n.extras().graphic_style == Some(id) && Some(n.id) != src); let (follow, edited): (Vec, Vec) = linked.into_iter().partition(|nid| !super::graph::is_design_art(d, *nid) && d.node(*nid).is_some_and(|n| in_sync(n, &old))); set_link(d, &edited, None); @@ -521,7 +542,7 @@ fn style_redefine(s: &mut Session, p: &Value) -> Result { // goes back to the empty appearance the graph draws it with. The source and the edited paths keep their look. let mut follow_marks = super::graph::series_group_marks(d, &follow); let edited: HashSet = edited.into_iter().collect(); - follow_marks.retain(|nid| *nid != src && !edited.contains(nid)); + follow_marks.retain(|nid| Some(*nid) != src && !edited.contains(nid)); super::appearance::clear_stood_for(d, &super::appearance::stood_for(&follow, &follow_marks)); let g = d.graphic_styles[i].clone(); let mut shared = None; @@ -530,8 +551,10 @@ fn style_redefine(s: &mut Session, p: &Value) -> Result { } super::appearance::capture_series_writes(&before, d, &follow_marks, (true, true), (true, true), false, true); super::graph::capture_label_rows(d, &follow_marks); - let link = (!super::graph::is_design_art(d, src)).then_some(id); - set_link(d, &[src], link); + if let Some(src) = src { + let link = (!super::graph::is_design_art(d, src)).then_some(id); + set_link(d, &[src], link); + } Ok(()) })?; Ok(json!({ "name": name })) diff --git a/crates/engine/src/cmd/symboledit.rs b/crates/engine/src/cmd/symboledit.rs index 77266b5aaa..a413631bb3 100644 --- a/crates/engine/src/cmd/symboledit.rs +++ b/crates/engine/src/cmd/symboledit.rs @@ -314,12 +314,12 @@ pub(crate) fn follow_history(st: &mut crate::DocState, was: Option<&SymbolEdit>) } } -/// Does `n` hold an instance of symbol `name`, directly or through the art of the symbols it holds -/// instances of? -fn holds_symbol(d: &Document, n: &Node, name: &str, seen: &mut HashSet) -> bool { +/// Does `n` hold an instance of symbol `name` (opacity masks included), directly or through the art +/// of the symbols it holds instances of? +pub(crate) fn holds_symbol(d: &Document, n: &Node, name: &str, seen: &mut HashSet) -> bool { let mut found = false; let mut nested = vec![]; - n.walk(&mut |c| { + vectorcraft_doc::swatches::walk_with_masks(n, &mut |c| { if let NodeKind::SymbolInstance { symbol, .. } = &c.kind { if symbol == name { found = true; diff --git a/crates/engine/src/cmd/textstyles.rs b/crates/engine/src/cmd/textstyles.rs index d544697c5c..11bd1b4259 100644 --- a/crates/engine/src/cmd/textstyles.rs +++ b/crates/engine/src/cmd/textstyles.rs @@ -522,14 +522,16 @@ pub(crate) fn style_attrs(d: &Document, para: bool, name: &str) -> Option vectorcraft_color::Paint { +/// `[Normal Character Style]` in `d`: the defaults, with whatever a redefinition gave it (font, +/// size, fill…). New type starts in that style ([Character and paragraph styles](https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html): +/// every character is in it by default; [FAQs on fonts](https://helpx.adobe.com/illustrator/using/fonts-faq.html) +/// and [Change the default font](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/change-the-default-font-in-illustrator.html): +/// new type's defaults, its font included, are changed by editing it), so it takes this style's +/// font and fill, not the current fill left from the last shape (#7975). Attributes that don't +/// pass its checks leave the defaults. +pub(crate) fn normal_char_style(d: &Document) -> CharStyle { let normal = Kind::Char.attrs(d, NORMAL_CHAR).unwrap_or_default(); - with_attrs(&CharStyle::default(), &normal, "text.create").map_or_else(|_| CharStyle::default().fill, |st| st.fill) + with_attrs(&CharStyle::default(), &normal, "text.create").unwrap_or_default() } /// `attrs` in the form `charStyle.new` (`para`: `paraStyle.new`) stores them in `d`, or `None` diff --git a/crates/engine/src/cmd/threads/tests.rs b/crates/engine/src/cmd/threads/tests.rs index 82ac2f9f76..7e0d790568 100644 --- a/crates/engine/src/cmd/threads/tests.rs +++ b/crates/engine/src/cmd/threads/tests.rs @@ -1991,6 +1991,31 @@ fn frames_made_into_a_symbol_leave_their_thread_with_their_text() { } } +/// New Symbol and Redefine Symbol with `keepArt: true` on a frame of threaded text leave the +/// thread as it was: every frame stays a frame of the thread with the text it holds, and the +/// symbol's art holds a copy of the text the frame shows. +#[test] +fn frames_kept_as_art_by_a_new_or_redefined_symbol_stay_in_their_thread() { + for command in ["symbol.new", "symbol.update"] { + let (mut s, frames) = three_frames(&TEXT.repeat(4), 200.0); + let shown = frames.map(|id| text(&s, id)); + let name = if command == "symbol.update" { + let mark = new_id(s.execute("shape.rectangle", &json!({"x": 400, "y": 200, "width": 20, "height": 20})).unwrap()); + s.execute("select.set", &json!({"ids": [mark]})).unwrap(); + s.execute("symbol.new", &json!({"name": "Mark"})).unwrap(); + "Mark" + } else { + "Story" + }; + s.execute("select.set", &json!({"ids": [frames[1]]})).unwrap(); + let r = s.execute(command, &json!({"name": name, "keepArt": true})).unwrap(); + assert!(r["id"].is_null(), "{command}: {r}"); + assert_eq!(threads(&s), [frames], "{command}: the thread is as it was"); + assert_eq!(frames.map(|id| text(&s, id)), shown, "{command}: each frame keeps its text"); + assert_eq!(symbol_texts(&s, name), [shown[1].clone()], "{command}: the symbol's art holds the text the frame shows"); + } +} + /// A frame of a numbered thread pasted while an opacity mask is edited numbers from 1 in the /// mask art too. #[test] diff --git a/crates/engine/src/cmd/webexport.rs b/crates/engine/src/cmd/webexport.rs index c6764cddb4..897cd87c55 100644 --- a/crates/engine/src/cmd/webexport.rs +++ b/crates/engine/src/cmd/webexport.rs @@ -32,7 +32,7 @@ pub fn specs() -> Vec { "Save for Web", [], None, - "{path?, preset?: a webExport.presets name (its settings, then these keys), format?: gif (default)|jpg|png8|png24, reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray (gif/png8, as the next five), colors?: 128 (2–256), dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, webSnap?: 0 (0–100 %: colours that close to a web-safe one become it), lossy?: 0 (0–100, gif), colorTable?: {locked?: [\"#rrggbb\"…] (kept when reducing), transparent?: [\"#rrggbb\"…] (become transparent), webShift?: [\"#rrggbb\"…] (become web-safe), sort?: none|hue|luminance|popularity} (colours as the preview's colors[].source; #rrggbbaa and #rgba are refused here and in matte), transparency?: true (gif/png8/png24), matte?: white (default)|black|none|\"#rrggbb\" (what edges blend into; jpg and opaque png24: the background), interlaced?: false (gif/png8/png24), quality?: 60 (jpg: 0–100), progressive?: false (jpg), optimized?: true (jpg), embedProfile?: false (jpg: sRGB profile), width?: px | height?: px | percent?: 100 (the image size, proportional; width wins over height, height over percent), antiAlias?: none|art (default)|type, clipToArtboard?: true (the artboard; false: the art and the slices), artboard?: 0 (0-based), convertToSrgb?: true (PNG files say they are sRGB), metadata?: none|copyright (default)|contact|all (File Info written as PNG text, a GIF or JPEG comment), slices?: all (default)|selected|none (one image per slice: images/.), output?: images (default)|html (an HTML page placing the image or slices, .html)} → {path, files: [path…], bytes (total), width, height, warnings: [] or [a note that an image couldn't be decoded and is missing from the image]}; no path → {files: [{name, dataBase64}], bytes, width, height, warnings} (names such as page.html, images/page_01.gif). A single image without HTML is written at path itself", + "{path?, preset?: a webExport.presets name (its settings, then these keys), format?: gif (default)|jpg|png8|png24, reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray (gif/png8, as the next five), colors?: 128 (2–256), dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, webSnap?: 0 (0–100 %: colours that close to a web-safe one become it), lossy?: 0 (0–100, gif), colorTable?: {locked?: [\"#rrggbb\"…] (kept when reducing), transparent?: [\"#rrggbb\"…] (become transparent), webShift?: [\"#rrggbb\"…] (become web-safe), sort?: none|hue|luminance|popularity, deleted?: [\"#rrggbb\"…] (taken out of the table: their pixels take the nearest color left, and at least one color stays), customPalette?: [\"#rrggbb\"…] (a fixed palette used instead of the reduction's, at most `colors` entries; a new reduction without colorTable clears it and deleted)} (colours as the preview's colors[].source; #rrggbbaa and #rgba are refused here and in matte), transparency?: true (gif/png8/png24), matte?: white (default)|black|none|\"#rrggbb\" (what edges blend into; jpg and opaque png24: the background), interlaced?: false (gif/png8/png24), quality?: 60 (jpg: 0–100), progressive?: false (jpg), optimized?: true (jpg), embedProfile?: false (jpg: sRGB profile), width?: px | height?: px | percent?: 100 (the image size, proportional; width wins over height, height over percent), antiAlias?: none|art (default)|type, clipToArtboard?: true (the artboard; false: the art and the slices), artboard?: 0 (0-based), convertToSrgb?: true (PNG files say they are sRGB), metadata?: none|copyright (default)|contact|all (File Info written as PNG text, a GIF or JPEG comment), slices?: all (default)|selected|none (one image per slice: images/.), output?: images (default)|html (an HTML page placing the image or slices, .html)} → {path, files: [path…], bytes (total), width, height, warnings: [] or [a note that an image couldn't be decoded and is missing from the image]}; no path → {files: [{name, dataBase64}], bytes, width, height, warnings} (names such as page.html, images/page_01.gif). A single image without HTML is written at path itself", has_doc, export ), @@ -325,27 +325,39 @@ pub struct ColorTable { pub web_shift: Vec, #[serde(serialize_with = "ser_key", deserialize_with = "de_key")] pub sort: ColorSort, + /// Taken out of the table: their pixels take the nearest color left. A deleted color is no + /// longer locked, transparent or web-shifted. + pub deleted: Vec, + /// A fixed palette (a Custom table) used instead of the reduction's own: the colors of the + /// table when the first color was deleted. Empty: the reduction makes the palette. + pub custom_palette: Vec, } /// The most colours a colour table list holds. const MAX_TABLE: usize = 256; +/// The error for a deletion that would leave the color table no color for the pixels. +pub const KEEP_ONE: &str = "colorTable.deleted: at least one color has to stay in the color table"; + impl ColorTable { + /// Whether the table is a Custom one: a color was deleted or the palette is fixed. + pub fn is_custom(&self) -> bool { + !self.deleted.is_empty() || !self.custom_palette.is_empty() + } + fn colors(list: &[String], what: &str) -> std::result::Result, String> { if list.len() > MAX_TABLE { return Err(format!("colorTable.{what}: at most {MAX_TABLE} colours")); } - list.iter() - .map(|h| { - vectorcraft_color::Color::from_hex(h) - .filter(|_| !super::hex_with_alpha(h)) - .map(|c| { - let [r, g, b, _] = c.to_rgba8(1.0); - [r, g, b] - }) - .ok_or_else(|| format!("colorTable.{what}: `{h}` is not a colour such as \"#ff8800\"")) - }) - .collect() + list.iter().map(|h| Self::rgb(h).ok_or_else(|| format!("colorTable.{what}: `{h}` is not a colour such as \"#ff8800\""))).collect() + } + + /// `h` as RGB; `None` when it is not a color such as `#ff8800`. + fn rgb(h: &str) -> Option<[u8; 3]> { + vectorcraft_color::Color::from_hex(h).filter(|_| !super::hex_with_alpha(h)).map(|c| { + let [r, g, b, _] = c.to_rgba8(1.0); + [r, g, b] + }) } } @@ -445,7 +457,13 @@ impl WebSettings { } } } - let s: WebSettings = serde_json::from_value(v).map_err(|e| format!("Save for Web settings: {e}"))?; + let mut s: WebSettings = serde_json::from_value(v).map_err(|e| format!("Save for Web settings: {e}"))?; + // Another reduction makes a new palette: the deletions and the fixed palette go, unless + // the params give the color table too. + if p.get("reduction").is_some() && p.get("colorTable").is_none() && s.reduction != self.reduction { + s.color_table.deleted.clear(); + s.color_table.custom_palette.clear(); + } s.checked() } @@ -463,11 +481,19 @@ impl WebSettings { return Err("width and height are at least 1 pixel".into()); } self.matte_rgb()?; + let table = &mut self.color_table; for (list, what) in - [(&self.color_table.locked, "locked"), (&self.color_table.transparent, "transparent"), (&self.color_table.web_shift, "webShift")] + [(&table.locked, "locked"), (&table.transparent, "transparent"), (&table.web_shift, "webShift"), (&table.custom_palette, "customPalette")] { ColorTable::colors(list, what)?; } + // A deleted color is no longer locked, transparent or web-shifted. + let deleted = ColorTable::colors(&table.deleted, "deleted")?; + if !deleted.is_empty() { + for list in [&mut table.locked, &mut table.transparent, &mut table.web_shift] { + list.retain(|h| ColorTable::rgb(h).is_none_or(|c| !deleted.contains(&c))); + } + } Ok(self) } @@ -741,7 +767,7 @@ fn palette_image(rgba: &[u8], w: u32, h: u32, s: &WebSettings, matte: Option<[u8 transparency: s.transparency, matte, }; - let mut ix = quantize::quantize_locked(rgba, w, h, &o, &locked); + let mut ix = reduced(rgba, w, h, s, &o, &locked)?; // Map to transparent works on the colours the reduction made. let before = ix.palette.clone(); let clear = ix.transparent.map(usize::from); @@ -789,6 +815,45 @@ fn palette_image(rgba: &[u8], w: u32, h: u32, s: &WebSettings, matte: Option<[u8 Ok(PaletteImage { ix, colors, mapped }) } +/// The pixels reduced to the palette `s` gives: the reduction's own (`locked` kept), or the +/// color table's fixed one, without the deleted colors. The pixels of a deleted color take the +/// nearest color left, with `o`'s dither. A deletion has to leave a color that is not mapped to +/// transparent. +fn reduced(rgba: &[u8], w: u32, h: u32, s: &WebSettings, o: &PaletteOptions, locked: &[[u8; 3]]) -> std::result::Result { + let table = &s.color_table; + let deleted = ColorTable::colors(&table.deleted, "deleted")?; + let custom = ColorTable::colors(&table.custom_palette, "customPalette")?; + let to_clear = ColorTable::colors(&table.transparent, "transparent")?; + let opaque_left = |left: &[[u8; 3]]| left.iter().any(|c| !to_clear.contains(c)); + if custom.is_empty() { + let ix = quantize::quantize_locked(rgba, w, h, o, locked); + let clear = ix.transparent.map(usize::from); + let gone = |i: usize, c: &[u8; 3]| Some(i) != clear && deleted.contains(c); + if !ix.palette.iter().enumerate().any(|(i, c)| gone(i, c)) { + return Ok(ix); + } + let left: Vec<[u8; 3]> = ix.palette.iter().enumerate().filter(|&(i, c)| Some(i) != clear && !deleted.contains(c)).map(|(_, c)| *c).collect(); + if left.is_empty() || !opaque_left(&left) { + return Err(KEEP_ONE.into()); + } + return Ok(quantize::quantize_to(rgba, w, h, o, &left)); + } + // A fixed palette holds at most `colors` entries, the transparent one included. + let has_clear = s.transparency && rgba.as_chunks::<4>().0.iter().any(|p| p[3] < 128); + let removed = custom.iter().any(|c| deleted.contains(c)); + let mut left: Vec<[u8; 3]> = vec![]; + for c in custom { + if !deleted.contains(&c) && !left.contains(&c) { + left.push(c); + } + } + left.truncate(usize::from(s.colors.clamp(2, 256)) - usize::from(has_clear)); + if left.is_empty() || (removed && !opaque_left(&left)) { + return Err(KEEP_ONE.into()); + } + Ok(quantize::quantize_to(rgba, w, h, o, &left)) +} + /// An optimised image as straight RGBA → `(pixels, width, height)` (the dialog's preview). pub fn decode(o: &Optimized) -> std::result::Result<(Vec, u32, u32), String> { let img = craft_image_codecs::decode(o.display()).map_err(|e| format!("the optimised image can't be read back: {e}"))?; diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 7e2f995e94..de780f406c 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -415,7 +415,7 @@ use history::history_budget_for; pub use history::{History, HistoryEntry, NamedStep, default_history_budget}; pub(crate) use interaction::PreviewCopies; pub use interaction::{Interaction, LastTransform, UndoGroup, UndoScope}; -pub use prefs::{DrawMode, Prefs}; +pub use prefs::{DrawMode, PluginBudget, Prefs}; pub use sanity::TOO_DEEP; pub(crate) use sanity::{deselect_hidden, is_guide_path}; #[cfg(test)] diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index ebee8b6e77..6d044eace3 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -10,6 +10,26 @@ pub enum DrawMode { Inside, } +/// Plug-ins & Scratch Disks › Plug-in Instruction Budget: the instructions an object filter's run +/// may use ([`vectorcraft_plugins::Plugin::large_limits`]). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize)] +#[serde(rename_all = "lowercase")] +pub enum PluginBudget { + /// The plug-in's own limits. + #[default] + Normal, + /// At least [`vectorcraft_plugins::LARGE_FUEL`] instructions besides those for each byte of + /// input; the time budget is unchanged. + Large, +} + +/// A saved Plug-in Instruction Budget: any value but `large`, of any type, reads as Normal, and the +/// other preferences are read as they are. +fn plugin_budget<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result { + let saved = ::deserialize(d)?; + Ok(if saved.as_str() == Some("large") { PluginBudget::Large } else { PluginBudget::Normal }) +} + /// A saved Default Language as its tag: older preferences hold the language's name, and one the list /// no longer has reads as the default. fn language_tag<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result { @@ -29,6 +49,12 @@ pub struct Prefs { pub constrain_angle: f64, pub corner_radius: f64, pub disable_auto_add_delete: bool, + /// General › Interpolate Control Points When Moving Anchors: the default of the `interpolate` + /// param of the commands that move direct-selected anchors (a Direct Selection drag, the arrow + /// keys, Move, Transform Again). On, the handles of each segment with one moved end are + /// re-mapped by the turn, scale and move that take its old ends to its new ends. Off (the + /// default), the handles of a moved anchor move with it and the other handles stay. + pub interpolate_control_points: bool, pub use_precise_cursors: bool, pub show_tool_tips: bool, /// Other Script… warns before it runs a chosen script. @@ -173,6 +199,11 @@ pub struct Prefs { pub fonts_folder: String, // Plug-ins & Scratch Disks pub plugins_folder: String, + /// Plug-in Instruction Budget: the instructions each object filter run gets, from + /// `plugin.run`, a plug-in command and the app alike. Live effects, exporters and importers + /// keep their own budgets. + #[serde(deserialize_with = "plugin_budget")] + pub plugin_instruction_budget: PluginBudget, pub scratch_primary: String, pub scratch_secondary: String, // User Interface @@ -397,6 +428,7 @@ impl Default for Prefs { constrain_angle: 0.0, corner_radius: 12.0, disable_auto_add_delete: false, + interpolate_control_points: false, use_precise_cursors: false, show_tool_tips: true, show_external_script_warning: true, @@ -489,6 +521,7 @@ impl Default for Prefs { hyphenation_exceptions: String::new(), fonts_folder: String::new(), plugins_folder: String::new(), + plugin_instruction_budget: PluginBudget::Normal, scratch_primary: s("Startup"), scratch_secondary: s("None"), ui_brightness: s("mediumDark"), diff --git a/crates/engine/src/session/edit.rs b/crates/engine/src/session/edit.rs index ed4aa0e105..ce0c2998fe 100644 --- a/crates/engine/src/session/edit.rs +++ b/crates/engine/src/session/edit.rs @@ -442,8 +442,10 @@ impl Session { // selected): Transform Again moves the selected anchors and the objects selected whole // by the same distance. A drag that ends where it began leaves the last transform. let mut options = serde_json::json!({ "copy": false }); - if let Some(patterns) = preview.1.get("patterns") { - options["patterns"] = patterns.clone(); + for key in ["patterns", "interpolate"] { + if let Some(v) = preview.1.get(key) { + options[key] = v.clone(); + } } st.last_transform = Some(LastTransform::Matrix(vectorcraft_geom::Affine::translate(moved), options)); st.last_perspective = None; diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 3e3a3c5a83..1f118b31a3 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -85,6 +85,7 @@ mod history_mem; mod ids_without_selection; mod inline; mod interactivity; +mod interpolate_handles; mod intertwine; mod journal; mod keyanchor; @@ -3219,6 +3220,101 @@ fn every_command_has_unique_id_and_doc() { assert!(command_specs().iter().all(|c| !c.params.is_empty() && !c.label.is_empty())); } +/// Ids that name no built-in command: commands only the app runs, near misses of real ids and +/// plug-in command ids of plug-ins that are not installed. +const NOT_BUILT_IN: &[&str] = + &["", "file.save", "file.open", "edit.preferences", "select", "select.none.", "SELECT.NONE", " select.none", "plugin.nobody.cmd", "plugin."]; + +/// The spec a search of the built-in list in order finds for `id`. +fn first_built_in(id: &str) -> Option<&'static CommandSpec> { + command_specs().iter().find(|c| c.id == id) +} + +#[test] +fn find_command_finds_the_spec_a_search_of_the_list_finds() { + let misses: Vec = NOT_BUILT_IN.iter().map(|id| (*id).to_string()).chain((0..200).map(|i| format!("missing.command{i}"))).collect(); + for id in command_specs().iter().map(|c| c.id.to_string()).chain(misses) { + let (found, first) = (find_command(&id), first_built_in(&id)); + assert!(found.map(std::ptr::from_ref) == first.map(std::ptr::from_ref), "{id:?}"); + assert_eq!(found.is_none(), NOT_BUILT_IN.contains(&id.as_str()) || id.starts_with("missing."), "{id:?}"); + } +} + +#[test] +fn the_command_index_keeps_the_first_spec_of_an_id() { + let base = &command_specs()[0]; + let specs = [ + CommandSpec { id: "test.twice", label: "First", ..*base }, + CommandSpec { id: "test.once", ..*base }, + CommandSpec { id: "test.twice", label: "Second", ..*base }, + ]; + let index = crate::cmd::index_by_id(&specs); + assert_eq!(index.len(), 2); + assert!(index.get("test.twice").is_some_and(|c| std::ptr::eq(*c, &specs[0]))); + assert!(index.get("test.once").is_some_and(|c| std::ptr::eq(*c, &specs[1]))); + assert!(!index.contains_key("test.none")); +} + +/// Times [`find_command`] against a search of the built-in list in order (the lookup before the +/// index), in one process, over every built-in id and 200 ids that name no command, and +/// `select.none` run 100,000 times on a document with one rectangle. +/// Run with `cargo test --release -p vectorcraft-engine --lib command_lookup_timing -- --ignored --nocapture`. +#[test] +#[ignore = "manual timing probe; wall-clock performance depends on machine load"] +fn command_lookup_timing() { + use std::hint::black_box; + use std::time::Instant; + let hits: Vec<&str> = command_specs().iter().map(|c| c.id).collect(); + let missing: Vec = (0..200 - NOT_BUILT_IN.len()).map(|i| format!("missing.command{i}")).collect(); + let misses: Vec<&str> = NOT_BUILT_IN.iter().copied().chain(missing.iter().map(String::as_str)).collect(); + let linear = |id: &str| first_built_in(id).or_else(|| crate::cmd::plugin::find_spec(id)); + for id in hits.iter().chain(&misses) { + assert!(find_command(id).map(std::ptr::from_ref) == linear(id).map(std::ptr::from_ref), "{id:?}"); + } + let per_lookup = |ids: &[&str], f: &dyn Fn(&str) -> Option<&'static CommandSpec>| { + let rounds = 50; + let start = Instant::now(); + for _ in 0..rounds { + for id in ids { + black_box(f(black_box(id))); + } + } + start.elapsed().as_nanos() as f64 / (rounds * ids.len()) as f64 + }; + let median = |mut v: Vec| { + v.sort_by(f64::total_cmp); + v[v.len() / 2] + }; + println!("{} built-in ids, {} ids that name no command", hits.len(), misses.len()); + for (what, ids) in [("built-in id", &hits), ("no such command", &misses)] { + let (mut old, mut new) = (Vec::new(), Vec::new()); + for run in 0..7 { + // Alternates which lookup goes first, so a change in machine load falls on both. + if run % 2 == 0 { + old.push(per_lookup(ids, &linear)); + new.push(per_lookup(ids, &find_command)); + } else { + new.push(per_lookup(ids, &find_command)); + old.push(per_lookup(ids, &linear)); + } + } + println!("{what}: search of the list {old:.0?} ns, median {:.0}; index {new:.0?} ns, median {:.0}", median(old.clone()), median(new.clone())); + } + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 200})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap(); + let runs: Vec = (0..7) + .map(|_| { + let start = Instant::now(); + for _ in 0..100_000 { + black_box(s.execute("select.none", &json!({})).unwrap()); + } + start.elapsed().as_nanos() as f64 / 100_000.0 + }) + .collect(); + println!("select.none: {runs:.0?} ns a command, median {:.0}", median(runs.clone())); +} + #[test] fn every_command_survives_empty_params() { // Robustness: no command may panic on {} (with and without a selection). diff --git a/crates/engine/src/tests/brushsym.rs b/crates/engine/src/tests/brushsym.rs index d8bfed74d8..3a3a07a2c1 100644 --- a/crates/engine/src/tests/brushsym.rs +++ b/crates/engine/src/tests/brushsym.rs @@ -1697,6 +1697,46 @@ fn brush_options_set_variation_modes() { assert_eq!(s.execute("brush.get", &json!({"name": "Dots"})).unwrap()["modes"], modes); } +/// The fill colors of the copies brushed path `id` draws in `doc`, as `#rrggbb`. +fn piece_fills(doc: &Document, id: NodeId) -> Vec { + let pieces = vectorcraft_brush::node_pieces(doc, doc.node(id).unwrap()).expect("brushed"); + pieces.iter().map(|n| n.appearance.fill_paint().color().unwrap().to_hex()).collect() +} + +/// Scatter Brush Options' `hue_jitter`: shown by `brush.get`, set by `brush.options`, saved with the +/// document, and the turned colors drawn the same after Open and written by SVG export. +#[test] +fn scatter_hue_jitter_saves_and_exports() { + let mut s = session(); + let r = rect(&mut s, 10.0, 200.0, 8.0, 8.0); + s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap(); + let name = s.execute("brush.new", &json!({"type": "scatter", "name": "Confetti", "ids": [r.0]})).unwrap()["name"].as_str().unwrap().to_string(); + let id = line(&mut s); + select(&mut s, &[id]); + s.execute("brush.apply", &json!({ "name": name })).unwrap(); + let plain = piece_fills(&s.doc().unwrap().doc, id); + assert!(plain.len() > 10 && plain.iter().all(|c| c == "#ff0000"), "{plain:?}"); + assert_eq!(s.execute("brush.get", &json!({ "name": name })).unwrap()["hue_jitter"], json!(0.0), "brush.get shows the option at 0"); + s.execute("brush.options", &json!({"name": name, "params": {"hue_jitter": 120}})).unwrap(); + assert_eq!(s.execute("brush.get", &json!({ "name": name })).unwrap()["hue_jitter"], json!(120.0)); + let doc = s.doc().unwrap().doc.clone(); + let turned = piece_fills(&doc, id); + assert_eq!(turned.len(), plain.len()); + let distinct: std::collections::HashSet<&String> = turned.iter().collect(); + assert!(distinct.len() > 5, "{turned:?}"); + // Saved and opened again, the stroke draws the same colors. + let back = vectorcraft_format::load(&vectorcraft_format::save(&doc, false)).unwrap(); + assert_eq!(piece_fills(&back, id), turned); + // SVG export writes each copy's turned color. + let svg = vectorcraft_svg::export(&doc, &Default::default()); + for c in &distinct { + assert!(svg.contains(&format!("fill=\"{c}\"")), "{c} missing from the SVG"); + } + // Back to 0, the copies draw the art's own color. + s.execute("brush.options", &json!({"name": name, "params": {"hue_jitter": 0}})).unwrap(); + assert_eq!(piece_fills(&s.doc().unwrap().doc, id), plain); +} + /// The bounds of the brush art `id`'s strokes draw. fn brushed_bounds(s: &Session, id: NodeId) -> Rect { let st = s.doc().unwrap(); @@ -2159,6 +2199,212 @@ fn break_link_then_update_redefines_all_instances() { assert!((bounds(&s, other).center().x - 300.0).abs() < 1e-6); } +/// Redefine Symbol with `keepArt: true` updates the symbol and its instances from the selection, +/// and the selected art stays ordinary art in its place, with its ids, still selected; the result +/// has no instance id. One undo step takes the definition back. Without `keepArt`, or with false, +/// the art becomes an instance. +#[test] +fn redefine_with_keep_art_leaves_the_art_as_ordinary_art() { + let mut s = session(); + let (inst, name, _) = make_symbol(&mut s); + let a = rect(&mut s, 20.0, 200.0, 60.0, 30.0); + let b = rect(&mut s, 100.0, 200.0, 40.0, 50.0); + let spot = |s: &Session, id: NodeId| s.doc().unwrap().doc.position(id).map(|(p, i, _)| (p, i)); + let before = (node(&s, a), node(&s, b), spot(&s, a), spot(&s, b)); + let symbol_art = |s: &Session| s.doc().unwrap().doc.symbols.iter().find(|x| x.name == name).map(|x| x.art.clone()).unwrap(); + let old_art = symbol_art(&s); + let steps = s.doc().unwrap().history.undo.len(); + select(&mut s, &[a, b]); + let r = s.execute("symbol.update", &json!({"name": name, "keepArt": true})).unwrap(); + assert_eq!(r, json!({"name": name, "id": null})); + assert_eq!((node(&s, a), node(&s, b), spot(&s, a), spot(&s, b)), before, "the art is unchanged and in its place"); + assert_eq!(s.doc().unwrap().selection.objects, vec![a, b], "the art stays selected"); + let instances = |s: &Session| { + let mut n = 0; + s.doc().unwrap().doc.walk(|c| n += usize::from(matches!(c.kind, NodeKind::SymbolInstance { .. }))); + n + }; + assert_eq!(instances(&s), 1, "no new instance"); + // The instance shows the new art: the 120 × 50 pair. + let w = bounds(&s, inst); + assert!((w.width() - 120.0).abs() < 1e-6 && (w.height() - 50.0).abs() < 1e-6, "{w:?}"); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(symbol_art(&s), old_art, "undo takes the definition back"); + s.execute("edit.redo", &json!({})).unwrap(); + assert!((bounds(&s, inst).width() - 120.0).abs() < 1e-6, "{:?}", bounds(&s, inst)); + // false, like no keepArt, makes the art an instance. + for p in [json!({"name": name, "ids": [a.0], "keepArt": false}), json!({"name": name, "ids": [b.0]})] { + let r = s.execute("symbol.update", &p).unwrap(); + let id = NodeId(r["id"].as_u64().expect("an instance id")); + assert!(matches!(node(&s, id).kind, NodeKind::SymbolInstance { .. }), "{p}"); + assert_eq!(s.doc().unwrap().selection.objects, vec![id], "{p}"); + } + assert!(s.doc().unwrap().doc.node(a).is_none() && s.doc().unwrap().doc.node(b).is_none()); +} + +/// Redefine Symbol with `keepArt: true` and explicit ids keeps the named art selected only where +/// it can be selected: locked or hidden art is left out. A `keepArt` that is not true or false is +/// refused, with no change and no undo step. +#[test] +fn redefine_with_keep_art_selects_only_selectable_art_and_refuses_a_bad_switch() { + let mut s = session(); + let (_, name, _) = make_symbol(&mut s); + let a = rect(&mut s, 20.0, 200.0, 60.0, 30.0); + let locked = rect(&mut s, 100.0, 200.0, 40.0, 50.0); + let hidden = rect(&mut s, 200.0, 200.0, 40.0, 50.0); + { + let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + doc.node_mut(locked).unwrap().locked = true; + doc.node_mut(hidden).unwrap().visible = false; + } + for bad in [json!("true"), json!(1), json!([true])] { + let before = s.doc().unwrap().doc.clone(); + let steps = s.doc().unwrap().history.undo.len(); + let e = s.execute("symbol.update", &json!({"name": name, "ids": [a.0], "keepArt": bad})).unwrap_err(); + assert!(e.to_string().contains("`keepArt` must be true or false"), "{bad}: {e}"); + assert!(std::sync::Arc::ptr_eq(&before, &s.doc().unwrap().doc), "{bad}: the document is unchanged"); + assert_eq!(s.doc().unwrap().history.undo.len(), steps, "{bad}: no undo step"); + } + select(&mut s, &[]); + s.execute("symbol.update", &json!({"name": name, "ids": [a.0, locked.0, hidden.0], "keepArt": true})).unwrap(); + assert_eq!(s.doc().unwrap().selection.objects, vec![a], "only the selectable art is selected"); + for id in [a, locked, hidden] { + assert!(matches!(node(&s, id).kind, NodeKind::Path { .. }), "{id:?} stays ordinary art"); + } +} + +/// The number of symbol instances in the document. +fn instance_count(s: &Session) -> usize { + let mut n = 0; + s.doc().unwrap().doc.walk(|c| n += usize::from(matches!(c.kind, NodeKind::SymbolInstance { .. }))); + n +} + +/// New Symbol with `keepArt: true` makes a symbol of the selection and makes it the current +/// symbol, and the selected art stays ordinary art in its place, with its ids, still selected; the +/// result has no instance id and nothing places the symbol. One undo step takes the symbol away +/// and redo makes it again. Without `keepArt`, or with false, the art becomes an instance. +#[test] +fn new_symbol_with_keep_art_leaves_the_art_as_ordinary_art() { + let mut s = session(); + let a = rect(&mut s, 20.0, 200.0, 60.0, 30.0); + let b = rect(&mut s, 100.0, 200.0, 40.0, 50.0); + let spot = |s: &Session, id: NodeId| s.doc().unwrap().doc.position(id).map(|(p, i, _)| (p, i)); + let before = (node(&s, a), node(&s, b), spot(&s, a), spot(&s, b)); + let steps = s.doc().unwrap().history.undo.len(); + select(&mut s, &[a, b]); + let r = s.execute("symbol.new", &json!({"name": "Kept", "keepArt": true})).unwrap(); + assert_eq!((&r["name"], &r["id"]), (&json!("Kept"), &Value::Null), "{r}"); + assert_eq!((node(&s, a), node(&s, b), spot(&s, a), spot(&s, b)), before, "the art is unchanged and in its place"); + assert_eq!(s.doc().unwrap().selection.objects, vec![a, b], "the art stays selected"); + assert_eq!(instance_count(&s), 0, "no instance"); + let list = s.execute("symbol.list", &json!({})).unwrap(); + assert_eq!((&list["current"], &list["symbols"][0]["name"], &list["symbols"][0]["instances"]), (&json!("Kept"), &json!("Kept"), &json!(0))); + // The symbol's art is the pair: an instance placed from it is 120 × 50. + let placed = NodeId(s.execute("symbol.place", &json!({"name": "Kept"})).unwrap()["id"].as_u64().unwrap()); + let w = bounds(&s, placed); + assert!((w.width() - 120.0).abs() < 1e-6 && (w.height() - 50.0).abs() < 1e-6, "{w:?}"); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "New Symbol is one undo step"); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.doc().unwrap().doc.symbols.is_empty(), "undo takes the symbol away"); + assert_eq!((node(&s, a), node(&s, b)), (before.0.clone(), before.1.clone()), "and leaves the art"); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(s.execute("symbol.list", &json!({})).unwrap()["current"], json!("Kept"), "redo"); + assert_eq!(instance_count(&s), 0, "redo places no instance"); + // false, like no keepArt, makes the art an instance. + for p in [json!({"name": "Plain", "ids": [a.0], "keepArt": false}), json!({"name": "Plain", "ids": [b.0]})] { + let r = s.execute("symbol.new", &p).unwrap(); + let id = NodeId(r["id"].as_u64().expect("an instance id")); + assert!(matches!(node(&s, id).kind, NodeKind::SymbolInstance { .. }), "{p}"); + assert_eq!(s.doc().unwrap().selection.objects, vec![id], "{p}"); + } + assert!(s.doc().unwrap().doc.node(a).is_none() && s.doc().unwrap().doc.node(b).is_none()); +} + +/// New Symbol with `keepArt: true` and explicit ids keeps the named art selected only where it +/// can be selected: locked or hidden art is left out. A symbol instance in the art stays the +/// instance it was. A `keepArt` that is not true or false is refused, with no symbol, no change and +/// no undo step. +#[test] +fn new_symbol_with_keep_art_selects_only_selectable_art_and_refuses_a_bad_switch() { + let mut s = session(); + let (inst, _, _) = make_symbol(&mut s); + let a = rect(&mut s, 20.0, 200.0, 60.0, 30.0); + let locked = rect(&mut s, 100.0, 200.0, 40.0, 50.0); + let hidden = rect(&mut s, 200.0, 200.0, 40.0, 50.0); + { + let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + doc.node_mut(locked).unwrap().locked = true; + doc.node_mut(hidden).unwrap().visible = false; + } + for bad in [json!("true"), json!(1), json!([true])] { + let before = s.doc().unwrap().doc.clone(); + let steps = s.doc().unwrap().history.undo.len(); + let e = s.execute("symbol.new", &json!({"name": "Bad", "ids": [a.0], "keepArt": bad})).unwrap_err(); + assert!(e.to_string().contains("`keepArt` must be true or false"), "{bad}: {e}"); + assert!(std::sync::Arc::ptr_eq(&before, &s.doc().unwrap().doc), "{bad}: the document is unchanged"); + assert_eq!(s.doc().unwrap().history.undo.len(), steps, "{bad}: no undo step"); + } + select(&mut s, &[]); + let symbols = s.doc().unwrap().doc.symbols.len(); + let ids = [a.0, locked.0, hidden.0, inst.0]; + s.execute("symbol.new", &json!({"name": "Kept", "ids": ids, "keepArt": true})).unwrap(); + assert_eq!(s.doc().unwrap().doc.symbols.len(), symbols + 1); + let selected = &s.doc().unwrap().selection.objects; + assert!(selected.len() == 2 && selected.contains(&a) && selected.contains(&inst), "only the selectable art is selected: {selected:?}"); + for id in [a, locked, hidden] { + assert!(matches!(node(&s, id).kind, NodeKind::Path { .. }), "{id:?} stays ordinary art"); + } + assert!(matches!(node(&s, inst).kind, NodeKind::SymbolInstance { .. }), "the instance stays an instance"); + assert_eq!(instance_count(&s), 1, "no new instance"); +} + +/// Redefine Symbol refuses art that holds an instance of the symbol it redefines, directly, in a +/// group, in an opacity mask, or through the art of another symbol it holds an instance of, and +/// then changes nothing and adds no undo step. An instance of an unrelated symbol still redefines +/// it. +#[test] +fn redefine_refuses_art_holding_an_instance_of_the_symbol() { + let mut s = session(); + let (inst, name, _) = make_symbol(&mut s); + // Ring's art is an instance of Box. + let ring = NodeId(s.execute("symbol.new", &json!({"name": "Ring", "ids": [inst.0]})).unwrap()["id"].as_u64().unwrap()); + let place = + |s: &mut Session, x: f64| NodeId(s.execute("symbol.place", &json!({"name": name, "x": x, "y": 200})).unwrap()["id"].as_u64().unwrap()); + let direct = place(&mut s, 300.0); + let plain = rect(&mut s, 20.0, 220.0, 30.0, 30.0); + let grouped = place(&mut s, 100.0); + // A rectangle whose opacity mask is a Box instance. + let masked = rect(&mut s, 60.0, 260.0, 30.0, 30.0); + let mut mask_art = node(&s, direct); + let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + mask_art.id = doc.alloc_id(); + doc.node_mut(masked).unwrap().extras_mut().mask = Some(Box::new(vectorcraft_doc::OpacityMask::new(mask_art, true))); + let cases = [ + ("a Box instance", vec![direct.0]), + ("Ring, whose art holds Box", vec![ring.0]), + ("art with a Box instance", vec![plain.0, grouped.0]), + ("art masked by a Box instance", vec![masked.0]), + ]; + for (case, ids) in cases { + let before = s.doc().unwrap().doc.clone(); + let undo = s.doc().unwrap().history.undo.len(); + let e = s.execute("symbol.update", &json!({"name": name, "ids": ids})).unwrap_err(); + assert!(e.to_string().contains("can't hold an instance of itself"), "{case}: {e}"); + assert!(std::sync::Arc::ptr_eq(&before, &s.doc().unwrap().doc), "{case}: the document is unchanged"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo, "{case}: no undo step"); + } + // An instance of a symbol that does not hold Box redefines it. + let dot = rect(&mut s, 200.0, 20.0, 10.0, 10.0); + let dot = NodeId(s.execute("symbol.new", &json!({"name": "Dot", "ids": [dot.0]})).unwrap()["id"].as_u64().unwrap()); + let r = s.execute("symbol.update", &json!({"name": name, "ids": [dot.0]})).unwrap(); + assert_eq!(r["name"], json!(name)); + let art = s.doc().unwrap().doc.symbols.iter().find(|x| x.name == name).map(|x| x.art.clone()).unwrap(); + assert!(matches!(&art.kind, NodeKind::SymbolInstance { symbol, .. } if symbol == "Dot"), "{}", art.kind_label()); +} + /// A linked opacity mask of a 10 × 10 square at (100, 50). fn square_mask(s: &mut Session) -> Box { let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); diff --git a/crates/engine/src/tests/expand.rs b/crates/engine/src/tests/expand.rs index 4e8d8697d4..e728754655 100644 --- a/crates/engine/src/tests/expand.rs +++ b/crates/engine/src/tests/expand.rs @@ -387,22 +387,79 @@ fn a_fill_effect_reshapes_the_fill_of_a_group_in_the_art() { assert!(differing(&before, &after, 8) < 200, "expanding changed {} pixels", differing(&before, &after, 8)); } +/// An image whose fill Convert to Shape gives a shape, selected. The frame runs from 85 to 115; +/// the fill's shape is 9 pt larger on each side. +fn image_with_shaped_fill(s: &mut Session) -> NodeId { + let mut png = vec![]; + image::RgbaImage::from_pixel(30, 30, image::Rgba([255, 0, 0, 255])) + .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) + .unwrap(); + let r = run(s, "file.place", json!({"name": "red.png", "dataBase64": vectorcraft_format::base64_encode(&png), "at": [100, 100]})); + let im = NodeId(r["ids"][0].as_u64().unwrap()); + run(s, "select.set", json!({"ids": [im.0]})); + run(s, "appearance.addFill", json!({})); + run(s, "paint.setFill", json!({"color": "#0000ff", "item": 0})); + run(s, "effect.apply", json!({"effect": "convertToShape.rectangle", "item": 0})); + im +} + +/// The objects a marquee from `x0` to `x1` across y = 100 touches, as the canvas shows them, in +/// outline with `outline`. +fn marquee_at(s: &Session, x0: f64, x1: f64, outline: bool) -> Vec { + let r = vectorcraft_geom::Rect::new(x0, 90.0, x1, 110.0); + vectorcraft_doc::hit::marquee_in_view(&s.doc().unwrap().doc, r, None, true, outline) +} + +/// A marquee touches a symbol instance where the geometry effects of its fill or stroke paint its +/// art outside its box, as a click there selects it, except in outline. +#[test] +fn a_marquee_where_a_symbol_instance_fill_or_stroke_effect_paints_selects_it() { + let mut s = session(); + let (id, row) = instance_with_row(&mut s, "Square", true); + assert_eq!(marquee_at(&s, 38.0, 45.0, false), []); + offset_row(&mut s, id, row, 10.0); + assert_eq!(marquee_at(&s, 38.0, 45.0, false), [id], "a marquee across the grown fill"); + assert_eq!(marquee_at(&s, 30.0, 37.0, false), [], "a marquee past the grown fill"); + assert_eq!(marquee_at(&s, 38.0, 45.0, true), [], "outline mode draws the art as it is"); + + let mut s = session(); + let (id, row) = instance_with_row(&mut s, "Square", false); + offset_row(&mut s, id, row, 10.0); + assert_eq!(marquee_at(&s, 38.0, 42.0, false), [id], "a marquee across the moved stroke"); + assert_eq!(marquee_at(&s, 43.0, 45.0, false), [], "a marquee between the moved stroke and the fill"); + + let mut s = session(); + let (id, row) = nested_instance_with_row(&mut s); + offset_row(&mut s, id, row, 10.0); + assert_eq!(marquee_at(&s, 38.0, 45.0, false), [id], "a marquee across the grown fill of the nested art"); +} + +/// A marquee touches an image where the shape of its own fill lies outside its frame, and an +/// instance of a symbol made of that image where the instance's fill effect grows that shape, as +/// clicks there select them, except in outline. +#[test] +fn a_marquee_on_the_shape_of_an_image_fill_selects_it() { + let mut s = session(); + let im = image_with_shaped_fill(&mut s); + assert_eq!(marquee_at(&s, 74.0, 79.0, false), [im], "a marquee across the fill's shape outside the frame"); + assert_eq!(marquee_at(&s, 70.0, 75.0, false), [], "a marquee past the fill's shape"); + assert_eq!(marquee_at(&s, 74.0, 79.0, true), [], "outline mode draws the frame"); + + let id = NodeId(run(&mut s, "symbol.new", json!({"name": "Image"}))["id"].as_u64().unwrap()); + run(&mut s, "appearance.addFill", json!({"ids": [id.0]})); + let row = node(&s, id).appearance.items.len() - 1; + run(&mut s, "appearance.setItem", json!({"ids": [id.0], "index": row, "none": true})); + offset_row(&mut s, id, row, 10.0); + assert_eq!(marquee_at(&s, 64.0, 68.0, false), [id], "a marquee across the instance's grown fill"); + assert_eq!(marquee_at(&s, 58.0, 63.0, false), [], "a marquee past the grown fill"); +} + /// An image in the symbol's art whose fill Convert to Shape gives a shape: the instance's fill /// effect grows what that fill paints, and a click there selects the instance. #[test] fn a_click_on_the_grown_fill_of_an_image_in_the_art_selects_the_instance() { let mut s = session(); - let mut png = vec![]; - image::RgbaImage::from_pixel(30, 30, image::Rgba([255, 0, 0, 255])) - .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) - .unwrap(); - // The frame runs from 85 to 115; the fill's shape is 9 pt larger on each side. - let r = run(&mut s, "file.place", json!({"name": "red.png", "dataBase64": vectorcraft_format::base64_encode(&png), "at": [100, 100]})); - let im = NodeId(r["ids"][0].as_u64().unwrap()); - run(&mut s, "select.set", json!({"ids": [im.0]})); - run(&mut s, "appearance.addFill", json!({})); - run(&mut s, "paint.setFill", json!({"color": "#0000ff", "item": 0})); - run(&mut s, "effect.apply", json!({"effect": "convertToShape.rectangle", "item": 0})); + image_with_shaped_fill(&mut s); let id = NodeId(run(&mut s, "symbol.new", json!({"name": "Image"}))["id"].as_u64().unwrap()); run(&mut s, "appearance.addFill", json!({"ids": [id.0]})); let row = node(&s, id).appearance.items.len() - 1; diff --git a/crates/engine/src/tests/interpolate_handles.rs b/crates/engine/src/tests/interpolate_handles.rs new file mode 100644 index 0000000000..158eb6a5fb --- /dev/null +++ b/crates/engine/src/tests/interpolate_handles.rs @@ -0,0 +1,522 @@ +//! #7832: General › Interpolate Control Points When Moving Anchors (`interpolateControlPoints`). +//! With it on, a Direct Selection drag or an arrow-key nudge of selected anchors re-maps the +//! handles of each segment with one moved end, so the segment keeps its shape relative to its +//! ends. Off (the default), the handles of a moved anchor move with it and the others stay. + +use serde_json::json; +use vectorcraft_geom::{Anchor, PathData, Point}; +use vectorcraft_tools::{PointerEvent, PointerKind}; + +use super::history; +use crate::*; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap(); + s +} + +fn interpolate(s: &mut Session, on: bool) { + s.execute("prefs.set", &json!({"key": "interpolateControlPoints", "value": on})).unwrap(); +} + +fn path_of(s: &Session, id: NodeId) -> PathData { + s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().clone() +} + +fn anchor(s: &Session, id: NodeId, ai: usize) -> Anchor { + path_of(s, id).subpaths[0].anchors[ai] +} + +fn create(s: &mut Session, anchors: serde_json::Value) -> NodeId { + NodeId(s.execute("path.create", &json!({ "anchors": anchors })).unwrap()["id"].as_u64().unwrap()) +} + +/// A curve from (100, 100) to (300, 100) whose handles lie on its chord. +fn curve(s: &mut Session) -> NodeId { + create(s, json!([{"x": 100, "y": 100, "out": [150, 100]}, {"x": 300, "y": 100, "in": [250, 100]}])) +} + +fn select(s: &mut Session, id: NodeId, anchors: serde_json::Value) { + s.execute("select.anchors", &json!({"id": id.0, "anchors": anchors, "mode": "set"})).unwrap(); +} + +/// A Direct Selection click on (`x`, `y`), then a drag from there to (`to_x`, `to_y`). +fn drag(s: &mut Session, (x, y): (f64, f64), (to_x, to_y): (f64, f64)) { + let v = ViewInfo { smart_guides: false, ..ViewInfo::default() }; + s.select_tool("directSelection", v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Down, x, y), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, x, y), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Down, x, y), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, (x + to_x) / 2.0, (y + to_y) / 2.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, to_x, to_y), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, to_x, to_y), v).unwrap(); +} + +#[test] +fn the_preference_is_off_by_default_and_the_handles_then_move_rigidly() { + let mut s = session(); + assert!(!s.prefs.interpolate_control_points); + let id = curve(&mut s); + select(&mut s, id, json!([[0, 0]])); + s.execute("object.nudge", &json!({"dx": 20, "dy": 8})).unwrap(); + let (a, b) = (anchor(&s, id, 0), anchor(&s, id, 1)); + assert_eq!(a.p, Point::new(120.0, 108.0)); + assert_eq!(a.h_out, Point::new(170.0, 108.0), "the moved anchor's handle moves with it"); + assert_eq!(b.h_in, Point::new(250.0, 100.0), "the other end's handle stays"); +} + +#[test] +fn a_nudge_with_the_preference_on_re_maps_both_handles_of_the_segment() { + let mut s = session(); + interpolate(&mut s, true); + let id = curve(&mut s); + select(&mut s, id, json!([[0, 0]])); + let before = history(&s).0; + s.execute("object.nudge", &json!({"dx": 20, "dy": 8})).unwrap(); + assert_eq!(history(&s).0, before + 1, "one undo step"); + let (a, b) = (anchor(&s, id, 0), anchor(&s, id, 1)); + // The chord goes from (200, 0) to (180, -8): a scale by 0.9 and a turn, so the handles a + // quarter of the way from each end stay on the new chord, a quarter of the way along it. + assert_eq!(a.p, Point::new(120.0, 108.0)); + assert_eq!(a.h_in, a.p, "a retracted handle stays retracted"); + assert_eq!(a.h_out, Point::new(165.0, 106.0)); + assert_eq!(b.p, Point::new(300.0, 100.0)); + assert_eq!(b.h_in, Point::new(255.0, 102.0)); + assert_eq!(b.h_out, b.p); +} + +#[test] +fn a_direct_selection_drag_with_the_preference_on_re_maps_the_handles_in_one_undo_step() { + let mut s = session(); + interpolate(&mut s, true); + let id = curve(&mut s); + let original = path_of(&s, id); + drag(&mut s, (100.0, 100.0), (120.0, 108.0)); + let (a, b) = (anchor(&s, id, 0), anchor(&s, id, 1)); + assert_eq!(a.p, Point::new(120.0, 108.0)); + assert_eq!(a.h_out, Point::new(165.0, 106.0)); + assert_eq!(b.h_in, Point::new(255.0, 102.0)); + // One undo step puts the path back as it was before the drag. + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(path_of(&s, id), original); +} + +#[test] +fn a_direct_selection_drag_with_the_preference_off_keeps_the_rigid_move() { + let mut s = session(); + let id = curve(&mut s); + drag(&mut s, (100.0, 100.0), (120.0, 108.0)); + let (a, b) = (anchor(&s, id, 0), anchor(&s, id, 1)); + assert_eq!(a.h_out, Point::new(170.0, 108.0)); + assert_eq!(b.h_in, Point::new(250.0, 100.0)); +} + +#[test] +fn a_segment_with_both_ends_moved_moves_rigidly() { + let mut s = session(); + interpolate(&mut s, true); + let id = create( + &mut s, + json!([ + {"x": 100, "y": 100, "out": [150, 60]}, + {"x": 300, "y": 100, "in": [250, 60], "out": [350, 150]}, + {"x": 500, "y": 100, "in": [450, 140]}, + ]), + ); + select(&mut s, id, json!([[0, 0], [0, 1]])); + s.execute("object.nudge", &json!({"dx": 10, "dy": 5})).unwrap(); + let (a, b, c) = (anchor(&s, id, 0), anchor(&s, id, 1), anchor(&s, id, 2)); + assert_eq!((a.p, a.h_out), (Point::new(110.0, 105.0), Point::new(160.0, 65.0))); + assert_eq!((b.p, b.h_in), (Point::new(310.0, 105.0), Point::new(260.0, 65.0))); + // The segment to the unmoved third anchor is re-mapped: its chord goes from (200, 0) to + // (190, -5), a scale by 0.95 with a turn of -0.025 per unit. + close(b.h_out, Point::new(358.75, 151.25)); + close(c.h_in, Point::new(453.5, 139.25)); + assert_eq!(c.p, Point::new(500.0, 100.0)); +} + +fn close(p: Point, q: Point) { + assert!((p.x - q.x).abs() < 1e-9 && (p.y - q.y).abs() < 1e-9, "{p:?} is not {q:?}"); +} + +/// A closed square from (100, 100) to (300, 300) whose handles lie on its sides, a quarter of +/// the way along. +fn square(s: &mut Session) -> NodeId { + let anchors = json!([ + {"x": 100, "y": 100, "in": [100, 150], "out": [150, 100]}, + {"x": 300, "y": 100, "in": [250, 100], "out": [300, 150]}, + {"x": 300, "y": 300, "in": [300, 250], "out": [250, 300]}, + {"x": 100, "y": 300, "in": [150, 300], "out": [100, 250]}, + ]); + NodeId(s.execute("path.create", &json!({ "anchors": anchors, "closed": true })).unwrap()["id"].as_u64().unwrap()) +} + +#[test] +fn moving_the_first_anchor_of_a_closed_path_re_maps_the_closing_segment_too() { + let mut s = session(); + interpolate(&mut s, true); + let id = square(&mut s); + select(&mut s, id, json!([[0, 0]])); + s.execute("object.nudge", &json!({"dx": 0, "dy": -200})).unwrap(); + let (a, b, c, d) = (anchor(&s, id, 0), anchor(&s, id, 1), anchor(&s, id, 2), anchor(&s, id, 3)); + assert_eq!(a.p, Point::new(100.0, -100.0)); + // The segment to the second anchor: its chord goes from (200, 0) to (200, 200). + close(a.h_out, Point::new(150.0, -50.0)); + close(b.h_in, Point::new(250.0, 50.0)); + // The closing segment from the fourth anchor: its chord goes from (0, -200) to (0, -400). + close(d.h_out, Point::new(100.0, 200.0)); + close(a.h_in, Point::new(100.0, 0.0)); + // The segment between the third and fourth anchors is not beside the moved anchor. + assert_eq!((c.h_out, d.h_in), (Point::new(250.0, 300.0), Point::new(150.0, 300.0))); + assert_eq!((b.h_out, c.h_in), (Point::new(300.0, 150.0), Point::new(300.0, 250.0))); +} + +#[test] +fn moving_the_last_anchor_of_an_open_path_re_maps_only_the_segment_before_it() { + let mut s = session(); + interpolate(&mut s, true); + let id = create( + &mut s, + json!([ + {"x": 100, "y": 100, "out": [150, 100]}, + {"x": 300, "y": 100, "in": [250, 100], "out": [350, 50]}, + {"x": 500, "y": 100, "in": [450, 100], "out": [550, 50]}, + ]), + ); + select(&mut s, id, json!([[0, 2]])); + s.execute("object.nudge", &json!({"dx": 0, "dy": 200})).unwrap(); + let (a, b, c) = (anchor(&s, id, 0), anchor(&s, id, 1), anchor(&s, id, 2)); + assert_eq!(c.p, Point::new(500.0, 300.0)); + // The chord from the second (corner) anchor goes from (200, 0) to (200, 200). + close(b.h_out, Point::new(400.0, 100.0)); + close(c.h_in, Point::new(450.0, 250.0)); + // The last anchor's own outgoing handle leads to no segment and moves with it. + assert_eq!(c.h_out, Point::new(550.0, 250.0)); + assert_eq!((a.h_out, b.h_in), (Point::new(150.0, 100.0), Point::new(250.0, 100.0))); +} + +#[test] +fn move_and_transform_of_anchors_re_map_the_handles_in_one_undo_step() { + for (cmd, params) in [("object.move", json!({"dx": 20, "dy": 8})), ("object.transform", json!({"matrix": [1, 0, 0, 1, 20, 8], "anchors": true}))] + { + let mut s = session(); + interpolate(&mut s, true); + let id = curve(&mut s); + select(&mut s, id, json!([[0, 0]])); + let (before, original) = (history(&s).0, path_of(&s, id)); + s.execute(cmd, ¶ms).unwrap(); + assert_eq!(history(&s).0, before + 1, "{cmd}: one undo step"); + let (a, b) = (anchor(&s, id, 0), anchor(&s, id, 1)); + assert_eq!(a.p, Point::new(120.0, 108.0), "{cmd}"); + close(a.h_out, Point::new(165.0, 106.0)); + close(b.h_in, Point::new(255.0, 102.0)); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(path_of(&s, id), original, "{cmd}: undone"); + } +} + +#[test] +fn set_bounds_and_guide_move_of_anchors_follow_the_preference_and_the_param() { + for (pref, param, re_mapped) in [(false, None, false), (true, None, true), (true, Some(false), false), (false, Some(true), true)] { + for cmd in ["object.setBounds", "guide.move"] { + let mut s = session(); + interpolate(&mut s, pref); + let id = curve(&mut s); + select(&mut s, id, json!([[0, 0]])); + let mut params = if cmd == "object.setBounds" { + json!({"x": 120, "y": 108}) + } else { + let g = s.execute("guide.add", &json!({"vertical": true, "pos": 50})).unwrap()["index"].as_u64().unwrap(); + s.execute("guide.select", &json!({"indexes": [g], "toggle": true})).unwrap(); + json!({"dx": 20, "dy": 8}) + }; + if let Some(on) = param { + params["interpolate"] = json!(on); + } + let (before, original) = (history(&s).0, path_of(&s, id)); + s.execute(cmd, ¶ms).unwrap(); + assert_eq!(history(&s).0, before + 1, "{cmd}: one undo step"); + let (a, b) = (anchor(&s, id, 0), anchor(&s, id, 1)); + assert_eq!(a.p, Point::new(120.0, 108.0), "{cmd}"); + if re_mapped { + close(a.h_out, Point::new(165.0, 106.0)); + close(b.h_in, Point::new(255.0, 102.0)); + } else { + assert_eq!((a.h_out, b.h_in), (Point::new(170.0, 108.0), Point::new(250.0, 100.0)), "{cmd}, pref {pref}, param {param:?}"); + } + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(path_of(&s, id), original, "{cmd}: undone"); + } + } + let mut s = session(); + let id = curve(&mut s); + // Both anchors, so that a new width scales them and does not only move them. + select(&mut s, id, json!([[0, 0], [0, 1]])); + s.execute("guide.add", &json!({"vertical": true, "pos": 50})).unwrap(); + s.execute("guide.select", &json!({"indexes": [0], "toggle": true})).unwrap(); + let original = path_of(&s, id); + for (cmd, params) in [ + ("object.setBounds", json!({"x": 120, "interpolate": "yes"})), + ("object.setBounds", json!({"width": 50, "interpolate": 1})), + ("guide.move", json!({"dx": 1, "interpolate": "yes"})), + ] { + let e = s.execute(cmd, ¶ms).unwrap_err().to_string(); + assert!(e.contains("`interpolate` must be true or false"), "{cmd}: {e}"); + } + assert_eq!(path_of(&s, id), original); + // With only guides selected, guide.move rejects the value too and leaves the guide. + s.execute("select.none", &json!({})).unwrap(); + s.execute("guide.select", &json!({"indexes": [0]})).unwrap(); + let e = s.execute("guide.move", &json!({"dx": 1, "interpolate": "yes"})).unwrap_err().to_string(); + assert!(e.contains("`interpolate` must be true or false"), "guide.move: {e}"); + assert_eq!(s.doc().unwrap().doc.ruler_guides()[0].pos, 50.0); +} + +#[test] +fn the_interpolate_param_overrides_the_preference_and_rejects_other_values() { + for (pref, param, re_mapped) in [(true, false, false), (false, true, true)] { + let mut s = session(); + interpolate(&mut s, pref); + let id = curve(&mut s); + select(&mut s, id, json!([[0, 0]])); + s.execute("path.moveAnchors", &json!({"dx": 20, "dy": 8, "interpolate": param})).unwrap(); + let b = anchor(&s, id, 1); + assert_eq!(b.h_in != Point::new(250.0, 100.0), re_mapped, "pref {pref}, param {param}: {:?}", b.h_in); + } + let mut s = session(); + let id = curve(&mut s); + select(&mut s, id, json!([[0, 0]])); + let original = path_of(&s, id); + for (cmd, params) in [ + ("path.moveAnchors", json!({"dx": 1, "dy": 0, "interpolate": "yes"})), + ("object.nudge", json!({"dx": 1, "dy": 0, "interpolate": "yes"})), + ("object.move", json!({"dx": 1, "dy": 0, "interpolate": "yes"})), + ("object.transform", json!({"matrix": [1, 0, 0, 1, 1, 0], "anchors": true, "interpolate": 1})), + ("object.transformAgain", json!({"interpolate": "yes"})), + ] { + let e = s.execute(cmd, ¶ms).unwrap_err().to_string(); + assert!(e.contains("`interpolate` must be true or false"), "{cmd}: {e}"); + } + assert_eq!(path_of(&s, id), original); +} + +#[test] +fn a_replayed_move_re_maps_the_handles_as_it_did_whatever_the_preference_is_then() { + let mut s = session(); + interpolate(&mut s, true); + let id = curve(&mut s); + select(&mut s, id, json!([[0, 0]])); + let start = s.journal.len(); + s.execute("object.nudge", &json!({"dx": 20, "dy": 8})).unwrap(); + let moved = path_of(&s, id); + let (cmd, params) = s.journal.since(start).last().cloned().unwrap(); + assert_eq!(params["interpolate"], json!(true), "{cmd}: journaled"); + // Undo, turn the preference off and play the journal entry again. + s.execute("edit.undo", &json!({})).unwrap(); + interpolate(&mut s, false); + select(&mut s, id, json!([[0, 0]])); + s.replay(&cmd, ¶ms).unwrap(); + assert_eq!(path_of(&s, id), moved); +} + +#[test] +fn a_saved_step_without_interpolate_moves_the_handles_rigidly_whatever_the_preference() { + // A step recorded before the preference existed has no `interpolate`; with the preference on, + // it still plays as it did when it was recorded. + for cmd in ["path.moveAnchors", "object.nudge", "object.move"] { + let mut s = session(); + interpolate(&mut s, true); + let id = curve(&mut s); + select(&mut s, id, json!([[0, 0]])); + s.replay(cmd, &json!({"dx": 1, "dy": 1})).unwrap(); + let (a, b) = (anchor(&s, id, 0), anchor(&s, id, 1)); + assert_ne!(a.p, Point::new(100.0, 100.0), "{cmd}: the anchor moves"); + assert_eq!((a.h_out.x - a.p.x, a.h_out.y - a.p.y), (50.0, 0.0), "{cmd}: the moved anchor's handle moves with it"); + assert_eq!(b.h_in, Point::new(250.0, 100.0), "{cmd}: the other end's handle stays"); + // Run directly, the same params follow the preference. + s.execute(cmd, &json!({"dx": 1, "dy": 1})).unwrap(); + assert_ne!(anchor(&s, id, 1).h_in, Point::new(250.0, 100.0), "{cmd}: executed, the handles are re-mapped"); + } +} + +#[test] +fn transform_again_keeps_the_setting_its_move_used() { + let mut s = session(); + interpolate(&mut s, true); + let id = curve(&mut s); + select(&mut s, id, json!([[0, 0]])); + s.execute("object.nudge", &json!({"dx": 20, "dy": 8})).unwrap(); + interpolate(&mut s, false); + s.execute("object.transformAgain", &json!({})).unwrap(); + let mut t = session(); + interpolate(&mut t, true); + let other = curve(&mut t); + select(&mut t, other, json!([[0, 0]])); + t.execute("object.nudge", &json!({"dx": 20, "dy": 8})).unwrap(); + t.execute("object.nudge", &json!({"dx": 20, "dy": 8})).unwrap(); + assert_eq!(path_of(&s, id), path_of(&t, other)); +} + +#[test] +fn a_segment_whose_ends_are_at_the_same_place_moves_rigidly() { + let mut s = session(); + interpolate(&mut s, true); + let id = create(&mut s, json!([{"x": 100, "y": 100, "out": [150, 50]}, {"x": 100, "y": 100, "in": [50, 150]}])); + select(&mut s, id, json!([[0, 0]])); + s.execute("object.nudge", &json!({"dx": 10, "dy": 0})).unwrap(); + let (a, b) = (anchor(&s, id, 0), anchor(&s, id, 1)); + assert_eq!((a.p, a.h_out), (Point::new(110.0, 100.0), Point::new(160.0, 50.0))); + assert_eq!((b.p, b.h_in), (Point::new(100.0, 100.0), Point::new(50.0, 150.0))); +} + +#[test] +fn a_move_onto_the_other_end_moves_the_handles_rigidly() { + let mut s = session(); + interpolate(&mut s, true); + let id = curve(&mut s); + select(&mut s, id, json!([[0, 0]])); + s.execute("object.nudge", &json!({"dx": 200, "dy": 0})).unwrap(); + let (a, b) = (anchor(&s, id, 0), anchor(&s, id, 1)); + assert_eq!((a.p, a.h_out), (Point::new(300.0, 100.0), Point::new(350.0, 100.0))); + assert_eq!(b.h_in, Point::new(250.0, 100.0)); +} + +#[test] +fn a_nudge_of_zero_with_the_preference_on_records_no_undo_step() { + let mut s = session(); + interpolate(&mut s, true); + let id = curve(&mut s); + select(&mut s, id, json!([[0, 0]])); + let (before, original) = (history(&s), path_of(&s, id)); + s.execute("object.nudge", &json!({"dx": 0, "dy": 0})).unwrap(); + assert_eq!(history(&s), before); + assert_eq!(path_of(&s, id), original); +} + +#[test] +fn a_smooth_anchor_keeps_its_handles_in_line() { + let mut s = session(); + interpolate(&mut s, true); + let id = create( + &mut s, + json!([ + {"x": 100, "y": 100, "out": [150, 100]}, + {"x": 300, "y": 100, "in": [250, 100], "out": [350, 100], "smooth": true}, + {"x": 500, "y": 100, "in": [450, 100]}, + ]), + ); + select(&mut s, id, json!([[0, 0]])); + s.execute("object.nudge", &json!({"dx": 0, "dy": -100})).unwrap(); + let b = anchor(&s, id, 1); + assert_eq!(b.p, Point::new(300.0, 100.0)); + // The segment to the third anchor did not move, so its handle stays where it was. + assert_eq!(b.h_out, Point::new(350.0, 100.0)); + // The incoming handle grows with the chord from the moved anchor (from 200 to 100√5) and + // turns back in line with the outgoing one. + assert_eq!(b.h_in.y, 100.0, "in line: {:?}", b.h_in); + assert!((300.0 - b.h_in.x - 25.0 * 5f64.sqrt()).abs() < 1e-9, "{:?}", b.h_in); +} + +#[test] +fn a_moved_smooth_anchor_keeps_a_retracted_handle_exactly_retracted() { + let mut s = session(); + interpolate(&mut s, true); + let id = create( + &mut s, + json!([ + {"x": 0, "y": 100, "out": [50, 100]}, + {"x": 200, "y": 100, "in": [200, 100], "out": [250, 150], "smooth": true}, + {"x": 400, "y": 100, "in": [350, 100]}, + ]), + ); + select(&mut s, id, json!([[0, 1]])); + s.execute("object.nudge", &json!({"dx": 20, "dy": 8.1})).unwrap(); + let b = anchor(&s, id, 1); + assert_eq!(b.p, Point::new(220.0, 108.1)); + // Re-mapping the retracted handle by its segment's map would leave it a rounding error away + // from the anchor, and lining the handles up would then turn the outgoing one by that error. + assert_eq!(b.h_in, b.p, "the retracted handle stays retracted"); + // The chord to the third anchor goes from (200, 0) to (180, -8.1). + close(b.h_out, Point::new(267.025, 151.075)); +} + +#[test] +fn transform_again_repeats_a_move_with_the_handles_re_mapped() { + let twice = |again: bool| { + let mut s = session(); + interpolate(&mut s, true); + let id = curve(&mut s); + select(&mut s, id, json!([[0, 0]])); + s.execute("object.nudge", &json!({"dx": 20, "dy": 8})).unwrap(); + if again { + s.execute("object.transformAgain", &json!({})).unwrap(); + } else { + s.execute("object.nudge", &json!({"dx": 20, "dy": 8})).unwrap(); + } + path_of(&s, id) + }; + let (repeated, nudged) = (twice(true), twice(false)); + assert_eq!(repeated.subpaths[0].anchors[0].p, Point::new(140.0, 116.0)); + assert_eq!(repeated, nudged); +} + +#[test] +fn a_transform_that_scales_by_a_hair_still_scales_the_anchors() { + let mut s = session(); + interpolate(&mut s, true); + let id = curve(&mut s); + select(&mut s, id, json!([[0, 0]])); + let k = 1.000_000_000_5; + s.execute("object.transform", &json!({"matrix": [k, 0, 0, 1, 0, 0], "anchors": true})).unwrap(); + let a = anchor(&s, id, 0); + assert_eq!(a.p, Point::new(100.0 * k, 100.0)); + assert_eq!(a.h_out, Point::new(150.0 * k, 100.0)); +} + +#[test] +fn a_smooth_anchor_whose_re_mapped_handles_point_the_same_way_moves_them_with_it() { + let mut s = session(); + interpolate(&mut s, true); + let id = create( + &mut s, + json!([ + {"x": 100, "y": 100, "out": [150, 100]}, + {"x": 300, "y": 100, "in": [250, 100], "out": [350, 100], "smooth": true}, + {"x": 500, "y": 100, "in": [450, 100]}, + ]), + ); + select(&mut s, id, json!([[0, 1]])); + s.execute("object.nudge", &json!({"dx": 300, "dy": 0})).unwrap(); + // Both chords re-map their handle to the left of the anchor, which has no direction between + // them: both handles move with the anchor, as with the preference off. + let b = anchor(&s, id, 1); + assert_eq!(b.p, Point::new(600.0, 100.0)); + assert_eq!(b.h_out, Point::new(650.0, 100.0)); + assert_eq!(b.h_in, Point::new(550.0, 100.0)); +} + +#[test] +fn a_smooth_anchor_between_two_re_mapped_segments_keeps_its_handles_in_line() { + let mut s = session(); + interpolate(&mut s, true); + let id = create( + &mut s, + json!([ + {"x": 100, "y": 100, "out": [150, 100]}, + {"x": 300, "y": 100, "in": [250, 100], "out": [350, 100], "smooth": true}, + {"x": 500, "y": 100, "in": [450, 100]}, + ]), + ); + select(&mut s, id, json!([[0, 1]])); + s.execute("object.nudge", &json!({"dx": 0, "dy": -100})).unwrap(); + let b = anchor(&s, id, 1); + let (v_in, v_out) = (b.h_in - b.p, b.h_out - b.p); + assert_eq!(b.p, Point::new(300.0, 0.0)); + // The two chords turn by the same angle in opposite directions, so the handles point along + // the mean of the two: across, at the length each chord gives them. + assert!(v_in.cross(v_out).abs() < 1e-9, "the handles stay in line: {:?} {:?}", b.h_in, b.h_out); + assert!(v_in.dot(v_out) < 0.0, "on opposite sides of the anchor"); + assert!(v_out.y.abs() < 1e-9 && v_out.x > 0.0, "{:?}", b.h_out); + assert!((v_out.hypot() - 25.0 * 5f64.sqrt()).abs() < 1e-9 && (v_in.hypot() - 25.0 * 5f64.sqrt()).abs() < 1e-9); +} diff --git a/crates/engine/src/tests/livecorners.rs b/crates/engine/src/tests/livecorners.rs index 906f7a1622..e372467603 100644 --- a/crates/engine/src/tests/livecorners.rs +++ b/crates/engine/src/tests/livecorners.rs @@ -392,6 +392,67 @@ fn an_ellipse_takes_pie_angles_and_inverts() { assert!(s.execute("object.setLiveShape", &json!({"pieStart": "half"})).is_err()); } +/// Constrain Pie Angle (`constrainPie`): a new Pie Start or End Angle moves the other angle by as +/// much, so each selected ellipse keeps its own span, across 0° too; a whole ellipse stays whole; +/// after Invert Pie the inverted span is kept; one undo step for all of them; the angle each +/// already has records nothing; and `constrainPie` with both angles, with neither, with Invert Pie +/// or as text is an error that changes nothing. +#[test] +fn constrain_pie_keeps_each_ellipses_span() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 300, "height": 300})).unwrap(); + let id = |v: Value| NodeId(v["id"].as_u64().unwrap()); + let [a, b, c] = [0, 100, 200].map(|y| id(s.execute("shape.ellipse", &json!({"x": 0, "y": y, "width": 200, "height": 80})).unwrap())); + run(&mut s, json!({"ids": [a.0], "pieStart": 300, "pieEnd": 60})); + run(&mut s, json!({"ids": [b.0], "pieStart": 0, "pieEnd": 90})); + let pies = |s: &Session| { + [a, b, c].map(|i| match &s.doc().unwrap().doc.node(i).unwrap().kind { + NodeKind::Path { live: Some(l), .. } => match &**l { + LiveShape::Ellipse { pie, .. } => *pie, + k => panic!("{k:?}"), + }, + k => panic!("{k:?}"), + }) + }; + let near = |p: (f64, f64), q: (f64, f64)| (p.0 - q.0).abs() < 1e-9 && (p.1 - q.1).abs() < 1e-9; + let undo = |s: &Session| s.doc().unwrap().history.undo.len(); + let n = undo(&s); + // 300° to 60° spans 120°, through 0°; 0° to 90° spans 90°; the third ellipse is whole. + run(&mut s, json!({"ids": [a.0, b.0, c.0], "pieStart": 350, "constrainPie": true})); + let [pa, pb, pc] = pies(&s); + assert!(near(pa, (350.0, 110.0)) && near(pb, (350.0, 80.0)), "{pa:?} {pb:?}"); + assert!(near(pc, (350.0, 350.0)), "{pc:?}"); + assert_eq!(s.doc().unwrap().doc.node(c).unwrap().path_data().unwrap().anchor_count(), 4, "the whole ellipse stays whole"); + assert_eq!(undo(&s), n + 1, "one undo step"); + run(&mut s, json!({"ids": [a.0, b.0], "pieEnd": 20, "constrainPie": true})); + let [pa, pb, _] = pies(&s); + assert!(near(pa, (260.0, 20.0)) && near(pb, (290.0, 20.0)), "{pa:?} {pb:?}"); + let n = undo(&s); + run(&mut s, json!({"ids": [a.0, b.0], "pieEnd": 380, "constrainPie": true})); + assert_eq!(undo(&s), n, "the end each already has: no undo step"); + s.execute("edit.undo", &json!({})).unwrap(); + let [pa, pb, _] = pies(&s); + assert!(near(pa, (350.0, 110.0)) && near(pb, (350.0, 80.0)), "{pa:?} {pb:?}"); + // Inverted, 80° to 350° spans 270°, and a linked edit keeps that. + run(&mut s, json!({"ids": [b.0], "invertPie": true})); + run(&mut s, json!({"ids": [b.0], "pieStart": 0, "constrainPie": true})); + assert!(near(pies(&s)[1], (0.0, 270.0)), "{:?}", pies(&s)[1]); + let before = (undo(&s), pies(&s)); + for (p, want) in [ + (json!({"ids": [b.0], "pieStart": 10, "pieEnd": 20, "constrainPie": true}), "needs one of"), + (json!({"ids": [b.0], "constrainPie": true}), "needs one of"), + (json!({"ids": [b.0], "pieStart": 10, "constrainPie": true, "invertPie": true}), "needs one of"), + (json!({"ids": [b.0], "pieStart": 10, "constrainPie": "yes"}), "`constrainPie` must be true or false"), + ] { + let r = s.execute("object.setLiveShape", &p); + assert!(matches!(&r, Err(EngineError::BadParams { msg, .. }) if msg.contains(want)), "{p}: {r:?}"); + assert_eq!((undo(&s), pies(&s)), before, "{p}"); + } + // Off, each angle is set on its own, as before. + run(&mut s, json!({"ids": [b.0], "pieStart": 90, "constrainPie": false})); + assert!(near(pies(&s)[1], (90.0, 270.0)), "{:?}", pies(&s)[1]); +} + /// Invert Pie and Make Sides Equal given as text or as another value that is not true or false are /// an error naming the key: the ellipse's pie, the polygon and the undo history stay as they were. /// True makes the change, and false and null leave the shape as it is. diff --git a/crates/engine/src/tests/newdoc.rs b/crates/engine/src/tests/newdoc.rs index 04e075f312..c6699190b6 100644 --- a/crates/engine/src/tests/newdoc.rs +++ b/crates/engine/src/tests/newdoc.rs @@ -745,6 +745,56 @@ fn the_profile_follows_the_preset_access_and_reset() { let _ = std::fs::remove_dir_all(&dir); } +/// The first run's style of text object `id`. +fn first_run(s: &Session, id: &Value) -> vectorcraft_doc::CharStyle { + let n = s.doc().unwrap().doc.node(vectorcraft_doc::NodeId(id.as_u64().unwrap())).cloned().unwrap(); + let vectorcraft_doc::NodeKind::Text(t) = &n.kind else { panic!("not type: {n:?}") }; + t.runs[0].style.clone() +} + +#[test] +fn a_profiles_normal_character_style_is_the_default_font() { + let (mut s, dir) = with_profiles("default-font"); + // The Print profile's [Normal Character Style] becomes Source Serif 4 Regular at 9 pt. + s.execute("file.newProfiles.edit", &json!({"name": "Print"})).unwrap(); + let attrs = json!({"font_family": "Source Serif 4", "font_style": "Regular", "size": 9, "charAlign": "emBoxBottom"}); + s.execute("charStyle.setAttrs", &json!({"name": "[Normal Character Style]", "attrs": attrs})).unwrap(); + s.execute("document.save", &json!({})).unwrap(); + + // New type in a document from the profile takes the font, size and Character Alignment. + s.execute("file.new", &json!({"preset": "A4"})).unwrap(); + let made = s.execute("text.create", &json!({"x": 20, "y": 40, "text": "Serif"})).unwrap(); + assert!(made.get("warning").is_none(), "{made}"); + let st = first_run(&s, &made["id"]); + assert_eq!((st.font_family.as_str(), st.font_style.as_str(), st.size), ("Source Serif 4", "Regular", 9.0)); + assert_eq!(st.char_align, vectorcraft_doc::CharAlign::EmBoxBottom); + // A font, size or Character Alignment given to the command still wins. + let made = s + .execute("text.create", &json!({"x": 20, "y": 80, "text": "Sans", "font": "Source Sans 3", "size": 14, "charAlign": "romanBaseline"})) + .unwrap(); + let st = first_run(&s, &made["id"]); + assert_eq!((st.font_family.as_str(), st.size, st.char_align), ("Source Sans 3", 14.0, vectorcraft_doc::CharAlign::RomanBaseline)); + // A family given alone starts in Regular, not the style's Bold, and without its axis settings. + let attrs = json!({"font_style": "Bold", "fontAxes": {"wght": 700}}); + s.execute("charStyle.setAttrs", &json!({"name": "[Normal Character Style]", "attrs": attrs})).unwrap(); + let made = s.execute("text.create", &json!({"x": 20, "y": 120, "text": "Inter", "font": "Inter"})).unwrap(); + let st = first_run(&s, &made["id"]); + assert_eq!((st.font_family.as_str(), st.font_style.as_str()), ("Inter", "Regular")); + assert!(st.font_axes.is_empty(), "{:?}", st.font_axes); + // A font of the style that isn't available is reported, as one given to the command is. + s.execute("charStyle.setAttrs", &json!({"name": "[Normal Character Style]", "attrs": {"font_family": "No Such Family 7498"}})).unwrap(); + let made = s.execute("text.create", &json!({"x": 20, "y": 160, "text": "Missing"})).unwrap(); + assert!(made["warning"].as_str().is_some_and(|w| w.contains("No Such Family 7498")), "{made}"); + + // A document from a profile left as shipped starts type in the default font and size. + s.execute("file.new", &json!({"profile": "Web"})).unwrap(); + let made = s.execute("text.create", &json!({"x": 20, "y": 40, "text": "Default"})).unwrap(); + let st = first_run(&s, &made["id"]); + let default = vectorcraft_doc::CharStyle::default(); + assert_eq!((st.font_family, st.size), (default.font_family, default.size)); + let _ = std::fs::remove_dir_all(&dir); +} + #[test] fn profile_errors_name_the_file_by_its_name_outside_the_read_roots() { let (mut s, dir) = with_profiles("errors"); diff --git a/crates/engine/src/tests/package.rs b/crates/engine/src/tests/package.rs index e5483d1889..582543f7eb 100644 --- a/crates/engine/src/tests/package.rs +++ b/crates/engine/src/tests/package.rs @@ -465,6 +465,117 @@ fn a_confined_package_refuses_a_linked_file_that_keeps_an_export_folder_outside_ assert_eq!(package(&mut s, json!({"folder": out})).unwrap()["links"], 1); } +/// A confined request packages no linked file whose native document it can't read to check against +/// its read roots: a PDF that needs a password to open, and a native document that doesn't load, +/// even inside the roots. The package is refused before anything is written, with an error that +/// names no file or folder. A PDF without editing data is copied, and the person's package copies +/// every file. +#[test] +fn a_confined_package_refuses_a_linked_file_whose_editing_data_cannot_be_read() { + let home = Folder::new("package-unreadable-home"); + let roots = crate::file_access::AutomationRoots::new(&[&home.0], &[&home.0]).unwrap().unwrap(); + let out = home.file("out"); + let package = |s: &mut Session, p: Value| crate::file_access::confine(Some(&roots), || s.execute("file.package", &p)); + let refused = |s: &mut Session, p: Value| { + let e = package(s, p.clone()).expect_err("refused"); + assert!(matches!(e, EngineError::BadParams { .. }), "{p}: {e:?}"); + let e = e.to_string(); + assert!(e.contains("a linked file's editing data can't be read to check it against the read roots"), "{p}: {e}"); + assert!(!e.contains(home.0.to_string_lossy().as_ref()) && !e.contains("part."), "{p}: {e}"); + assert!(!std::path::Path::new(&out).exists(), "{p}"); + }; + let mut part = session(); + run(&mut part, "shape.rectangle", json!({"x": 10, "y": 10, "width": 30, "height": 30})); + std::fs::create_dir_all(home.0.join("art")).unwrap(); + let native = home.file("art/part.vectorcraft"); + let pdf = home.file("art/part.pdf"); + save(&mut part, &native); + let pdf_of = + |part: &mut Session, p: Value| vectorcraft_format::base64_decode(run(part, "document.serialize", p)["dataBase64"].as_str().unwrap()).unwrap(); + let editable = pdf_of(&mut part, json!({"format": "pdf"})); + let locked = pdf_of(&mut part, json!({"format": "pdf", "security": {"openPassword": "open sesame"}})); + assert!(vectorcraft_pdf::editing_with(&locked, Some("open sesame")).is_some(), "the locked PDF carries editing data"); + let plain = pdf_of(&mut part, json!({"format": "pdf", "preserveEditing": false})); + let poster = |placed: &str| { + let mut s = session(); + let r = run(&mut s, "file.place", json!({"path": placed, "link": true})); + assert_eq!(r["linked"], true, "{r}"); + save(&mut s, &home.file("poster.vectorcraft")); + s + }; + write(&pdf, &editable); + let mut s = poster(&pdf); + write(&pdf, &locked); + refused(&mut s, json!({"folder": out})); + refused(&mut s, json!({"relink": false})); + // A package prepared in the confined request and written on another thread. + let prepared = crate::file_access::confine(Some(&roots), || s.prepare_package(&json!({"folder": out}))).unwrap(); + let e = + std::thread::spawn(move || prepared.write(&mut |_, _| Ok(())).map(|_| ()).map_err(|e| e.to_string())).join().unwrap().expect_err("refused"); + assert!(e.contains("a linked file's editing data can't be read to check it against the read roots"), "{e}"); + assert!(!std::path::Path::new(&out).exists()); + assert_eq!(run(&mut s, "file.package", json!({}))["links"], 1, "the person's package"); + // A PDF listing the editing file without its data (`EF` renamed, the same length). + let at = editable.windows(4).position(|w| w.starts_with(b"/EF") && !w[3].is_ascii_alphanumeric()).expect("the editing file's EF"); + let mut detached = editable.clone(); + detached[at..at + 3].copy_from_slice(b"/XF"); + assert!(vectorcraft_pdf::editing(&detached).is_none(), "the editing data can't be resolved"); + write(&pdf, &detached); + refused(&mut s, json!({"folder": out})); + refused(&mut s, json!({"relink": false})); + assert_eq!(run(&mut s, "file.package", json!({}))["links"], 1, "the person's package"); + // A PDF without editing data. + write(&pdf, &plain); + assert_eq!(package(&mut s, json!({"folder": out})).unwrap()["links"], 1); + std::fs::remove_dir_all(&out).unwrap(); + // A PDF whose attachments are too many to search to their end, with a readable editing file + // listed before the ones left unsearched. + let cut = attachments_cut_short(&vectorcraft_pdf::editing(&editable).unwrap().data); + assert!(vectorcraft_pdf::editing(&cut).is_some(), "the editing data is read"); + write(&pdf, &cut); + refused(&mut s, json!({"folder": out})); + refused(&mut s, json!({"relink": false})); + assert_eq!(run(&mut s, "file.package", json!({}))["links"], 1, "the person's package"); + // A native document that doesn't load, rewritten or copied as it is. + let mut s = poster(&native); + write(&native, b"not a document"); + refused(&mut s, json!({"folder": out})); + refused(&mut s, json!({"folder": out, "relink": false})); + assert_eq!(run(&mut s, "file.package", json!({}))["links"], 1, "the person's package"); +} + +/// A one-page PDF carrying `native` as its editing file, listed first in an attachment name tree +/// whose second subtree has 70,000 nodes, more than are searched. +fn attachments_cut_short(native: &[u8]) -> Vec { + let name = vectorcraft_pdf::EDITING_FILE; + let mut stream = format!("<< /Length {} >>\nstream\n", native.len()).into_bytes(); + stream.extend_from_slice(native); + stream.extend_from_slice(b"\nendstream"); + let objects = [ + b"<< /Type /Catalog /Pages 2 0 R /Names << /EmbeddedFiles 3 0 R >> >>".to_vec(), + b"<< /Type /Pages /Kids [6 0 R] /Count 1 >>".to_vec(), + format!("<< /Kids [4 0 R << /Kids [{}] >>] >>", "<< /Names [] >> ".repeat(70_000)).into_bytes(), + format!("<< /Names [({name}) << /Type /Filespec /UF ({name}) /EF << /F 5 0 R >> >>] >>").into_bytes(), + stream, + b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 100 100] >>".to_vec(), + ]; + let mut out = b"%PDF-1.7\n".to_vec(); + let mut offsets = Vec::new(); + for (i, body) in objects.iter().enumerate() { + offsets.push(out.len()); + out.extend_from_slice(format!("{} 0 obj\n", i + 1).as_bytes()); + out.extend_from_slice(body); + out.extend_from_slice(b"\nendobj\n"); + } + let xref = out.len(); + out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", offsets.len() + 1).as_bytes()); + for at in &offsets { + out.extend_from_slice(format!("{at:010} 00000 n \n").as_bytes()); + } + out.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", offsets.len() + 1).as_bytes()); + out +} + /// A missing link stored as a path relative to the document names a file inside a confined /// request's read root: the package report and Document Info give its stored path. #[test] diff --git a/crates/engine/src/tests/params.rs b/crates/engine/src/tests/params.rs index 059dd041a3..ca72e66eec 100644 --- a/crates/engine/src/tests/params.rs +++ b/crates/engine/src/tests/params.rs @@ -430,6 +430,7 @@ fn set_live_shape_refuses_an_unknown_key() { json!({"id": 3, "radius": 5}), json!({"ids": [3], "sides": 6, "polygonAngle": 15, "polygonRadius": 20, "sideLength": null, "makeSidesEqual": true}), json!({"pieStart": 30, "pieEnd": 90, "invertPie": true}), + json!({"pieEnd": 90, "constrainPie": true}), json!({"ids": [3], "lineLength": 72, "lineAngle": 90}), json!({"items": null}), ] { diff --git a/crates/engine/src/tests/plugins.rs b/crates/engine/src/tests/plugins.rs index 8ea5d9f3b5..947a3ec42d 100644 --- a/crates/engine/src/tests/plugins.rs +++ b/crates/engine/src/tests/plugins.rs @@ -4446,6 +4446,59 @@ fn a_cancelled_filter_run_changes_nothing() { assert_eq!(s.doc().unwrap().doc, before); } +/// Preferences › Plug-ins & Scratch Disks › Plug-in Instruction Budget: with Normal a light filter +/// runs out of instructions and changes nothing; with Large the same installed filter finishes, as +/// one undo step, without being installed again. The time budget, Cancel and a heavy filter's +/// larger budget stay as they are, and setting Normal again applies to the next run. +#[test] +fn the_plugin_instruction_budget_preference_sets_a_filter_run_s_instructions() { + use cmd::plugin::FilterRun; + let mut s = session(); + let id = "test.engine.largebudget"; + let output = json!({"objects": [{"path": triangle(), "name": "Plug-in"}]}).to_string(); + // More steps than a light budget pays for, fewer than 5 times it. + install_wat(&mut s, &tpl::spinning(&tpl::manifest(id, "filter", "{}"), 20_000_000, &output)); + let p = json!({"id": id, "ids": []}); + let (before, undo) = (s.doc().unwrap().doc.clone(), s.doc().unwrap().history.undo.len()); + let e = s.execute("plugin.run", &p).unwrap_err().to_string(); + assert!(e.contains("instruction budget"), "{e}"); + assert_eq!((&s.doc().unwrap().doc, s.doc().unwrap().history.undo.len()), (&before, undo)); + + run(&mut s, "prefs.set", json!({"key": "pluginInstructionBudget", "value": "large"})); + let light = vectorcraft_plugins::Limits::default(); + let large = FilterRun::prepare(&s, &p).unwrap().limits().clone(); + assert_eq!(large, vectorcraft_plugins::Limits { fuel_base: vectorcraft_plugins::LARGE_FUEL, ..light.clone() }); + assert_eq!((large.fuel_per_byte, large.wall_time_ms), (light.fuel_per_byte, light.wall_time_ms)); + // Cancel still stops it, and it changes nothing. + let token = vectorcraft_doc::cancel::CancelToken::new(); + token.cancel(); + let r = vectorcraft_doc::cancel::scope(&token, None, || s.execute("plugin.run", &p)); + assert!(matches!(r, Err(EngineError::Cancelled)), "{r:?}"); + assert_eq!((&s.doc().unwrap().doc, s.doc().unwrap().history.undo.len()), (&before, undo)); + let made = run(&mut s, "plugin.run", p.clone())["ids"].clone(); + assert_eq!(made.as_array().map(Vec::len), Some(1)); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1); + + // A heavy filter keeps its larger budget with either choice. + let heavy_id = "test.engine.largebudget.heavy"; + run(&mut s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&heavy(heavy_id, 1)), "allowHeavy": true})); + let hp = json!({"id": heavy_id, "ids": []}); + for budget in ["large", "normal"] { + run(&mut s, "prefs.set", json!({"key": "pluginInstructionBudget", "value": budget})); + let limits = FilterRun::prepare(&s, &hp).unwrap().limits().clone(); + let heavy_limits = (vectorcraft_plugins::HEAVY_FUEL, vectorcraft_plugins::HEAVY_WALL_TIME_MS); + assert_eq!((limits.fuel_base, limits.wall_time_ms), heavy_limits, "{budget}"); + } + + // Normal again: the next run runs out of instructions. + let undo = s.doc().unwrap().history.undo.len(); + let e = s.execute("plugin.run", &p).unwrap_err().to_string(); + assert!(e.contains("instruction budget"), "{e}"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo); + run(&mut s, "plugin.remove", json!({"id": id})); + run(&mut s, "plugin.remove", json!({"id": heavy_id})); +} + /// The manifest of a filter `id` named "Cmd Test" of `kind` with `commands` (a JSON list). fn with_commands(id: &str, kind: &str, commands: &str) -> String { format!(r#"{{"id":"{id}","name":"Cmd Test","version":"1","kind":"{kind}","commands":{commands}}}"#) @@ -4511,9 +4564,10 @@ fn plugin_commands_are_registered_run_and_removed() { install_wat(&mut s, &tpl::module(&tpl::manifest(id, "filter", "{}"), tpl::ECHO, "", 1)); assert!(listed(&s, grow).is_none() && crate::cmd::find_command(grow).is_none()); install_wat(&mut s, &grower(id)); - assert!(listed(&s, grow).is_some()); + assert!(listed(&s, grow).is_some() && crate::cmd::find_command(grow).is_some()); run(&mut s, "plugin.remove", json!({"id": id})); assert!(listed(&s, grow).is_none() && listed(&s, tidy).is_none()); + assert!(crate::cmd::find_command(grow).is_none() && crate::cmd::find_command(tidy).is_none()); assert!(s.execute(grow, &json!({})).is_err(), "removed, it no longer runs"); } diff --git a/crates/engine/src/tests/prefs.rs b/crates/engine/src/tests/prefs.rs index 94a5a1f12e..966e68dc60 100644 --- a/crates/engine/src/tests/prefs.rs +++ b/crates/engine/src/tests/prefs.rs @@ -464,6 +464,38 @@ fn gpu_preference_defaults_to_automatic_and_validates() { assert_eq!(s.prefs.gpu_preference, "automatic"); } +/// Plug-ins & Scratch Disks › Plug-in Instruction Budget: Normal by default, Large by value or +/// label, kept through a save and load, and reset with its category. Setting another value is an +/// error that changes nothing; a saved value that is missing, unknown or of another type reads as +/// Normal and leaves the other saved preferences as they are. +#[test] +fn plugin_instruction_budget_defaults_to_normal_and_validates() { + let mut s = Session::new(); + assert_eq!(s.prefs.plugin_instruction_budget, PluginBudget::Normal); + assert_eq!(s.execute("prefs.get", &json!({"key": "pluginInstructionBudget"})).unwrap(), json!("normal")); + set_pref(&mut s, "pluginInstructionBudget", json!("Large")); + assert_eq!(s.prefs.plugin_instruction_budget, PluginBudget::Large); + assert_eq!(s.execute("prefs.get", &json!({"key": "pluginInstructionBudget"})).unwrap(), json!("large")); + for bad in [json!("unlimited"), json!(""), json!(5), json!(null), json!(true), json!(["large"])] { + assert!(s.execute("prefs.set", &json!({"key": "pluginInstructionBudget", "value": bad})).is_err(), "{bad}"); + assert_eq!(s.prefs.plugin_instruction_budget, PluginBudget::Large, "{bad}"); + } + let back: Prefs = serde_json::from_value(s.prefs.to_json()).unwrap(); + assert_eq!(back.plugin_instruction_budget, PluginBudget::Large); + let other_values = [json!("unlimited"), json!(5), json!(null), json!(["large"]), json!({"large": true}), json!("LARGE")]; + let saved_files = other_values.map(|v| json!({"keyboardIncrement": 4, "pluginInstructionBudget": v})); + for saved in std::iter::once(json!({"keyboardIncrement": 4})).chain(saved_files) { + let read: Prefs = serde_json::from_value(saved.clone()).unwrap(); + assert_eq!((read.plugin_instruction_budget, read.keyboard_increment), (PluginBudget::Normal, 4.0), "{saved}"); + } + let l = s.execute("prefs.list", &json!({})).unwrap(); + let row = l.as_array().unwrap().iter().find(|e| e["key"] == "pluginInstructionBudget").unwrap().clone(); + assert_eq!((row["category"].as_str(), row["section"].as_str()), (Some("Plug-ins & Scratch Disks"), Some("Plug-ins"))); + assert_eq!((&row["options"], &row["value"]), (&json!(["normal", "large"]), &json!("large"))); + s.execute("prefs.reset", &json!({"category": "Plug-ins & Scratch Disks"})).unwrap(); + assert_eq!(s.prefs.plugin_instruction_budget, PluginBudget::Normal); +} + /// Performance › Low-Latency Drawing (#6013): off by default and for preference files written /// before it, a boolean only, kept through a save/load round trip, listed under Performance and /// reset with it. diff --git a/crates/engine/src/tests/styles.rs b/crates/engine/src/tests/styles.rs index 6f0242c662..dd5ca1d9f8 100644 --- a/crates/engine/src/tests/styles.rs +++ b/crates/engine/src/tests/styles.rs @@ -299,6 +299,68 @@ fn redefine_shares_one_appearance() { assert!(!Shared::ptr_eq(&node(&s, d).appearance, &nb.appearance)); } +/// Redefine with `from` gives a style another style's look: the style keeps its name, place and id, +/// its objects still linked follow, edited ones are unlinked, and `from` and its objects stay as +/// they are, in one undo step. A style replaced by itself or by a style with the same look records +/// nothing, and bad parameters are errors that change nothing. +#[test] +fn redefine_from_a_style_gives_the_style_that_look() { + let mut s = session(); + let (a, b, c) = linked_three(&mut s); + let d = rect(&mut s, 300.0); + set_fill(&mut s, d, "#0000ff"); + run(&mut s, "transparency.set", json!({"item": null, "opacity": 50, "blend": "multiply"})); + run(&mut s, "graphicStyle.new", json!({"name": "Blue"})); + set_fill(&mut s, c, "#00ff00"); + let names = |s: &Session| s.doc().unwrap().doc.graphic_styles.iter().map(|g| g.name.clone()).collect::>(); + let steps = |s: &Session| s.doc().unwrap().history.undo.len(); + let (old, blue, order, before) = (style(&s, "S"), style(&s, "Blue"), names(&s), steps(&s)); + assert_eq!(run(&mut s, "graphicStyle.redefine", json!({"name": "S", "from": "Blue"}))["name"], "S"); + assert_eq!(style(&s, "S"), GraphicStyle { name: "S".into(), id: old.id, ..blue.clone() }); + assert_eq!(names(&s), order); + let blue_paint = Paint::solid(Color::from_hex("#0000ff").unwrap()); + for id in [a, b] { + let n = node(&s, id); + assert_eq!((n.appearance.fill_paint(), n.opacity, n.blend), (blue_paint.clone(), 0.5, BlendMode::Multiply)); + } + assert_eq!(linked(&mut s, "S"), vec![a.0, b.0]); + // The edited object keeps its look and is unlinked; Blue and its object are as they were. + assert_eq!(fill(&s, c), Paint::solid(Color::from_hex("#00ff00").unwrap())); + assert_eq!(node(&s, c).extras().graphic_style, None); + assert_eq!(style(&s, "Blue"), blue); + assert_eq!(linked(&mut s, "Blue"), vec![d.0]); + let step = s.doc().unwrap().history.undo.last().unwrap().clone(); + assert_eq!((step.label.as_str(), steps(&s)), ("Redefine Graphic Style “S”", before + 1)); + run(&mut s, "edit.undo", json!({})); + assert_eq!(style(&s, "S"), old); + assert_eq!((fill(&s, a), fill(&s, b)), (Paint::solid(Color::WHITE), Paint::solid(Color::WHITE))); + assert_eq!(node(&s, c).extras().graphic_style, Some(old.id)); + run(&mut s, "edit.redo", json!({})); + assert_eq!(style(&s, "S").appearance, blue.appearance); + assert_eq!(linked(&mut s, "S"), vec![a.0, b.0]); + run(&mut s, "edit.undo", json!({})); + + // A style replaced by itself, or by a copy with the same look, records nothing. + run(&mut s, "graphicStyle.duplicate", json!({"name": "Blue"})); + let before = steps(&s); + run(&mut s, "graphicStyle.redefine", json!({"name": "S", "from": "S"})); + run(&mut s, "graphicStyle.redefine", json!({"name": "Blue copy", "from": "Blue"})); + assert_eq!(steps(&s), before); + assert_eq!(style(&s, "S"), old); + + // A style that does not exist, a `from` that is not a name, `from` with `id` and a missing `name` are errors. + for p in [ + json!({"name": "S", "from": "nope"}), + json!({"name": "nope", "from": "Blue"}), + json!({"name": "S", "from": 3}), + json!({"name": "S", "from": "Blue", "id": a.0}), + json!({"from": "Blue"}), + ] { + assert!(s.execute("graphicStyle.redefine", &p).is_err(), "{p}"); + } + assert_eq!((steps(&s), style(&s, "S")), (before, old)); +} + #[test] fn deleting_a_style_unlinks_and_renaming_keeps_links() { let mut s = session(); diff --git a/crates/engine/src/tests/symboledit.rs b/crates/engine/src/tests/symboledit.rs index 450572b731..47dfeacc5e 100644 --- a/crates/engine/src/tests/symboledit.rs +++ b/crates/engine/src/tests/symboledit.rs @@ -253,6 +253,28 @@ fn redefining_the_symbol_being_edited_leaves_symbol_editing_mode_in_the_same_ste assert!(st.doc.symbol_edit.is_some()); } +/// Redefining the symbol being edited with `keepArt: true` also leaves symbol editing mode in the +/// same step; the art outside the editing layer stays ordinary art and stays selected, and the +/// art on the editing layer still can't redefine it. +#[test] +fn redefining_the_symbol_being_edited_with_keep_art_leaves_the_art_and_the_mode() { + let (mut s, first, second) = two_instances(); + let other = id(&run(&mut s, "shape.rectangle", json!({"x": 10, "y": 200, "width": 30, "height": 30}))); + let layer = NodeId(run(&mut s, "symbol.edit", json!({"id": first.0}))["layer"].as_u64().unwrap()); + let e = s.execute("symbol.update", &json!({"name": "Box", "keepArt": true})).unwrap_err().to_string(); + assert!(e.contains("can't hold an instance of itself"), "{e}"); + let steps = s.doc().unwrap().history.undo.len(); + let r = run(&mut s, "symbol.update", json!({"name": "Box", "ids": [other.0], "keepArt": true})); + assert!(r["id"].is_null(), "{r}"); + let st = s.doc().unwrap(); + assert!(st.doc.symbol_edit.is_none() && st.isolation.is_none() && st.doc.node(layer).is_none()); + assert_eq!(st.history.undo.len(), steps + 1); + assert!(matches!(st.doc.node(other).map(|n| &n.kind), Some(NodeKind::Path { .. })), "the art stays ordinary art"); + assert_eq!(st.selection.objects, vec![other], "the art stays selected"); + assert!(is_instance(&s, first), "the instance editing was entered from is still an instance"); + assert!(close(bounds(&s, second), Rect::new(285.0, 185.0, 315.0, 215.0)), "{:?}", bounds(&s, second)); +} + #[test] fn leaving_goes_back_to_the_isolation_before_and_undo_keeps_a_group_isolated_inside() { let (mut s, first, _) = two_instances(); diff --git a/crates/engine/src/tests/webexport.rs b/crates/engine/src/tests/webexport.rs index a731e51aca..21ae0796d3 100644 --- a/crates/engine/src/tests/webexport.rs +++ b/crates/engine/src/tests/webexport.rs @@ -453,6 +453,92 @@ fn colour_table_lock_web_shift_snap_and_sort() { assert!(lossy < plain, "{lossy} vs {plain}"); } +/// Delete Color: the deleted colors leave the table and the file, their pixels take the nearest +/// color left, and the edit stays with the settings until another reduction is chosen. +#[test] +fn colour_table_delete_maps_pixels_to_the_nearest_color_left() { + // 40×10: red, a near red and blue, and 10 px with nothing (transparent). + let mut s = session(40.0, 10.0); + rect(&mut s, [0.0, 0.0, 10.0, 10.0], "#ff0000"); + rect(&mut s, [10.0, 0.0, 10.0, 10.0], "#ee1100"); + rect(&mut s, [20.0, 0.0, 10.0, 10.0], "#0000ff"); + let preview = |s: &mut Session, p: Value| run(s, "document.exportForWeb.preview", p); + let sources = |v: &Value| -> Vec { + let mut out: Vec = + v["colors"].as_array().unwrap().iter().filter(|c| c["transparent"] == false).map(|c| c["source"].as_str().unwrap().to_string()).collect(); + out.sort(); + out + }; + let base = preview(&mut s, json!({"dither": "none"})); + assert_eq!(base["colors"].as_array().unwrap().len(), 4, "{base}"); + for format in ["gif", "png8"] { + let p = json!({"format": format, "dither": "none", "colorTable": {"deleted": ["#EE1100"]}}); + let v = preview(&mut s, p.clone()); + assert_eq!(v["colors"].as_array().unwrap().len(), 3, "{format}: {v}"); + assert!(v["colors"].as_array().unwrap().iter().any(|c| c["transparent"] == true), "{format}: the transparent entry stays"); + assert_eq!(sources(&v), ["#0000ff", "#ff0000"], "{format}"); + let file = one(&mut s, p); + assert_eq!(v["bytes"].as_u64(), Some(file.len() as u64), "{format}: the preview is the file"); + let img = pixels(&file); + assert_eq!(img.get_pixel(15, 5).0, [255, 0, 0, 255], "{format}: the nearest color left"); + assert_eq!((img.get_pixel(5, 5).0, img.get_pixel(25, 5).0, img.get_pixel(35, 5).0[3]), ([255, 0, 0, 255], [0, 0, 255, 255], 0)); + assert_eq!(distinct(&img), 3, "{format}"); + } + // A color the table does not hold is no edit; sorting does not bring a deleted one back. + assert_eq!(sources(&preview(&mut s, json!({"dither": "none", "colorTable": {"deleted": ["#123456"]}}))).len(), 3); + let sorted = preview(&mut s, json!({"dither": "none", "colorTable": {"deleted": ["#ee1100"], "sort": "luminance"}})); + assert_eq!(sources(&sorted), ["#0000ff", "#ff0000"]); + // A fixed palette: colors it lacks are not made again, and deletions come out of it. + let fixed = preview(&mut s, json!({"dither": "none", "colorTable": {"customPalette": ["#0000ff", "#ff0000"]}})); + assert_eq!(sources(&fixed), ["#0000ff", "#ff0000"]); + let fixed = preview(&mut s, json!({"dither": "none", "colorTable": {"customPalette": ["#0000ff", "#ff0000"], "deleted": ["#ff0000"]}})); + assert_eq!(sources(&fixed), ["#0000ff"]); + // At most `colors` entries of a fixed palette, the transparent one included. + let two = preview(&mut s, json!({"dither": "none", "colors": 2, "colorTable": {"customPalette": ["#0000ff", "#ff0000"]}})); + assert_eq!(sources(&two), ["#0000ff"]); + // Deleting every opaque color is refused: the pixels need a color. + // Colors mapped to transparent do not count as left. + for table in [ + json!({"deleted": ["#ff0000", "#ee1100", "#0000ff"]}), + json!({"customPalette": ["#ff0000"], "deleted": ["#ff0000"]}), + json!({"deleted": ["#0000ff", "#ee1100"], "transparent": ["#ff0000"]}), + json!({"customPalette": ["#ff0000", "#0000ff"], "deleted": ["#0000ff"], "transparent": ["#ff0000"]}), + ] { + let p = json!({"colorTable": table}); + let e = s.execute("document.exportForWeb.preview", &p).err().map(|e| e.to_string()).unwrap_or_default(); + assert!(e.contains(cmd::webexport::KEEP_ONE), "{p}: {e}"); + assert!(s.execute("document.exportForWeb", &p).is_err(), "{p}"); + } + for bad in [ + json!({"colorTable": {"deleted": ["nope"]}}), + json!({"colorTable": {"customPalette": ["#ff000080"]}}), + json!({"colorTable": {"deleted": vec!["#ff0000"; 257]}}), + ] { + assert!(s.execute("document.exportForWeb", &bad).is_err(), "{bad}"); + assert!(s.execute("webExport.settings", &bad).is_err(), "{bad}"); + } + // A deleted color leaves the other lists; JPEG and PNG-24 have no table to edit. + let table = json!({ + "deleted": ["#ee1100"], "customPalette": ["#ff0000", "#ee1100", "#0000ff"], "locked": ["#EE1100", "#0000ff"], + "transparent": ["#ee1100"], "webShift": ["#ee1100"], + }); + let r = run(&mut s, "webExport.settings", json!({ "colorTable": table })); + let t = r["settings"]["colorTable"].clone(); + assert_eq!((&t["locked"], &t["transparent"], &t["webShift"]), (&json!(["#0000ff"]), &json!([]), &json!([]))); + assert_eq!(t["deleted"], json!(["#ee1100"])); + for format in ["jpg", "png24"] { + assert!(preview(&mut s, json!({"format": format, "colorTable": t.clone()})).get("colors").is_none(), "{format}"); + } + // The remembered edit survives other keys and a format change, and goes with another reduction. + let r = run(&mut s, "webExport.settings", json!({"colors": 64, "format": "png8"})); + assert_eq!(r["settings"]["colorTable"]["deleted"], json!(["#ee1100"])); + let r = run(&mut s, "webExport.settings", json!({"reduction": "adaptive"})); + assert_eq!((&r["settings"]["colorTable"]["deleted"], &r["settings"]["colorTable"]["customPalette"]), (&json!([]), &json!([]))); + // A saved preset keeps the edit. + run(&mut s, "webExport.presets.save", json!({"name": "No near red", "dither": "none", "colorTable": {"deleted": ["#ee1100"]}})); + assert_eq!(sources(&preview(&mut s, json!({"preset": "No near red"}))), ["#0000ff", "#ff0000"]); +} + #[test] fn presets_and_remembered_settings() { let mut s = two_colours(); diff --git a/crates/engine/src/tests/xform.rs b/crates/engine/src/tests/xform.rs index 4e13e5fe02..a3470617a7 100644 --- a/crates/engine/src/tests/xform.rs +++ b/crates/engine/src/tests/xform.rs @@ -480,8 +480,8 @@ fn reflect_and_shear_tools() { assert!((b.width() - 150.0).abs() < 1e-6, "{b:?}"); } -/// Reflect and Shear return an error for an `axis` they don't take (Reflect's names it and also -/// takes an angle): nothing moves and no undo step is recorded. A null `axis` counts as not given: Reflect +/// Reflect and Shear return an error for an `axis` they don't take, naming it (both also take an +/// angle, Shear's from -359° to 359°): nothing moves and no undo step is recorded. A null `axis` counts as not given: Reflect /// then reflects across the vertical axis and Shear shears along the horizontal one. #[test] fn reflect_and_shear_reject_unknown_axes_without_changing_state() { @@ -489,13 +489,17 @@ fn reflect_and_shear_reject_unknown_axes_without_changing_state() { let a = rect(&mut s, 10.0, 20.0, 30.0, 10.0); let n = undo_len(&s); let reflect = "axis must be \"vertical\", \"horizontal\" or an angle in degrees"; - let shear = "`axis` must be one of horizontal, vertical"; + let shear = "axis must be \"horizontal\", \"vertical\" or an angle in degrees from -359 to 359"; for (cmd, p, msg) in [ ("object.reflect", json!({"axis": "diagonal", "origin": [0, 0]}), format!("{reflect}, not `diagonal`")), ("object.reflect", json!({"axis": "45", "origin": [0, 0]}), format!("{reflect}, not `45`")), ("object.reflect", json!({"axis": true, "origin": [0, 0]}), format!("{reflect}, not `true`")), - ("object.shear", json!({"angle": 30, "axis": "diagonal"}), shear.to_string()), - ("object.shear", json!({"angle": 30, "axis": 90}), shear.to_string()), + ("object.shear", json!({"angle": 30, "axis": "diagonal"}), format!("{shear}, not `diagonal`")), + ("object.shear", json!({"angle": 30, "axis": "90"}), format!("{shear}, not `90`")), + ("object.shear", json!({"angle": 30, "axis": 360}), format!("{shear}, not `360`")), + ("object.shear", json!({"angle": 30, "axis": -359.5}), format!("{shear}, not `-359.5`")), + ("object.shear", json!({"angle": 30, "axis": [45]}), format!("{shear}, not `[45]`")), + ("object.shear", json!({"angle": 30, "axis": false}), format!("{shear}, not `false`")), ] { let e = s.execute(cmd, &p).expect_err(&format!("{cmd} {p}")); assert_eq!(e.to_string(), format!("invalid parameters for `{cmd}`: {msg}")); @@ -511,6 +515,119 @@ fn reflect_and_shear_reject_unknown_axes_without_changing_state() { assert!((b.y0 + 30.0).abs() < 1e-6 && (b.y1 + 20.0).abs() < 1e-6 && b.width() > 30.0, "along the horizontal axis: {b:?}"); } +/// Shear takes an angle from -359 to 359 degrees and shears by its tangent: 60 and -60 slant +/// opposite ways, and 120 and 300 slant as -60 does. +#[test] +fn shear_angles_slant_by_their_tangent() { + let run = 100.0 * 60f64.to_radians().tan(); + for (angle, want) in [ + (60.0, Rect::new(-run, 0.0, 100.0, 100.0)), + (-60.0, Rect::new(0.0, 0.0, 100.0 + run, 100.0)), + (120.0, Rect::new(0.0, 0.0, 100.0 + run, 100.0)), + (300.0, Rect::new(0.0, 0.0, 100.0 + run, 100.0)), + (-359.0, Rect::new(-100.0 * 1f64.to_radians().tan(), 0.0, 100.0, 100.0)), + ] { + let mut s = session(); + let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0); + s.execute("object.shear", &json!({"angle": angle, "origin": [0, 0]})).unwrap(); + assert!(close(bounds(&s, a), want), "{angle}: {:?}, want {want:?}", bounds(&s, a)); + } +} + +/// Shear returns an error for an angle outside -359 to 359 and for ±90 and ±270, which have no +/// finite shear (within a billionth of a degree too); nothing moves and no undo step is recorded. +#[test] +fn shear_rejects_angles_with_no_shear_or_out_of_range() { + let mut s = session(); + let a = rect(&mut s, 10.0, 20.0, 30.0, 10.0); + let n = undo_len(&s); + let none = |v: f64| format!("invalid parameters for `object.shear`: `angle` cannot be {v}: ±90 and ±270 degrees have no shear"); + let range = |v: f64| format!("invalid parameters for `object.shear`: `angle` must be from -359 to 359 degrees, not {v}"); + for (angle, msg) in [ + (90.0, none(90.0)), + (-90.0, none(-90.0)), + (270.0, none(270.0)), + (-270.0, none(-270.0)), + (90.0 + 1e-12, none(90.0 + 1e-12)), + (360.0, range(360.0)), + (-359.5, range(-359.5)), + (1e300, range(1e300)), + ] { + let e = s.execute("object.shear", &json!({"angle": angle})).expect_err(&angle.to_string()); + assert_eq!(e.to_string(), msg); + } + assert!(s.execute("object.shear", &json!({"angle": "45"})).is_err(), "a string is not an angle"); + assert!(close(bounds(&s, a), Rect::new(10.0, 20.0, 40.0, 30.0)), "nothing moved: {:?}", bounds(&s, a)); + assert_eq!(undo_len(&s), n, "no undo step"); +} + +/// Shear by 0, 180 or -180 degrees, along either axis, has no slant: the art keeps its exact +/// coordinates and no undo step is recorded. +#[test] +fn shear_by_0_and_180_changes_nothing() { + let mut s = session(); + let a = rect(&mut s, 10.0, 20.0, 30.0, 10.0); + let before = bounds(&s, a); + let n = undo_len(&s); + for angle in [180.0, -180.0, 0.0, 180.0 + 1e-12, -180.0 - 1e-12] { + for axis in ["horizontal", "vertical"] { + s.execute("object.shear", &json!({"angle": angle, "axis": axis})).unwrap(); + assert_eq!(bounds(&s, a), before, "{angle} {axis}"); + assert_eq!(undo_len(&s), n, "{angle} {axis}: no undo step"); + } + } +} + +/// Shear along an axis at an angle, counter-clockwise from horizontal on the page: each point +/// slides along the axis by the tangent of the shear angle times its distance across the axis +/// from the origin. -359° and 359° are taken, the shear is one undo step and Transform Again +/// repeats it; 0° and 90° shear as the named axes do, and a copy leaves the original in place. +#[test] +fn shear_along_an_axis_at_an_angle() { + let anchors = |s: &Session, id: NodeId| -> Vec { + s.doc().unwrap().doc.node(id).unwrap().path_data().unwrap().anchors().map(|(_, _, an)| an.p).collect() + }; + // The axis's direction and the direction a quarter turn counter-clockwise from it, with y down. + let sheared = |p: Point, o: Point, axis: f64, angle: f64| { + let (a, k) = (axis.to_radians(), angle.to_radians().tan()); + let (along, across) = (Vec2::new(a.cos(), -a.sin()), Vec2::new(-a.sin(), -a.cos())); + p + along * (k * (p - o).dot(across)) + }; + let near = |a: &[Point], b: &[Point]| a.len() == b.len() && a.iter().zip(b).all(|(p, q)| p.distance(*q) < 1e-9); + let o = Point::new(20.0, 30.0); + for (axis, angle) in [(45.0, 30.0), (-120.5, 20.0), (359.0, 30.0), (-359.0, -30.0), (30.0, 30.0)] { + let mut s = session(); + let a = rect(&mut s, 100.0, 100.0, 60.0, 20.0); + let before = anchors(&s, a); + let n = undo_len(&s); + s.execute("object.shear", &json!({"angle": angle, "axis": axis, "origin": [o.x, o.y]})).unwrap(); + let want: Vec = before.iter().map(|p| sheared(*p, o, axis, angle)).collect(); + assert!(near(&anchors(&s, a), &want), "{axis}° {angle}°: {:?}, not {want:?}", anchors(&s, a)); + assert_eq!(undo_len(&s), n + 1, "one undo step"); + s.execute("object.transformAgain", &json!({})).unwrap(); + let again: Vec = want.iter().map(|p| sheared(*p, o, axis, angle)).collect(); + assert!(near(&anchors(&s, a), &again), "Transform Again at {axis}°: {:?}", anchors(&s, a)); + } + for (named, axis) in [("horizontal", 0.0), ("vertical", 90.0), ("vertical", -270.0)] { + let mut s = session(); + let a = rect(&mut s, 100.0, 100.0, 60.0, 20.0); + s.execute("object.shear", &json!({"angle": 30, "axis": named, "origin": [o.x, o.y]})).unwrap(); + let by_name = anchors(&s, a); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("object.shear", &json!({"angle": 30, "axis": axis, "origin": [o.x, o.y]})).unwrap(); + assert!(near(&anchors(&s, a), &by_name), "{axis}° shears as {named}: {:?}, not {by_name:?}", anchors(&s, a)); + } + let mut s = session(); + let a = rect(&mut s, 100.0, 100.0, 60.0, 20.0); + let before = anchors(&s, a); + s.execute("object.shear", &json!({"angle": 30, "axis": 45, "origin": [o.x, o.y], "copy": true})).unwrap(); + assert!(near(&anchors(&s, a), &before), "the original stays: {:?}", anchors(&s, a)); + let copy = *s.doc().unwrap().selection.objects.first().unwrap(); + assert_ne!(copy, a, "the copy is selected"); + let want: Vec = before.iter().map(|p| sheared(*p, o, 45.0, 30.0)).collect(); + assert!(near(&anchors(&s, copy), &want), "the copy is sheared: {:?}", anchors(&s, copy)); +} + #[test] fn distort_command_maps_corners() { let mut s = session(); diff --git a/crates/engine/tests/command_sweep.rs b/crates/engine/tests/command_sweep.rs index 1fcea777d1..4f49a25b03 100644 --- a/crates/engine/tests/command_sweep.rs +++ b/crates/engine/tests/command_sweep.rs @@ -1009,6 +1009,9 @@ fn structured_junk() { ("addon.pathtools.expandDashes", json!({})), ("addon.pathtools.expandDashes", json!({"ids": [0, 1, 2, 3, u64::MAX]})), ("addon.pathtools.expandDashes", json!({"ids": "x", "junk": f64::MAX})), + ("addon.pathtools.bridge", json!({"radius": 1e-308, "keepOriginals": "x"})), + ("addon.pathtools.bridge", json!({"radius": 1000, "keepOriginals": true, "ids": [0, 1, 2, 3, u64::MAX]})), + ("addon.pathtools.bridge", json!({"radius": f64::MAX, "ids": [1, 1], "junk": [0]})), // Refused before anything is written: no format of that name, a time that is no time. ("addon.document.saveTimestampedCopy", json!({"format": "png", "folder": 7})), ("addon.document.saveTimestampedCopy", json!({"format": "svg", "time": [1e308], "folder": null})), diff --git a/crates/engine/tests/it/dimensions.rs b/crates/engine/tests/it/dimensions.rs index 94c54dea4f..f864877025 100644 --- a/crates/engine/tests/it/dimensions.rs +++ b/crates/engine/tests/it/dimensions.rs @@ -95,6 +95,29 @@ fn apply_to_all_restyles_every_dimension_in_one_undo_step() { assert!(s.execute("dimension.applyToAll", &json!({"id":line})).is_err(), "not a dimension"); } +#[test] +fn each_arrow_style_draws_its_stroke_arrowhead_at_both_ends() { + use vectorcraft_doc::Arrowhead; + let mut s = session(); + for (style, head) in + [("filled", Some(Arrowhead::Triangle)), ("open", Some(Arrowhead::TriangleOpen)), ("tick", Some(Arrowhead::Slash)), ("none", None)] + { + let id = run(&mut s, "dimension.create", json!({"a":[0,0],"b":[72,0],"options":{"arrowStyle":style}}))["id"].as_u64().unwrap(); + let n = s.doc().unwrap().doc.node(NodeId(id)).unwrap(); + let heads: Vec<_> = n + .children() + .unwrap() + .iter() + .filter_map(|n| n.appearance.stroke().map(|s| (s.start_arrow.clone(), s.end_arrow.clone()))) + .filter(|(a, b)| a.is_some() || b.is_some()) + .collect(); + match head { + Some(head) => assert!(!heads.is_empty() && heads.iter().all(|h| *h == (Some(head.clone()), Some(head.clone()))), "{style}: {heads:?}"), + None => assert!(heads.is_empty(), "{style}: {heads:?}"), + } + } +} + #[test] fn dimension_angles_circles_arcs_and_curves() { let mut s = session(); diff --git a/crates/engine/tests/plugin_export.rs b/crates/engine/tests/plugin_export.rs index cc39566875..a8de5429dc 100644 --- a/crates/engine/tests/plugin_export.rs +++ b/crates/engine/tests/plugin_export.rs @@ -287,3 +287,107 @@ fn a_cancelled_export_stops_the_exporter() { assert!(matches!(r, Err(EngineError::Cancelled)), "{r:?}"); assert!(took >= wait && took < Duration::from_secs(10), "stopped while running, not before: {took:?}"); } + +/// Every string in `v`, at any depth. +fn strings_in(v: &Value, out: &mut Vec) { + match v { + Value::String(s) => out.push(s.clone()), + Value::Array(items) => items.iter().for_each(|v| strings_in(v, out)), + Value::Object(map) => map.values().for_each(|v| strings_in(v, out)), + _ => {} + } +} + +/// A confined caller: an exporter, given the native document's JSON, is not run for a document +/// that links a JavaScript file, a data set's image or a placed file outside the read roots. Every +/// command that writes its format refuses, before any file or folder is written, with an error +/// that names no file or folder, and the document keeps its links. A data set's image inside the +/// roots is given to it, the JSON it is given leaves out an Export for Screens folder outside them, +/// and the person's export gives it every path as stored. +#[test] +fn a_confined_exporter_is_refused_stored_paths_outside_the_read_roots() { + use vectorcraft_engine::file_access::{AutomationRoots, confine}; + + let away = tmp_dir("confined-away"); + let home = tmp_dir("confined-home"); + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 200})).unwrap(); + let r = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 100, "height": 50})).unwrap(); + s.execute("assets.add", &json!({"ids": [r["id"]]})).unwrap(); + s.execute("select.all", &json!({})).unwrap(); + install(&mut s, &tpl::echo_exporter(&tpl::exporter("test.confined", r#"["tsc"]"#, "{}"), Echo::Input)); + let format = "plugin.test.confined"; + let roots = AutomationRoots::new(&[home.as_path()], &[home.as_path()]).unwrap(); + let out = path_of(&home.join("out")); + let outputs = [ + ("document.serialize", json!({"format": format})), + ("document.export", json!({"format": format})), + ("document.export", json!({"format": format, "path": path_of(&home.join("export.tsc"))})), + ("document.exportSelection", json!({"format": format})), + ("document.exportForScreens", json!({"folder": out, "formats": [{"format": format}]})), + ("assets.export", json!({"folder": out, "formats": [{"format": format}]})), + ]; + let hidden = [path_of(&away), path_of(&home)]; + // `assets`: an asset's file is checked too (its document holds the asset's art and the + // document's data sets, not other art). + let refused = |s: &mut Session, why: &str, assets: bool| { + for (cmd, p) in outputs.iter().filter(|(cmd, _)| assets || *cmd != "assets.export") { + let e = confine(roots.as_ref(), || s.execute(cmd, p)).expect_err(&format!("{cmd} {p}: {why}")); + assert!(matches!(e, EngineError::BadParams { .. }), "{cmd} {p}: {e:?}"); + let e = e.to_string(); + assert!(e.contains(why), "{cmd} {p}: {e}"); + for h in &hidden { + assert!(!e.contains(h.as_str()), "{cmd} {p} names {h}: {e}"); + } + } + assert_eq!(std::fs::read_dir(&home).unwrap().count(), 0, "nothing is written"); + }; + // The strings of the JSON the exporter is given. + let given = |s: &mut Session, confined: bool| { + let p = json!({"format": format}); + let r = if confined { confine(roots.as_ref(), || s.execute("document.export", &p)) } else { s.execute("document.export", &p) }; + let mut found = vec![]; + strings_in(&serde_json::from_slice(&exported(&r.unwrap())).unwrap(), &mut found); + found + }; + + let script = path_of(&away.join("menu.js")); + s.execute("svgInteractivity.addFile", &json!({"file": script})).unwrap(); + refused(&mut s, "a linked JavaScript file is outside the read roots", true); + assert!(given(&mut s, false).contains(&script), "the person's export"); + s.execute("svgInteractivity.removeFile", &json!({"file": script})).unwrap(); + + let set_image = |s: &mut Session, path: &str| { + let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc); + let values = [("Photo".to_string(), vectorcraft_doc::DataValue::Image(path.into()))].into_iter().collect(); + doc.variables.datasets = vec![vectorcraft_doc::DataSet { name: "Row 1".into(), values }]; + }; + let photo = path_of(&away.join("photo.png")); + set_image(&mut s, &photo); + refused(&mut s, "a linked image file is outside the read roots", true); + assert!(given(&mut s, false).contains(&photo), "the person's export"); + let inside = path_of(&home.join("photo.png")); + set_image(&mut s, &inside); + assert!(given(&mut s, true).contains(&inside), "an image inside the read roots"); + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).variables.datasets.clear(); + + let folder = path_of(&away.join("screens")); + std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc).export_settings = serde_json::from_value(json!({"folder": folder})).unwrap(); + assert!(!given(&mut s, true).contains(&folder), "the export folder is left out"); + assert!(given(&mut s, false).contains(&folder), "the person's export"); + assert_eq!(s.doc().unwrap().doc.export_settings.get("folder"), Some(&json!(folder)), "the document keeps it"); + + let mut part = Session::new(); + part.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let placed = path_of(&away.join("part.vectorcraft")); + part.execute("file.saveAs", &json!({"path": placed})).unwrap(); + s.execute("file.place", &json!({"path": placed, "link": true})).unwrap(); + refused(&mut s, "a linked image file is outside the read roots", false); + // The asset's file holds the rectangle alone, without the placed file. + let r = confine(roots.as_ref(), || s.execute("assets.export", &outputs[5].1)).unwrap(); + let mut found = vec![]; + strings_in(&serde_json::from_slice(&std::fs::read(r["files"][0].as_str().unwrap()).unwrap()).unwrap(), &mut found); + assert!(!found.contains(&placed), "{found:?}"); + let _ = std::fs::remove_dir_all(&away); + let _ = std::fs::remove_dir_all(&home); +} diff --git a/crates/eps/src/ai_editing/tests.rs b/crates/eps/src/ai_editing/tests.rs index 1d9adcfd38..3c2b229e1f 100644 --- a/crates/eps/src/ai_editing/tests.rs +++ b/crates/eps/src/ai_editing/tests.rs @@ -3431,6 +3431,133 @@ fn many_gradient_definitions_take_distinct_names_in_order() { assert_eq!(text, program(&doc)); } +/// The program written from `doc`, with the gradient and pattern definitions found by comparing +/// each in turn (`scanned`) or through their indexes. +fn program_scanned(doc: &Document, scanned: bool) -> Vec { + writer::SCANNED_DEFINITIONS.with(|s| s.set(scanned)); + let out = export_ai_editing(doc, &opts()); + writer::SCANNED_DEFINITIONS.with(|s| s.set(false)); + out.unwrap().program +} + +/// [`gradients_and_patterns`] with more rectangles, each filled with a gradient: `distinct` with +/// gradients of their own; `reused` with one of `ramps` gradients in turn; one for each of +/// `swatches` new gradient swatches, linked to it, with the swatch's gradient for every other one +/// and another gradient for the rest; one with the gradient of an object whose style isn't written +/// (an even-odd fill with a drop shadow), after that object; and two whose gradients +/// differ only in the sign of a zero offset. +fn many_gradients(distinct: u16, reused: u16, ramps: u16, swatches: u16) -> Document { + let mut doc = gradients_and_patterns(); + let two = |a: Color, b: Color| ramp(GradientKind::Linear, &[(0.0, a, 1.0, 0.5), (1.0, b, 1.0, 0.5)]); + let shade = |i: u16, n: u16| f32::from(i) / f32::from(n.max(1)); + let swatch_gradient = |i: u16| two(Color::gray(shade(i, swatches)), Color::rgb(1.0, 0.0, 0.0)); + let more = (0..swatches) + .map(|i| Swatch { name: format!("Ramp {i}"), paint: gradient_paint(swatch_gradient(i), None, None), global: false, spot: false }) + .collect(); + swatches_plus(&mut doc, more); + let mut paints = vec![]; + for i in 0..distinct { + paints.push(gradient_paint(two(Color::rgb(shade(i, distinct), 0.5, 0.0), Color::rgb(0.0, 0.0, 1.0)), None, None)); + } + for i in 0..reused { + paints.push(gradient_paint(two(Color::rgb(0.0, shade(i % ramps.max(1), ramps), 0.5), Color::WHITE), None, None)); + } + for i in 0..swatches { + let g = if i % 2 == 0 { swatch_gradient(i) } else { two(Color::gray(shade(i, swatches)), Color::rgb(0.0, 1.0, 0.0)) }; + paints.push(gradient_paint(g, None, Some(&format!("Ramp {i}")))); + } + // The reader wouldn't read an even-odd fill with the style, so the style isn't written. + let unstyled = two(Color::WHITE, Color::BLACK); + let ap = Appearance { + items: vec![AppearanceItem::Fill(FillLayer::new(gradient_paint(unstyled.clone(), None, None)))], + effects: vec![fx("stylize.dropShadow", serde_json::json!({}))], + contents_index: None, + }; + let mut n = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(10.0, 10.0, 50.0, 40.0)), ap); + if let NodeKind::Path { rule, .. } = &mut n.kind { + *rule = FillRule::EvenOdd; + } + put(&mut doc, n); + paints.push(gradient_paint(unstyled, None, None)); + let zero = |o: f32| ramp(GradientKind::Linear, &[(o, Color::rgb(0.2, 0.3, 0.4), 1.0, 0.5), (1.0, Color::BLACK, 1.0, 0.5)]); + paints.extend([gradient_paint(zero(0.0), None, None), gradient_paint(zero(-0.0), None, None)]); + for (i, p) in (0u16..).zip(paints) { + let (x, y) = (f64::from(i % 60) * 5.0, f64::from(i / 60 % 40) * 5.0); + let n = painted(&mut doc, shapes::rectangle(Rect::new(x, y, x + 4.0, y + 4.0)), vec![AppearanceItem::Fill(FillLayer::new(p))]); + put(&mut doc, n); + } + doc +} + +/// Gradient and pattern definitions found through their indexes are those found by comparing each +/// in turn: the program is the same, byte for byte. A swatch's definition serves a paint linked to +/// it only with the swatch's gradient; a gradient defined for a style that isn't written leaves its +/// name free; gradients that differ only in the sign of a zero share a definition. +#[test] +fn indexed_definitions_write_the_same_program() { + let doc = many_gradients(300, 300, 7, 6); + let (indexed, scanned) = (program_scanned(&doc, false), program_scanned(&doc, true)); + let differ = indexed.iter().zip(&scanned).position(|(a, b)| a != b); + assert!(indexed == scanned, "the programs differ from byte {differ:?} ({} and {} bytes)", indexed.len(), scanned.len()); + let text = String::from_utf8(indexed).unwrap(); + let names: Vec<&str> = text.lines().filter_map(|l| l.strip_prefix("%AI5_BeginGradient: ")).collect(); + // `gradients_and_patterns`'s 5, then 300 + 7 + 6 swatches' + 3 others linked to swatches + 1 + // after the style + 1 for both signs of zero. + assert_eq!(names.len(), 5 + 300 + 7 + 6 + 3 + 1 + 1, "{names:?}"); + assert_eq!(names.iter().collect::>().len(), names.len(), "{names:?}"); + assert_eq!(text.matches("%AI3_BeginPattern: (Dots)").count(), 1); +} + +/// A gradient paint is matched with the definitions of the same gradient, not with each +/// definition: 1,000 gradients of their own and 1,000 paints of 10 others take a few comparisons +/// each, where comparing each definition in turn takes hundreds of thousands. +#[test] +fn gradient_definitions_are_found_without_comparing_each() { + let doc = many_gradients(1000, 1000, 10, 0); + let comparisons = |scanned: bool| { + writer::GRADIENT_COMPARISONS.with(|c| c.set(0)); + program_scanned(&doc, scanned); + writer::GRADIENT_COMPARISONS.with(std::cell::Cell::get) + }; + let (indexed, scanned) = (comparisons(false), comparisons(true)); + assert!(indexed <= 2 * 2010, "{indexed} comparisons through the index"); + assert!(scanned > 100 * indexed, "{scanned} comparisons scanning, {indexed} through the index"); +} + +/// The time to write 5,000 rectangles with gradients of their own, 5,000 with 50 others and 20 +/// gradient swatches, with the definitions found by comparing each in turn and through their +/// indexes: the median of 7 runs of each, alternating, with the programs compared. Run with +/// `cargo test --release -p vectorcraft-eps --lib -- --ignored --nocapture gradient_definitions_timing`. +#[test] +#[ignore = "timing"] +fn gradient_definitions_timing() { + let doc = many_gradients(5000, 5000, 50, 20); + let mut times = [vec![], vec![]]; + let mut programs: [Option>; 2] = [None, None]; + let mut how = ""; + for _ in 0..7 { + for (k, scanned) in [true, false].into_iter().enumerate() { + let (start, h) = thread_time(); + let program = program_scanned(&doc, scanned); + times[k].push(thread_time().0.saturating_sub(start)); + how = h; + programs[k].get_or_insert(program); + } + } + assert_eq!(programs[0], programs[1]); + for t in &mut times { + t.sort(); + } + let ms = |d: std::time::Duration| d.as_secs_f64() * 1000.0; + println!("median of 7 runs ({how}):"); + println!("| definitions found | median (ms) | runs (ms) |"); + println!("|---|---:|---|"); + for (k, label) in ["by comparing each", "through the indexes"].into_iter().enumerate() { + let runs: Vec = times[k].iter().map(|d| format!("{:.1}", ms(*d))).collect(); + println!("| {label} | {:.1} | {} |", ms(times[k][3]), runs.join(", ")); + } +} + /// A hard edge: a linear gradient whose stops all lie at one place is written from its last stop, /// and reads back with each stop on its side. #[test] @@ -10077,6 +10204,7 @@ fn brush_library() -> Vec { rotation: (-45.0, 30.0), rotation_relative_to_path: true, colorization: Colorization::Tints, + hue_jitter: 0.0, modes: Some([Variation::Random, Variation::Fixed, Variation::Pressure, Variation::Random]), }), }, @@ -10183,6 +10311,22 @@ fn brushes_are_read_back_with_their_settings() { } } +/// The writer does not write a Scatter brush's hue jitter: the brush would open without it, so it +/// is left out of the Brushes panel and reported. +#[test] +fn a_scatter_brush_with_hue_jitter_is_left_out() { + use vectorcraft_brush::BrushKind; + let mut lib = brush_library(); + let BrushKind::Scatter(s) = &mut lib[1].kind else { panic!("scatter") }; + s.hue_jitter = 60.0; + let mut doc = Document::new(300.0, 200.0); + vectorcraft_brush::store(&mut doc, &lib); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert!(out.warnings.iter().any(|w| w == writer::BRUSHES), "{:?}", out.warnings); + let back = vectorcraft_brush::library(&read_back(&doc)); + assert_eq!(back.iter().map(|b| b.name.as_str()).collect::>(), ["Nib", "Ribbon", "Plain ribbon"]); +} + /// An Art brush's options, without its art. #[derive(Debug, PartialEq)] struct ArtBrushOptions(serde_json::Value); @@ -10512,6 +10656,7 @@ fn more_brush_settings_are_read_back() { rotation: (15.0, 15.0), rotation_relative_to_path: false, colorization: Colorization::None, + hue_jitter: 0.0, modes: Some([Variation::Tilt, Variation::Bearing, Variation::Fixed, Variation::Rotation]), }; let lib = vec![ diff --git a/crates/eps/src/ai_editing/writer.rs b/crates/eps/src/ai_editing/writer.rs index 0091d0a37c..41254840cb 100644 --- a/crates/eps/src/ai_editing/writer.rs +++ b/crates/eps/src/ai_editing/writer.rs @@ -45,7 +45,8 @@ pub(super) use images::PAYLOAD; pub(super) use images::{IMAGE_DEPTH, IMAGES, LAST_SAMPLES_ONLY, LINKS_EMBEDDED, SAMPLE_LIMITS, SAMPLE_READS, SAMPLES_KEPT}; #[cfg(test)] pub(super) use paints::{ - GRADIENT_DITHER, GRADIENT_HUE, GRADIENT_PERCEPTUAL, GRADIENT_SHAPES, GRADIENTS, STOP_LINKS, SWATCH_PLACEMENT, free_gradient_name, + GRADIENT_COMPARISONS, GRADIENT_DITHER, GRADIENT_HUE, GRADIENT_PERCEPTUAL, GRADIENT_SHAPES, GRADIENTS, SCANNED_DEFINITIONS, STOP_LINKS, + SWATCH_PLACEMENT, free_gradient_name, }; #[cfg(test)] pub(super) use symbols::{MISSING_SYMBOL, SYMBOL_ART, SYMBOL_COUNT, SYMBOL_OPTIONS}; @@ -200,11 +201,11 @@ pub(super) struct Writer<'a> { /// pattern's definition, the pattern's space turned y up. canvas: Affine, /// The gradient definitions, in the order they are first used. - gradients: Vec, + gradients: paints::GradientDefs, /// The number the next new gradient definition's name tries first (1 is `Gradient`). next_gradient: u64, /// The pattern definitions written, each after those its art uses. - patterns: Vec, + patterns: paints::PatternDefs, /// The patterns whose definitions are being written. defining: Vec, /// Writing the palette: the definitions it adds are for its swatches only. @@ -357,9 +358,9 @@ impl<'a> Writer<'a> { grad_space: to_art, tile_grad_space: Affine::translate((-origin.0, origin.1)), canvas: Affine::new([1.0, 0.0, 0.0, -1.0, origin.0, origin.1]) * to_art, - gradients: vec![], + gradients: paints::GradientDefs::default(), next_gradient: 1, - patterns: vec![], + patterns: paints::PatternDefs::default(), defining: vec![], in_palette: false, canvas_origin: origin, diff --git a/crates/eps/src/ai_editing/writer/paints.rs b/crates/eps/src/ai_editing/writer/paints.rs index 1d5651b596..5a850d7db3 100644 --- a/crates/eps/src/ai_editing/writer/paints.rs +++ b/crates/eps/src/ai_editing/writer/paints.rs @@ -1,7 +1,9 @@ //! Gradients and patterns: their definitions in the setup, gradient instances on paths and the //! pattern operators (see [`crate::ai_editing`] for the form). +use std::collections::HashMap; use std::fmt::Write; +use std::hash::{Hash, Hasher}; use vectorcraft_color::gradient::GradientGeom; use vectorcraft_color::swatch::REGISTRATION; @@ -46,6 +48,134 @@ pub(super) struct PatternOut { used: bool, } +#[cfg(test)] +thread_local! { + /// Whether [`GradientDefs`] and [`PatternDefs`] find definitions on this thread by comparing + /// the gradient or name with each definition in turn. + pub(in crate::ai_editing) static SCANNED_DEFINITIONS: std::cell::Cell = const { std::cell::Cell::new(false) }; + /// How many times [`GradientDefs::find`] has compared two gradients on this thread. + pub(in crate::ai_editing) static GRADIENT_COMPARISONS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Are gradients `a` and `b` the same? +fn same_gradient(a: &Gradient, b: &Gradient) -> bool { + #[cfg(test)] + GRADIENT_COMPARISONS.with(|c| c.set(c.get() + 1)); + a == b +} + +/// A key of `g` for [`GradientDefs`]: the same gradients have the same key (each number by its +/// bits, with -0 as 0); different gradients may share one. +fn gradient_key(g: &Gradient) -> u64 { + let bits = |x: f32| if x == 0.0 { 0 } else { x.to_bits() }; + let mut h = std::hash::DefaultHasher::new(); + std::mem::discriminant(&g.kind).hash(&mut h); + std::mem::discriminant(&g.method).hash(&mut h); + (g.dither, g.spread, g.repeats, g.stops.len()).hash(&mut h); + for s in &g.stops { + let (model, c) = match s.color { + Color::Rgb { r, g, b } => (0u8, [r, g, b, 0.0]), + Color::Cmyk { c, m, y, k } => (1, [c, m, y, k]), + Color::Gray { k } => (2, [k, 0.0, 0.0, 0.0]), + Color::Lab { l, a, b } => (3, [l, a, b, 0.0]), + }; + (model, c.map(bits), [s.offset, s.opacity, s.midpoint, s.tint].map(bits)).hash(&mut h); + (&s.swatch, s.plates.map(|p| p.map(bits))).hash(&mut h); + } + h.finish() +} + +/// The gradient definitions, in the order they are first used, found by name and by gradient +/// without comparing each one. +#[derive(Default)] +pub(super) struct GradientDefs { + list: Vec, + /// Each definition's place in `list`, by its name (no two definitions share one). + names: HashMap, + /// The places in `list` of the definitions no swatch names, in order, by their gradient's key + /// ([`gradient_key`]). + ramps: HashMap>, +} + +impl GradientDefs { + /// Is `name` a definition's name? + fn has_name(&self, name: &str) -> bool { + #[cfg(test)] + if SCANNED_DEFINITIONS.with(std::cell::Cell::get) { + return self.list.iter().any(|d| d.name == name); + } + self.names.contains_key(name) + } + + /// The place of the definition of `g`: the swatch `swatch` names when it is a gradient swatch + /// of the same gradient, else the first definition of the same gradient that no swatch names. + fn find(&self, g: &Gradient, swatch: Option<&str>) -> Option { + #[cfg(test)] + if SCANNED_DEFINITIONS.with(std::cell::Cell::get) { + return swatch + .and_then(|s| self.list.iter().position(|d| d.swatch && d.name == s && same_gradient(&d.gradient, g))) + .or_else(|| self.list.iter().position(|d| !d.swatch && same_gradient(&d.gradient, g))); + } + let held = |i: &usize, swatch: bool| self.list.get(*i).is_some_and(|d| d.swatch == swatch && same_gradient(&d.gradient, g)); + swatch + .and_then(|s| self.names.get(s).copied().filter(|i| held(i, true))) + .or_else(|| self.ramps.get(&gradient_key(g))?.iter().copied().find(|i| held(i, false))) + } + + /// Add `d`, whose name no definition has. + fn push(&mut self, d: GradientDef) { + let i = self.list.len(); + if !d.swatch { + self.ramps.entry(gradient_key(&d.gradient)).or_default().push(i); + } + self.names.insert(d.name.clone(), i); + self.list.push(d); + } + + /// Keep the first `len` definitions; the names of those removed are free again. + fn truncate(&mut self, len: usize) { + while self.list.len() > len { + let Some(d) = self.list.pop() else { break }; + self.names.remove(&d.name); + if !d.swatch { + // Places are added in order, so the removed definition's is the last of its key's. + let key = gradient_key(&d.gradient); + if let Some(places) = self.ramps.get_mut(&key) { + places.pop(); + if places.is_empty() { + self.ramps.remove(&key); + } + } + } + } + } +} + +/// The pattern definitions written, each after those its art uses, found by name. +#[derive(Default)] +pub(super) struct PatternDefs { + list: Vec, + /// Each definition's place in `list`, by its name (no two definitions share one). + names: HashMap, +} + +impl PatternDefs { + /// The place of pattern `name`'s definition. + fn find(&self, name: &str) -> Option { + #[cfg(test)] + if SCANNED_DEFINITIONS.with(std::cell::Cell::get) { + return self.list.iter().position(|p| p.name == name); + } + self.names.get(name).copied() + } + + /// Add `p`, whose name no definition has. + fn push(&mut self, p: PatternOut) { + self.names.insert(p.name.clone(), self.list.len()); + self.list.push(p); + } +} + pub(in crate::ai_editing) const DIAMOND: &str = "diamond gradients are written as radial gradients through their corners, with the same stops, in the editing data for other apps"; pub(in crate::ai_editing) const SPREAD: &str = "gradients that repeat or reflect are written with their stops repeated across the shape (at most 256 stops, padding past them) in the editing data for other apps"; @@ -118,7 +248,7 @@ impl Writer<'_> { && let stops = curve_as_stops(&g.gradient) && let gradient = stops.unrolled_within(crate::import::MAX_GRADIENT_STOPS) && writable_gradient(&gradient) - && !self.gradients.iter().any(|d| d.name == sw.name) + && !self.gradients.has_name(&sw.name) { self.gradients.push(GradientDef { name: sw.name.clone(), gradient: gradient.into_owned(), swatch: true, used: false }); } @@ -131,17 +261,14 @@ impl Writer<'_> { /// swatch or a pattern). fn define_gradient(&mut self, g: &Gradient, swatch: Option<&str>) -> String { let used = !self.in_palette; - let found = swatch - .and_then(|s| self.gradients.iter().position(|d| d.swatch && d.name == s && d.gradient == *g)) - .or_else(|| self.gradients.iter().position(|d| !d.swatch && d.gradient == *g)); - if let Some(d) = found.and_then(|i| self.gradients.get_mut(i)) { + let found = self.gradients.find(g, swatch); + if let Some(d) = found.and_then(|i| self.gradients.list.get_mut(i)) { d.used |= used; return d.name.clone(); } let (doc, gradients) = (self.doc, &self.gradients); - let name = free_gradient_name(&mut self.next_gradient, |name| { - gradients.iter().any(|d| d.name == name) || doc.swatch(name).is_some() || doc.pattern(name).is_some() - }); + let name = + free_gradient_name(&mut self.next_gradient, |name| gradients.has_name(name) || doc.swatch(name).is_some() || doc.pattern(name).is_some()); self.gradients.push(GradientDef { name: name.clone(), gradient: g.clone(), swatch: false, used }); name } @@ -149,14 +276,14 @@ impl Writer<'_> { /// The gradient definitions' state, for [`Self::gradient_rollback`]: their count, which ones the /// art uses, and the next name's number. pub(super) fn gradient_mark(&self) -> (usize, Vec, u64) { - (self.gradients.len(), self.gradients.iter().map(|d| d.used).collect(), self.next_gradient) + (self.gradients.list.len(), self.gradients.list.iter().map(|d| d.used).collect(), self.next_gradient) } /// The gradient definitions as they were at `mark` ([`Self::gradient_mark`]). pub(super) fn gradient_rollback(&mut self, mark: (usize, Vec, u64)) { let (len, used, next) = mark; self.gradients.truncate(len); - for (d, u) in self.gradients.iter_mut().zip(used) { + for (d, u) in self.gradients.list.iter_mut().zip(used) { d.used = u; } self.next_gradient = next; @@ -476,7 +603,7 @@ impl Writer<'_> { if !self.defining.is_empty() || self.nest >= MAX_NEST || self.in_symbol { return false; } - if self.patterns.iter().any(|p| p.name == name) { + if self.patterns.find(name).is_some() { return true; } self.doc.pattern(name).is_some_and(tile_holds_art) @@ -492,7 +619,7 @@ impl Writer<'_> { return false; } let used = !self.in_palette; - if let Some(p) = self.patterns.iter_mut().find(|p| p.name == name) { + if let Some(p) = self.patterns.find(name).and_then(|i| self.patterns.list.get_mut(i)) { p.used |= used; return true; } @@ -582,7 +709,7 @@ impl Writer<'_> { /// uses). pub(in crate::ai_editing) fn definitions(&mut self, s: &mut String) { let defs = std::mem::take(&mut self.gradients); - let (used, unused): (Vec<&GradientDef>, Vec<&GradientDef>) = defs.iter().partition(|d| d.used); + let (used, unused): (Vec<&GradientDef>, Vec<&GradientDef>) = defs.list.iter().partition(|d| d.used); let _ = writeln!(s, "{} Bn", used.len()); for d in &used { self.gradient_def(s, d); @@ -595,12 +722,12 @@ impl Writer<'_> { s.push_str("%AI5_End_NonPrinting--\n"); } self.gradients = defs; - for p in self.patterns.iter().filter(|p| p.used) { + for p in self.patterns.list.iter().filter(|p| p.used) { s.push_str(&p.text); } - if self.patterns.iter().any(|p| !p.used) { + if self.patterns.list.iter().any(|p| !p.used) { s.push_str("%AI5_Begin_NonPrinting\nNp\n"); - for p in self.patterns.iter().filter(|p| !p.used) { + for p in self.patterns.list.iter().filter(|p| !p.used) { s.push_str(&p.text); } s.push_str("%AI5_End_NonPrinting--\n"); @@ -729,3 +856,94 @@ fn tile_holds_art(def: &PatternDef) -> bool { b.x0 >= room.x0 && b.y0 >= room.y0 && b.x1 <= room.x1 && b.y1 <= room.y1 }) } + +#[cfg(test)] +mod tests { + use super::*; + + fn two(a: f32, b: Color) -> Gradient { + Gradient::new(GradientKind::Linear, vec![GradientStop::new(a, Color::rgb(0.2, 0.4, 0.6)), GradientStop::new(1.0, b)]) + } + + fn def(name: &str, gradient: Gradient, swatch: bool) -> GradientDef { + GradientDef { name: name.into(), gradient, swatch, used: true } + } + + /// The same gradients have the same key, a zero of either sign included. + #[test] + fn a_zero_of_either_sign_gives_the_same_key() { + assert_eq!(gradient_key(&two(0.0, Color::BLACK)), gradient_key(&two(-0.0, Color::BLACK))); + assert_eq!(two(0.0, Color::BLACK), two(-0.0, Color::BLACK)); + assert_ne!(gradient_key(&two(0.0, Color::BLACK)), gradient_key(&two(0.0, Color::WHITE))); + } + + /// Definitions whose gradients share a key are told apart by their gradients, the first of the + /// same gradient found; a gradient that isn't equal to itself is found in none. + #[test] + fn definitions_that_share_a_key_are_told_apart() { + let (black, white) = (two(0.0, Color::BLACK), two(0.0, Color::WHITE)); + let mut defs = GradientDefs::default(); + defs.push(def("Gradient", white.clone(), false)); + defs.push(def("Gradient 2", black.clone(), false)); + defs.push(def("Gradient 3", black.clone(), false)); + // Every definition under the black gradient's key, as if the keys of both were the same. + defs.ramps = HashMap::from([(gradient_key(&black), vec![0, 1, 2])]); + assert_eq!(defs.find(&black, None), Some(1)); + assert_eq!(defs.find(&white, None), None); + defs.ramps.insert(gradient_key(&white), vec![0, 1, 2]); + assert_eq!(defs.find(&white, None), Some(0)); + let nan = two(f32::NAN, Color::BLACK); + defs.push(def("Gradient 4", nan.clone(), false)); + assert_eq!(defs.find(&nan, None), None); + } + + /// A swatch's definition is found by the swatch's name and gradient; a definition that no + /// swatch names, for the same gradient without the name or with another. + #[test] + fn a_swatch_definition_is_found_by_its_name_and_gradient() { + let (black, white) = (two(0.0, Color::BLACK), two(0.0, Color::WHITE)); + let mut defs = GradientDefs::default(); + defs.push(def("Ramp", black.clone(), true)); + assert_eq!(defs.find(&black, Some("Ramp")), Some(0)); + assert_eq!(defs.find(&black, None), None); + assert_eq!(defs.find(&white, Some("Ramp")), None); + defs.push(def("Gradient", black.clone(), false)); + defs.push(def("Gradient 2", white.clone(), false)); + assert_eq!(defs.find(&black, Some("Ramp")), Some(0)); + assert_eq!(defs.find(&black, None), Some(1)); + assert_eq!(defs.find(&white, Some("Ramp")), Some(2)); + assert_eq!(defs.find(&black, Some("Other")), Some(1)); + } + + /// Definitions removed leave their names free and are no longer found; those kept still are. + #[test] + fn removed_definitions_free_their_names() { + let (black, white) = (two(0.0, Color::BLACK), two(0.0, Color::WHITE)); + let mut defs = GradientDefs::default(); + defs.push(def("Ramp", white.clone(), true)); + defs.push(def("Gradient", black.clone(), false)); + defs.push(def("Gradient 2", white.clone(), false)); + defs.push(def("Gradient 3", black.clone(), false)); + defs.truncate(2); + assert!(defs.has_name("Ramp") && defs.has_name("Gradient")); + assert!(!defs.has_name("Gradient 2") && !defs.has_name("Gradient 3")); + assert_eq!(defs.find(&black, None), Some(1)); + assert_eq!(defs.find(&white, None), None); + assert_eq!(defs.ramps.values().map(Vec::len).sum::(), 1); + defs.push(def("Gradient 2", white.clone(), false)); + assert_eq!(defs.find(&white, None), Some(2)); + defs.truncate(0); + assert!(defs.list.is_empty() && defs.names.is_empty() && defs.ramps.is_empty()); + } + + /// A pattern's definition is found by its name. + #[test] + fn pattern_definitions_are_found_by_name() { + let mut defs = PatternDefs::default(); + assert_eq!(defs.find("Dots"), None); + for name in ["Dots", "Checks"] { + defs.push(PatternOut { name: name.into(), text: String::new(), used: false }); + } + assert_eq!((defs.find("Dots"), defs.find("Checks"), defs.find("Stripes")), (Some(0), Some(1), None)); + } +} diff --git a/crates/eps/src/import.rs b/crates/eps/src/import.rs index ba38492f77..d835b457c0 100644 --- a/crates/eps/src/import.rs +++ b/crates/eps/src/import.rs @@ -70,6 +70,8 @@ mod tests_native; #[cfg(test)] mod tests_reads; #[cfg(test)] +mod tests_strings; +#[cfg(test)] mod tests_type1; #[cfg(test)] mod tests_type42; diff --git a/crates/eps/src/import/data/ops.rs b/crates/eps/src/import/data/ops.rs index c4fc09e0b0..cca8bb50ea 100644 --- a/crates/eps/src/import/data/ops.rs +++ b/crates/eps/src/import/data/ops.rs @@ -146,13 +146,21 @@ impl Interp<'_> { fn token(&mut self) -> Res { match self.pop()? { Obj::Str(s) => { - let bytes = s.to_vec(); - let mut lex = Lexer::new(&bytes); - let Some(o) = lex.next()? else { return self.push(Obj::Bool(false)) }; - let o = self.scanned(o, lex.immediate)?; - // The whitespace after the token is read with it. - let used = bytes.len() - lex.data().len(); - self.push_interval(Obj::Str(s), used, bytes.len() - used)?; + // The scanner reads the string in place. The borrow ends before `scanned`, which + // can fail or charge the budget, and before the results are pushed. + let read = { + let bytes = s.borrow(); + let mut lex = Lexer::new(&bytes); + // The whitespace after the token is read with it. + lex.next()?.map(|o| { + let immediate = lex.immediate; + let rest = lex.data().len(); + (o, immediate, bytes.len() - rest, rest) + }) + }; + let Some((o, immediate, used, rest)) = read else { return self.push(Obj::Bool(false)) }; + let o = self.scanned(o, immediate)?; + self.push_interval(Obj::Str(s), used, rest)?; self.push(o)?; } Obj::File { stream: f, .. } => { diff --git a/crates/eps/src/import/interp.rs b/crates/eps/src/import/interp.rs index 43346988ff..8d883a0bff 100644 --- a/crates/eps/src/import/interp.rs +++ b/crates/eps/src/import/interp.rs @@ -753,21 +753,25 @@ impl<'a> Interp<'a> { } fn search_string(&mut self, op: Op) -> Res { - let seek = self.pop_str()?.to_vec(); + let seek = self.pop_str()?; let s = self.pop_str()?; - let text = s.to_vec(); - self.spend((text.len() / 64) as u64)?; - let at = if op == Op::Search { super::lex::find(&text, &seek) } else { text.starts_with(&seek).then_some(0) }; + // Both strings are read in place, and the borrows end before the results are pushed. + let (len, n, at) = { + let (text, seek) = (s.borrow(), seek.borrow()); + self.spend((text.len() / 64) as u64)?; + let at = if op == Op::Search { super::lex::find(&text, &seek) } else { text.starts_with(&seek).then_some(0) }; + (text.len(), seek.len(), at) + }; match at { Some(i) => { let o = Obj::Str(s); if op == Op::Search { - self.push_interval(o.clone(), i + seek.len(), text.len() - i - seek.len())?; - self.push_interval(o.clone(), i, seek.len())?; + self.push_interval(o.clone(), i + n, len - i - n)?; + self.push_interval(o.clone(), i, n)?; self.push_interval(o, 0, i)?; } else { - self.push_interval(o.clone(), seek.len(), text.len() - seek.len())?; - self.push_interval(o, 0, seek.len())?; + self.push_interval(o.clone(), n, len - n)?; + self.push_interval(o, 0, n)?; } self.push(Obj::Bool(true))?; } diff --git a/crates/eps/src/import/obj.rs b/crates/eps/src/import/obj.rs index 2b3ae92c73..1fcd41dd85 100644 --- a/crates/eps/src/import/obj.rs +++ b/crates/eps/src/import/obj.rs @@ -49,6 +49,8 @@ thread_local! { /// Tests: the arrays of the list last released on this thread that were still alive after it /// (the ones the interpreter itself still held). pub(crate) static ARRAYS_LEFT: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// Tests: how many values [`Shared::to_vec`] has copied on this thread. + pub(crate) static VALUES_COPIED: std::cell::Cell = const { std::cell::Cell::new(0) }; } thread_local! { @@ -340,7 +342,10 @@ impl Shared { } pub fn to_vec(&self) -> Vec { - self.borrow().to_vec() + let v = self.borrow().to_vec(); + #[cfg(test)] + VALUES_COPIED.with(|n| n.set(n.get() + v.len())); + v } /// `n` values from `at`, sharing the storage (`getinterval`); `None` past the end. diff --git a/crates/eps/src/import/tests_strings.rs b/crates/eps/src/import/tests_strings.rs new file mode 100644 index 0000000000..2a07dafd7c --- /dev/null +++ b/crates/eps/src/import/tests_strings.rs @@ -0,0 +1,306 @@ +//! `token` on a string, `search` and `anchorsearch` (PLRM 3rd ed., pp. 702-703, 655 and 529) read +//! their strings in place. The tests run them next to reference readers that copy the strings +//! first, on the same operands in the same interpreter state: the operand stack, the error and the +//! operations spent must agree. + +use std::hash::{DefaultHasher, Hash, Hasher}; +use std::time::{Duration, Instant}; + +use vectorcraft_doc::Document; +use vectorcraft_geom::{Affine, Rect}; + +use super::graphics::{GState, Out}; +use super::interp::Interp; +use super::lex::Lexer; +use super::obj::{Obj, Op, PsError, Res, Shared, VALUES_COPIED}; + +/// An interpreter that has run `src`, with the operands it left. +fn after(src: &[u8]) -> Interp<'_> { + let mut doc = Document::new(100.0, 100.0); + doc.layers.clear(); + let page = Affine::new([1.0, 0.0, 0.0, -1.0, 0.0, 100.0]); + let mut it = Interp::new(src, GState::default(), Out::new(doc, page, Rect::new(0.0, 0.0, 100.0, 100.0))); + assert_eq!(it.run(), Ok(()), "{}", String::from_utf8_lossy(src)); + it +} + +/// The reference `token`: the string copied before it is scanned. +fn token_by_copy(it: &mut Interp) -> Res { + match it.pop()? { + Obj::Str(s) => { + let bytes = s.to_vec(); + let mut lex = Lexer::new(&bytes); + let Some(o) = lex.next()? else { return it.push(Obj::Bool(false)) }; + let o = it.scanned(o, lex.immediate)?; + let used = bytes.len() - lex.data().len(); + it.push_interval(Obj::Str(s), used, bytes.len() - used)?; + it.push(o)?; + } + Obj::File { stream: f, .. } => { + let (o, immediate) = it.next_in(&f)?; + let Some(o) = o else { return it.push(Obj::Bool(false)) }; + let o = it.scanned(o, immediate)?; + it.push(o)?; + } + _ => return Err(PsError::Ps("typecheck", "token".into())), + } + it.push(Obj::Bool(true)) +} + +/// The reference `search` and `anchorsearch`: both strings copied before they are compared. +fn search_by_copy(it: &mut Interp, op: Op) -> Res { + let seek = it.pop_str()?.to_vec(); + let s = it.pop_str()?; + let text = s.to_vec(); + it.spend((text.len() / 64) as u64)?; + let at = if op == Op::Search { super::lex::find(&text, &seek) } else { text.starts_with(&seek).then_some(0) }; + match at { + Some(i) => { + let o = Obj::Str(s); + if op == Op::Search { + it.push_interval(o.clone(), i + seek.len(), text.len() - i - seek.len())?; + it.push_interval(o.clone(), i, seek.len())?; + it.push_interval(o, 0, i)?; + } else { + it.push_interval(o.clone(), seek.len(), text.len() - seek.len())?; + it.push_interval(o, 0, seek.len())?; + } + it.push(Obj::Bool(true))?; + } + None => { + it.push(Obj::Str(s))?; + it.push(Obj::Bool(false))?; + } + } + Ok(()) +} + +fn by_copy(it: &mut Interp, op: Op) -> Res { + if op == Op::Token { token_by_copy(it) } else { search_by_copy(it, op) } +} + +/// The error's name, or the limit reached. +fn outcome(r: Res) -> Result<(), String> { + r.map_err(|e| match e { + PsError::Ps(name, _) => name.to_string(), + e => format!("{e:?}"), + }) +} + +/// Everything the operator left: the operand stack with each string's storage, offset and length, +/// and the operations spent. +fn state(it: &Interp) -> (String, u64) { + (format!("{:?}", it.stack), it.ops_left()) +} + +/// Run `op` on the operands `src` leaves, in place and by copy, `steps` times (a walk that feeds +/// each call the string the last one left), and check that the two agree after every call. +fn agree(src: &str, op: Op, steps: usize) { + let (mut new, mut old) = (after(src.as_bytes()), after(src.as_bytes())); + // `search` and `anchorsearch` look for the same string on each call. + let seeks = [new.stack.last().cloned(), old.stack.last().cloned()]; + for step in 0..steps { + let (a, b) = (outcome(new.op(op)), outcome(by_copy(&mut old, op))); + assert_eq!(a, b, "{src} {op:?}, call {step}"); + assert_eq!(state(&new), state(&old), "{src} {op:?}, call {step}"); + // Keep walking while the operator answered true, with the string it left. + let more = matches!(new.stack.last(), Some(Obj::Bool(true))); + if a.is_err() || !more { + break; + } + for (it, seek) in [&mut new, &mut old].into_iter().zip(&seeks) { + it.stack.pop(); + // `token` leaves the rest under the object; `search` leaves it under match and pre + // (and `anchorsearch` under the match). + let keep = it.stack.len() - if op == Op::Search { 2 } else { 1 }; + it.stack.truncate(keep); + // The string to look for again, or the file `token` reads on from. + if op != Op::Token || matches!(seek, Some(Obj::File { .. })) { + it.stack.extend(seek.clone()); + } + } + } + new.release(); + old.release(); +} + +#[test] +fn token_and_search_agree_with_copying_readers() { + let tokens = [ + "()", + "( )", + "(\r\n\t )", + "(12)", + "(12 34)", + "(12 34)", + "(12\r\n34)", + "(/x {a b} (s) <41> 1.5 x)", + "(1 {)", + "( [ 1 ] )", + "/x 7 def (//x {//x} y)", + "(xx12 34 56) 2 7 getinterval", + "(%comment only)", + "5", + "(12 /x {a}) /ReusableStreamDecode filter", + "currentfile", + ]; + for src in tokens { + agree(src, Op::Token, 16); + } + let searches = [ + "(abcabc) (bc)", + "(abc) (x)", + "(abc) ()", + "() ()", + "() (a)", + "(ab) (abc)", + "(a\nb\nc\n) (\n)", + "/s (aa) def s s", + "(xxab cd ef) 2 8 getinterval ( )", + "(abc) 5", + "5 (abc)", + ]; + for src in searches { + agree(src, Op::Search, 8); + agree(src, Op::AnchorSearch, 8); + } + // Over the operation budget: the same error, with the same operands popped. + let big = "/h 65536 string def h (\\001)"; + let (mut new, mut old) = (after(big.as_bytes()), after(big.as_bytes())); + for it in [&mut new, &mut old] { + let left = it.ops_left(); + assert_eq!(it.spend(left.saturating_sub(10)), Ok(())); + } + let (a, b) = (outcome(new.op(Op::Search)), outcome(by_copy(&mut old, Op::Search))); + assert!(a.as_ref().is_err_and(|e| e.contains("too long")), "{a:?}"); + assert_eq!((a, state(&new)), (b, state(&old))); + new.release(); + old.release(); +} + +/// The results share the string's storage: a write to the string after `token` or `search` shows +/// in what they left. +#[test] +fn token_and_search_results_see_later_writes() { + let check = super::tests::check; + check("/s (12 34) def s token pop pop /post exch def s 3 57 put post token pop exch pop 94 eq"); + check("/s (ab cd) def s ( ) search pop /pre exch def pop /post exch def s 0 120 put s 4 121 put pre (xb) eq post (cy) eq and"); + check("/s (ab cd) def s (ab) anchorsearch pop pop /post exch def s 4 122 put post ( cz) eq"); + check("/s (xx12 34) def s 2 5 getinterval token pop pop /post exch def s 5 57 put post token pop exch pop 94 eq"); +} + +/// `token` on a string, `search` and `anchorsearch` copy neither string. +#[test] +fn token_and_search_copy_no_string() { + for (src, op) in [ + ("(12 34 56 78)", Op::Token), + ("(abc def ghi) ( )", Op::Search), + ("(abc def ghi) (xyz)", Op::Search), + ("(abc def ghi) (abc)", Op::AnchorSearch), + ("(abc def ghi) (def)", Op::AnchorSearch), + ] { + let mut it = after(src.as_bytes()); + VALUES_COPIED.with(|n| n.set(0)); + assert_eq!(it.op(op), Ok(()), "{src} {op:?}"); + assert_eq!(VALUES_COPIED.with(std::cell::Cell::get), 0, "{src} {op:?}"); + it.release(); + } +} + +/// The median of `runs`. +fn median(runs: &[Duration]) -> Duration { + let mut sorted = runs.to_vec(); + sorted.sort(); + sorted.get(sorted.len() / 2).copied().unwrap_or_default() +} + +/// What a walk records of each result: a string's length and first bytes, any other object whole. +fn mark(o: &Obj, h: &mut impl Hasher) { + match o { + Obj::Str(s) => { + s.len().hash(h); + s.borrow().iter().take(16).for_each(|b| b.hash(h)); + } + o => format!("{o:?}").hash(h), + } +} + +/// Walk `data` with `op` and `seek` (none for `token`) until the operator answers false, by copy +/// or in place: how long it took, the calls made, and a hash of every result and of the operations +/// spent. The interpreter is made before the clock starts. +fn walk(data: &[u8], op: Op, seek: Option<&[u8]>, copy: bool) -> (Duration, usize, u64) { + let mut it = after(b""); + it.stack.push(Obj::Str(Shared::new(data.to_vec()))); + let mut calls = 0; + let mut h = DefaultHasher::new(); + let start = Instant::now(); + loop { + if let Some(seek) = seek { + it.stack.push(Obj::Str(Shared::new(seek.to_vec()))); + } + let r = if copy { by_copy(&mut it, op) } else { it.op(op) }; + assert_eq!(r, Ok(())); + calls += 1; + if !matches!(it.stack.pop(), Some(Obj::Bool(true))) { + break; + } + let keep = it.stack.len() - if op == Op::Search { 2 } else { 1 }; + it.stack.iter().for_each(|o| mark(o, &mut h)); + it.stack.truncate(keep); + } + let took = start.elapsed(); + it.stack.iter().for_each(|o| mark(o, &mut h)); + it.ops_left().hash(&mut h); + it.release(); + (took, calls, h.finish()) +} + +/// Time both readers on `data` in 7 runs, alternating which goes first, check that they leave the +/// same, and print every run and the medians. +fn compare(what: &str, data: &[u8], op: Op, seek: Option<&[u8]>) { + let (mut old, mut new) = (vec![], vec![]); + let mut calls = 0; + for run in 0..7 { + let order: [bool; 2] = if run % 2 == 0 { [true, false] } else { [false, true] }; + let mut got = vec![]; + for copy in order { + let (took, n, last) = walk(data, op, seek, copy); + if copy { + old.push(took) + } else { + new.push(took) + } + calls = n; + got.push((n, last)); + } + assert!(got.first() == got.get(1), "{what}: the readers differ"); + } + let ms = |d: &Duration| format!("{:.2}", d.as_secs_f64() * 1000.0); + println!("{what}: {} bytes, {calls} calls", data.len()); + println!(" by copy, ms: {}", old.iter().map(ms).collect::>().join(" ")); + println!(" in place, ms: {}", new.iter().map(ms).collect::>().join(" ")); + let (o, w) = (median(&old), median(&new)); + println!(" median: by copy {} ms, in place {} ms, {:.1}x", ms(&o), ms(&w), o.as_secs_f64() / w.as_secs_f64().max(1e-9)); +} + +/// Times `token` and `search` walking a string by what each call leaves, against the copying +/// reference readers, in one process: strings of 4 KiB, 64 KiB and 512 KiB, of numbers and names +/// for `token` and of 128-byte lines for `search`. Run it in release: +/// `cargo test --release -p vectorcraft-eps --lib tests_strings::string_walks_timed -- --ignored --nocapture`. +#[test] +#[ignore = "manual timing probe; wall-clock performance depends on machine load"] +fn string_walks_timed() { + for kib in [4, 64, 512] { + let size = kib * 1024; + let mut words = Vec::with_capacity(size + 16); + let mut i = 0u32; + while words.len() < size { + let w = if i.is_multiple_of(2) { format!("{} ", i.wrapping_mul(2_654_435_761) % 100_000) } else { format!("/n{i} ") }; + words.extend_from_slice(w.as_bytes()); + i += 1; + } + compare(&format!("token, {kib} KiB"), &words, Op::Token, None); + let lines: Vec = (0..size / 128).flat_map(|i| format!("{:<127}\n", format!("line {i}")).into_bytes()).collect(); + compare(&format!("search, {kib} KiB"), &lines, Op::Search, Some(b"\n")); + } +} diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rs index 56b2f95944..a8d6cc86e6 100644 --- a/crates/mcp/src/tests.rs +++ b/crates/mcp/src/tests.rs @@ -1636,6 +1636,33 @@ fn doc_json(s: &mut Server) -> Value { serde_json::from_str(&text_of(&r)).unwrap() } +#[test] +fn transform_refused_by_a_later_operation_changes_nothing() { + let mut s = server(); + let count = |s: &mut Server| -> u64 { + let r = call(s, 90, "inspect_document", json!({})); + serde_json::from_str::(&text_of(&r)).unwrap()["objects"].as_u64().unwrap() + }; + let base = count(&mut s); + let r = id_of(&call(&mut s, 1, "draw_shape", json!({"shape": "rectangle", "x": 100, "y": 100, "width": 100, "height": 50}))); + let before = doc_json(&mut s); + for (id, args, says) in [ + (2, json!({"ids": [r], "scale": 50, "shear": 90}), "object.shear"), + (3, json!({"ids": [r], "dx": 10, "rotate": 30, "shear": -270}), "object.shear"), + (4, json!({"ids": [r], "scale": 50, "shear": 400}), "object.shear"), + (5, json!({"ids": [r], "scale": 50, "reflect": "diagonal"}), "object.reflect"), + (6, json!({"ids": [r], "dx": 10, "rotate": 30, "scaleX": 0}), "object.scale"), + ] { + let t = call(&mut s, id, "transform", args.clone()); + assert_eq!(t["isError"], true, "{args}: {t}"); + assert!(text_of(&t).contains(says), "{args}: {t}"); + assert_eq!(doc_json(&mut s), before, "{args}"); + } + // No undo step was recorded: one undo removes the rectangle. + assert_eq!(call(&mut s, 7, "undo", json!({}))["isError"], false); + assert_eq!(count(&mut s), base, "one undo removes the rectangle"); +} + #[test] fn add_text_rejects_invalid_path_effects_before_editing() { let mut s = server(); diff --git a/crates/mcp/src/tools/definitions.rs b/crates/mcp/src/tools/definitions.rs index 1b86095c6e..d730f8deaf 100644 --- a/crates/mcp/src/tools/definitions.rs +++ b/crates/mcp/src/tools/definitions.rs @@ -466,7 +466,7 @@ pub fn tool_definitions() -> Vec { tool( "transform", "Transform", - "Move, rotate, scale, reflect or shear the selection (or `ids`); several may be combined and run in that order. Angles in degrees (counter-clockwise), scale in %. Scale and reflect act along the selection's bounding box, turned with rotated objects until Reset Bounding Box. `origin` [x,y] defaults to the selection centre; `copy` transforms a copy.", + "Move, rotate, scale, reflect or shear the selection (or `ids`); several may be combined and run in that order. Angles in degrees (counter-clockwise), scale in %. Scale and reflect act along the selection's bounding box, turned with rotated objects until Reset Bounding Box. `origin` [x,y] defaults to the selection centre; `copy` transforms a copy. A scale, reflect or shear its command refuses returns that error before any step runs, and nothing changes.", obj( json!({ "ids": {"type": "array", "items": {"type": "integer"}}, diff --git a/crates/mcp/src/tools/handlers.rs b/crates/mcp/src/tools/handlers.rs index 8841c050ee..619af2e12e 100644 --- a/crates/mcp/src/tools/handlers.rs +++ b/crates/mcp/src/tools/handlers.rs @@ -302,6 +302,24 @@ pub(super) fn add_text(b: &mut dyn Backend, a: &Args) -> Result { } pub(super) fn transform(b: &mut dyn Backend, a: &Args) -> Result { + // Each operation is its own command: check the params the later ones refuse before the first + // runs, so a refused request changes nothing. + fn bad(cmd: &'static str) -> impl Fn(String) -> String { + move |e| format!("invalid parameters for `{cmd}`: {e}") + } + let s = a.get("scale").and_then(Value::as_f64); + let (sx, sy) = (a.get("scaleX").and_then(Value::as_f64).or(s), a.get("scaleY").and_then(Value::as_f64).or(s)); + if sx.is_some() || sy.is_some() { + vectorcraft_engine::cmd::scale_factors(sx.unwrap_or(100.0), sy.unwrap_or(100.0)).map_err(bad("object.scale"))?; + } + let reflect = a.get("reflect").and_then(Value::as_str); + if let Some(axis) = reflect { + vectorcraft_engine::cmd::reflect_axis(Some(&json!(axis))).map_err(bad("object.reflect"))?; + } + let shear = a.get("shear").and_then(Value::as_f64); + if let Some(sh) = shear { + vectorcraft_engine::cmd::shear_tangent(sh).map_err(bad("object.shear"))?; + } select_ids(b, a)?; // With `copy`, the first operation duplicates and the rest transform the copy (the new selection). let copy = std::cell::Cell::new(a.get("copy").and_then(Value::as_bool).unwrap_or(false)); @@ -322,17 +340,15 @@ pub(super) fn transform(b: &mut dyn Backend, a: &Args) -> Result exec(b, "object.rotate", with(json!({"angle": r})))?; done.push("rotate"); } - let s = a.get("scale").and_then(Value::as_f64); - let (sx, sy) = (a.get("scaleX").and_then(Value::as_f64).or(s), a.get("scaleY").and_then(Value::as_f64).or(s)); if sx.is_some() || sy.is_some() { exec(b, "object.scale", with(json!({"sx": sx.unwrap_or(100.0), "sy": sy.unwrap_or(100.0)})))?; done.push("scale"); } - if let Some(axis) = a.get("reflect").and_then(Value::as_str) { + if let Some(axis) = reflect { exec(b, "object.reflect", with(json!({"axis": axis})))?; done.push("reflect"); } - if let Some(sh) = a.get("shear").and_then(Value::as_f64) { + if let Some(sh) = shear { exec(b, "object.shear", with(json!({"angle": sh})))?; done.push("shear"); } diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index bb2c6b9927..4ff7aacecd 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -166,6 +166,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ ("app.home", "Home", "", "{} shows the Home screen (new file presets, Open) over the open documents; choosing a document tab returns to it"), ("edit.preferences", "Preferences…", "Cmd+K", "{category?} open Preferences (engine: prefs.get / prefs.set / prefs.list)"), ("edit.keyboardShortcuts", "Keyboard Shortcuts…", "Cmd+Alt+Shift+K", "{}"), + ( + "view.refreshMonitorProfile", + "Refresh Monitor Profile", + "", + "{} read the display's profile for Use Monitor Profile for Canvas (monitorProfileDisplay) again on the next frame, without waiting for the 10-second reading or the 1-second display check; while a reading runs, the request waits for it to end → {requested: true}, before the profile is read (ui.inspect › displayProfile reports the reading, and readRequested while it waits); an error while the preference is off, and where nothing reads the display's profile (the web build)", + ), ( "edit.autoSpellCheck", "Auto Spell Check", @@ -894,6 +900,25 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ ("help.about", "About VectorCraft", "", "{}"), ("help.checkForUpdates", "Check for Updates…", "", "{}"), ("help.commandPalette", "Search Commands…", "Cmd+Shift+/", "{}"), + ( + "help.discover", + "VectorCraft Help…", + "F1", + "{query?: string (at most 1024 characters, VectorCraft's limit)} show the Help panel without toggling it closed; a supplied query searches tools, menu commands, and built-in tutorials; omission keeps the current search. Returns {query, results: [{kind: tool|command|tutorial, id, label, path, shortcut}], selected: index|null}", + ), + ( + "help.discover.search", + "Search", + "", + "{query: string (at most 1024 characters, VectorCraft's limit)} search tools, menu commands, and built-in tutorials and show the Help panel; empty or whitespace-only text clears the results. Returns the help.discover result", + ), + ( + "help.discover.choose", + "Select", + "", + "{index: zero-based result index} show a tool's location, a tutorial's steps in Help, or a command's menu path and shortcut without running it; an invalid index is an error. Returns {result: chosen result, location: tool location, tutorial id, or command path}", + ), + ("help.discover.back", "Back", "", "{} return from a Help result to its search results without changing the query"), ( "help.safeMode", "Safe Mode…", @@ -947,7 +972,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.brushOptions", "Brush Options…", "", - "{name?} (default: the selected path's brush, else the current brush) open its Brush Options, what double-clicking a brush in the Brushes panel opens (dialog `brushOptions`): Calligraphic (fields name, angle −180..180, roundness 0..100, size 0..1296 pt, angleMode/roundnessMode/sizeMode: fixed|random|pressure, angleVariation/roundnessVariation/sizeVariation), Bristle (fields name, shape, size, length, density, thickness, opacity, stiffness), Scatter (fields sizeMin/sizeMax/sizeMode, spacingMin/spacingMax/spacingMode, scatterMin/scatterMax/scatterMode, rotationMin/rotationMax/rotationMode with modes fixed|random|pressure, rotationRelativeTo: page|path), Art (fields width %, scaleMode: proportional|stretch|betweenGuides, guideStart/guideEnd % of the art length, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flipAlong, flipAcross) or Pattern (fields scale %, spacing %, fit: stretch|addSpace|approximate, flipAlong, flipAcross); Scatter, Art and Pattern also colorization: none|tints|tintsAndShades|hueShift, keyColor, and tips: true opens Colorization Tips (what each method does, beside a sample of the brush painted with it), as the Tips button beside Method does; OK runs brush.options", + "{name?} (default: the selected path's brush, else the current brush) open its Brush Options, what double-clicking a brush in the Brushes panel opens (dialog `brushOptions`): Calligraphic (fields name, angle −180..180, roundness 0..100, size 0..1296 pt, angleMode/roundnessMode/sizeMode: fixed|random|pressure, angleVariation/roundnessVariation/sizeVariation), Bristle (fields name, shape, size, length, density, thickness, opacity, stiffness), Scatter (fields sizeMin/sizeMax/sizeMode, spacingMin/spacingMax/spacingMode, scatterMin/scatterMax/scatterMode, rotationMin/rotationMax/rotationMode with modes fixed|random|pressure, rotationRelativeTo: page|path, hueJitter 0..180°), Art (fields width %, scaleMode: proportional|stretch|betweenGuides, guideStart/guideEnd % of the art length, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flipAlong, flipAcross) or Pattern (fields scale %, spacing %, fit: stretch|addSpace|approximate, flipAlong, flipAcross); Scatter, Art and Pattern also colorization: none|tints|tintsAndShades|hueShift, keyColor, and tips: true opens Colorization Tips (what each method does, beside a sample of the brush painted with it), as the Tips button beside Method does; OK runs brush.options", ), ( "ui.brushObjectOptions", @@ -1001,7 +1026,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.symbolOptions", "Symbol Options…", "F8", - "{name?} open Symbol Options (dialog `symbolOptions`, fields `name`, `exportType`: movieClip|graphic, `registration` 0..8). Without `name` and with a selection: New Symbol (default name the first free \"New Symbol\"/\"New Symbol N\", Export Type Movie Clip, Registration centre); OK runs symbol.new {name, exportType, registration}. With `edit: true` or `name`: edit that symbol; OK runs symbol.options {name, newName?, exportType, registration}", + "{name?, edit?, keepArt?: false} open Symbol Options (dialog `symbolOptions`, fields `name`, `exportType`: movieClip|graphic, `registration` 0..8). Without `name` and with a selection: New Symbol (default name the first free \"New Symbol\"/\"New Symbol N\", Export Type Movie Clip, Registration centre); OK runs symbol.new {name, exportType, registration}, with keepArt: true when it was opened with keepArt: true (the selection stays ordinary art). With `edit: true` or `name`: edit that symbol; OK runs symbol.options {name, newName?, exportType, registration}; keepArt: true is then an error", ), ( "tool.options", diff --git a/crates/pathops/src/addons/pathtools.rs b/crates/pathops/src/addons/pathtools.rs index 87cc5ba56f..d8ad6ae8e4 100644 --- a/crates/pathops/src/addons/pathtools.rs +++ b/crates/pathops/src/addons/pathtools.rs @@ -4,10 +4,12 @@ //! tool shows over a path, open paths lengthened or shortened at an end ([`extend`]), the places //! where paths cross ([`crossings`]), the stretches between them ([`spans`]), anchors slid along //! their path ([`slide`]), touching edges merged ([`shared_edge`]), paths divided into dashes -//! ([`divide_dashes`]), the common tangents of two convex outlines ([`common_tangents`]), the +//! ([`divide_dashes`]), two circles joined by a smooth bridge ([`smooth_bridge`]), the common +//! tangents of two convex outlines ([`common_tangents`]), the //! Parametric Shape Tool's shapes ([`shapes`]) and the circles that touch two or three shapes //! ([`tangent_circles`]). +mod bridge; mod crossings; mod dashes; mod extend; @@ -25,6 +27,7 @@ use std::collections::BTreeSet; use kurbo::{CubicBez, ParamCurve, ParamCurveArclen, ParamCurveNearest, Point, Vec2}; use vectorcraft_geom::{Anchor, AnchorKind, PathData, SubPath}; +pub use bridge::{BridgeError, circle_of, smooth_bridge}; pub use crossings::{MAX_CROSSED_BY_SEGMENTS, MAX_CROSSING_SEGMENTS, Place, Work, crossings, crossings_on, crossings_on_within, insert_at}; pub use dashes::{DashSpec, Piece, divide_dashes}; pub use extend::{ExtendMode, extend_length_to, extend_open}; diff --git a/crates/pathops/src/addons/pathtools/bridge.rs b/crates/pathops/src/addons/pathtools/bridge.rs new file mode 100644 index 0000000000..43ee629a91 --- /dev/null +++ b/crates/pathops/src/addons/pathtools/bridge.rs @@ -0,0 +1,365 @@ +//! Smooth Bridge: two circles joined into one outline by two concave arcs, each touching both +//! circles from outside, so the outline runs on smoothly from each circle into the bridge. + +use std::f64::consts::{FRAC_PI_2, PI, SQRT_2, TAU}; + +use kurbo::{CubicBez, ParamCurve, Point, Shape, Vec2}; +use vectorcraft_geom::{Anchor, AnchorKind, PathData, SubPath}; + +use super::Circle; + +/// How far (as a share of the radius) a path's outline may stray from a circle and still be read +/// as that circle. +const ROUND: f64 = 1e-3; +/// Points [`circle_of`] checks on each segment, its ends included. +const SAMPLES: usize = 9; + +/// Why [`smooth_bridge`] makes no outline. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum BridgeError { + /// One circle is inside the other (or they share a center). + Inside, + /// The circles are too far apart for the radius: the two arcs would not reach both circles, + /// or would cross before they do. + TooFar, + /// A radius or circle that is not a finite size above 0, or an outline too large for `f64`. + Bad, +} + +/// The circle `path` draws: one closed subpath whose outline stays within 0.1% of its radius of +/// a circle all the way around, once. `None` for any other path. +pub fn circle_of(path: &PathData) -> Option { + let [sp] = path.subpaths.as_slice() else { return None }; + if !sp.closed || sp.anchors.len() < 2 { + return None; + } + let b = path.bounds()?; + let (w, h) = (b.width(), b.height()); + if !(w > 0.0 && h > 0.0 && w.is_finite() && h.is_finite()) || (w - h).abs() > ROUND * w.max(h) { + return None; + } + let (center, radius) = (b.center(), (w + h) / 4.0); + let off = |q: Point| (q.distance(center) - radius).abs() > ROUND * radius; + for k in 0..sp.segment_count() { + let seg = sp.segment(k); + if (0..SAMPLES).any(|i| off(seg.eval(i as f64 / (SAMPLES - 1) as f64))) { + return None; + } + } + // Around once: a path going around twice, or back on itself, encloses a different area. + let area = path.to_bezpath().area().abs(); + ((area - PI * radius * radius).abs() <= 4.0 * ROUND * area).then_some(Circle { center, radius }) +} + +/// The outline of circles `a` and `b` joined by two arcs of radius `radius` (pt), one on each +/// side of the line through their centers, each touching both circles from outside. The outline +/// runs around `a` on its side away from `b`, along one arc, around `b` on its side away from `a` +/// and back along the other arc; every anchor is smooth, as each arc and the circle it meets share +/// a tangent there. Overlapping and touching circles are joined too. A larger radius makes a wider, +/// gentler bridge; farther apart circles make a narrower one, until the arcs would cross. +pub fn smooth_bridge(a: Circle, b: Circle, radius: f64) -> Result { + let finite = |x: f64| x.is_finite() && x > 0.0; + let points = [a.center, b.center].iter().all(|c| c.x.is_finite() && c.y.is_finite()); + if !finite(radius) || !finite(a.radius) || !finite(b.radius) || !points { + return Err(BridgeError::Bad); + } + let axis = b.center - a.center; + // `f64::hypot`: `Vec2::hypot` squares the length, which overflows above about 1e154 pt. + let d = axis.x.hypot(axis.y); + if d + a.radius.min(b.radius) <= a.radius.max(b.radius) * (1.0 + 1e-9) { + return Err(BridgeError::Inside); + } + // The arcs' centers are `radius` outside both circles: where circles about the two centers, + // `radius` larger than each, cross. + let (ra, rb) = (radius + a.radius, radius + b.radius); + if !ra.is_finite() || !rb.is_finite() { + return Err(BridgeError::Bad); + } + // Halves and no squares, so no step overflows while the lengths fit in `f64`. + let half = ra / 2.0 + rb / 2.0; + if d / 2.0 > half { + return Err(BridgeError::TooFar); + } + let along = d / 2.0 + (ra - rb) / d * half; + let across = (ra - along).max(0.0).sqrt() * (ra / 2.0 + along / 2.0).max(0.0).sqrt() * SQRT_2; + if !along.is_finite() || !across.is_finite() { + return Err(BridgeError::Bad); + } + // Each arc runs between its points on `a` and `b`, which lie towards the two centers from the + // arc's center. Its point nearest the axis is the foot of its center on the axis when that foot + // is between the two centers, else one of its ends, which are off the axis. So the two arcs + // cross, leaving no neck, only when that foot is between the centers and nearer to the arc's + // center than its radius. + if along > 0.0 && along < d && across <= radius * (1.0 + 1e-9) { + return Err(BridgeError::TooFar); + } + let u = axis / d; + let n = Vec2::new(-u.y, u.x); + let mut segs = vec![]; + // Each side's arc center and where its arc touches `a` and `b`. + let side = |s: f64| { + let p = a.center + u * along + n * (s * across); + (p, a.center + (p - a.center) * (a.radius / ra), b.center + (p - b.center) * (b.radius / rb)) + }; + let ((p1, a1, b1), (p2, a2, b2)) = (side(1.0), side(-1.0)); + arc(&mut segs, a.center, a.radius, a1, a2, Some(-u)); + arc(&mut segs, p2, radius, a2, b2, None); + arc(&mut segs, b.center, b.radius, b2, b1, Some(u)); + arc(&mut segs, p1, radius, b1, a1, None); + let count = segs.len(); + let anchors: Vec = (0..count) + .map(|i| { + let (prev, seg) = (segs[(i + count - 1) % count], segs[i]); + Anchor { p: seg.p0, h_in: prev.p2, h_out: seg.p1, kind: AnchorKind::Smooth } + }) + .collect(); + let finite_point = |p: Point| p.x.is_finite() && p.y.is_finite(); + if !anchors.iter().all(|q| finite_point(q.p) && finite_point(q.h_in) && finite_point(q.h_out)) { + return Err(BridgeError::Bad); + } + Ok(SubPath::new(anchors, true)) +} + +/// Append to `out` the arc of the circle about `center` with radius `r` from `from` to `to` (both +/// on it): through the direction `through` from the center when given, else the shorter way. In +/// cubics of at most a quarter turn each, `from` exactly at the start and `to` at the end. +fn arc(out: &mut Vec, center: Point, r: f64, from: Point, to: Point, through: Option) { + let angle = |q: Vec2| q.y.atan2(q.x); + let start = angle(from - center); + // The turn from `from` to `to` counter-clockwise (in the y-up sense), 0 to 2π. + let ccw = (angle(to - center) - start).rem_euclid(TAU); + let sweep = match through { + Some(dir) if (angle(dir) - start).rem_euclid(TAU) <= ccw => ccw, + Some(_) => ccw - TAU, + None if ccw > PI => ccw - TAU, + None => ccw, + }; + let pieces = (sweep.abs() / FRAC_PI_2).ceil().max(1.0) as usize; + let step = sweep / pieces as f64; + // Handle length that makes a cubic follow the arc of `step`, signed with its direction. + let k = 4.0 / 3.0 * (step / 4.0).tan() * r; + let on = |t: f64| center + Vec2::new(t.cos(), t.sin()) * r; + let tangent = |t: f64| Vec2::new(-t.sin(), t.cos()); + for i in 0..pieces { + let (t0, t1) = (start + step * i as f64, start + step * (i + 1) as f64); + let p0 = if i == 0 { from } else { on(t0) }; + let p3 = if i + 1 == pieces { to } else { on(t1) }; + out.push(CubicBez::new(p0, p0 + tangent(t0) * k, p3 - tangent(t1) * k, p3)); + } +} + +#[cfg(test)] +mod tests { + use vectorcraft_geom::shapes; + + use super::*; + + fn circle(x: f64, y: f64, r: f64) -> Circle { + Circle { center: Point::new(x, y), radius: r } + } + + /// Every point the outline passes through, 32 to a segment. + fn outline(sp: &SubPath) -> Vec { + (0..sp.segment_count()).flat_map(|k| (0..32).map(move |i| sp.segment(k).eval(i as f64 / 32.0))).collect() + } + + /// The outline crosses the vertical line at `x` at these y values, top to bottom. + fn crossings_at(sp: &SubPath, x: f64) -> Vec { + let pts = outline(sp); + let mut ys: Vec = (0..pts.len()) + .filter_map(|i| { + let (p, q) = (pts[i], pts[(i + 1) % pts.len()]); + ((p.x - x) * (q.x - x) <= 0.0 && p.x != q.x).then(|| p.y + (q.y - p.y) * (x - p.x) / (q.x - p.x)) + }) + .collect(); + ys.sort_by(f64::total_cmp); + ys + } + + /// The bridge's width at `x`, from the outline's crossings there. + fn width_at(sp: &SubPath, x: f64) -> f64 { + let ys = crossings_at(sp, x); + ys.last().unwrap() - ys.first().unwrap() + } + + fn assert_smooth(sp: &SubPath) { + for a in sp.anchors.iter() { + let (i, o) = (a.p - a.h_in, a.h_out - a.p); + assert!(i.hypot() > 1e-6 && o.hypot() > 1e-6, "both handles at {a:?}"); + assert!(i.cross(o).abs() <= 1e-9 * i.hypot() * o.hypot() && i.dot(o) > 0.0, "the outline turns at {a:?}"); + assert_eq!(a.kind, AnchorKind::Smooth); + } + } + + /// Each point of the outline is on circle `c` or outside it. + fn outside(sp: &SubPath, c: Circle) -> bool { + outline(sp).iter().all(|p| p.distance(c.center) >= c.radius - 1e-3) + } + + #[test] + fn two_equal_circles_join_with_a_neck_narrower_than_the_circles() { + let (a, b) = (circle(0.0, 0.0, 20.0), circle(60.0, 0.0, 20.0)); + let sp = smooth_bridge(a, b, 20.0).unwrap(); + assert!(sp.closed); + assert_smooth(&sp); + // The arcs' centers are 40 from each circle's center: (30, ±√700), so the neck at x = 30 is + // 2 × (√700 − 20) wide. + let neck = 2.0 * (700f64.sqrt() - 20.0); + assert!((width_at(&sp, 30.0) - neck).abs() < 1e-2, "{}", width_at(&sp, 30.0)); + assert!(width_at(&sp, 30.0) < width_at(&sp, 10.0)); + // Around each circle on its far side, and symmetric. + let ys = crossings_at(&sp, -10.0); + assert!((ys[0] + 300f64.sqrt()).abs() < 1e-2 && (ys[1] - 300f64.sqrt()).abs() < 1e-2, "{ys:?}"); + assert!((width_at(&sp, 50.0) - width_at(&sp, 10.0)).abs() < 1e-2); + let b = PathData::single(sp).bounds().unwrap(); + // Within the cubics' own error from a true circle (about 0.03% of the radius). + assert!((b.x0 + 20.0).abs() < 1e-2 && (b.x1 - 80.0).abs() < 1e-2 && (b.y1 - 20.0).abs() < 1e-2, "{b:?}"); + } + + #[test] + fn the_arcs_touch_both_circles_and_run_on_from_them() { + for (a, b, r) in [ + (circle(0.0, 0.0, 20.0), circle(60.0, 0.0, 20.0), 20.0), + (circle(10.0, 5.0, 30.0), circle(70.0, 40.0, 8.0), 40.0), + (circle(0.0, 0.0, 20.0), circle(30.0, 0.0, 15.0), 10.0), + ] { + let sp = smooth_bridge(a, b, r).unwrap(); + assert_smooth(&sp); + // The outline goes around the outside of both circles, never into either. + assert!(outside(&sp, a) && outside(&sp, b)); + // On each circle the outline leaves along the circle's tangent, where an arc takes over + // as well: two anchors on each circle are where an arc meets it. + for c in [a, b] { + let on: Vec<_> = sp.anchors.iter().filter(|q| (q.p.distance(c.center) - c.radius).abs() < 1e-6).collect(); + assert!(on.len() >= 2, "{}", on.len()); + for q in on { + let radial = q.p - c.center; + assert!(radial.dot(q.h_out - q.p).abs() <= 1e-6 * radial.hypot() * (q.h_out - q.p).hypot(), "{q:?}"); + } + } + assert!(sp.anchors.len() <= 12, "{}", sp.anchors.len()); + // Every segment off the two circles is part of an arc of radius `r` that touches both + // circles from outside: its center is `r` farther than each circle's radius from it. + let on = |q: Point, c: Circle| (q.distance(c.center) - c.radius).abs() < 1e-3; + let mut arcs = 0; + for k in 0..sp.segment_count() { + let seg = sp.segment(k); + let (p0, pm, p1) = (seg.eval(0.0), seg.eval(0.5), seg.eval(1.0)); + if on(pm, a) || on(pm, b) { + continue; + } + arcs += 1; + let (center, radius) = circumcircle(p0, pm, p1); + assert!((radius - r).abs() < 1e-2 * r, "radius {radius} for {r}"); + assert!((center.distance(a.center) - (r + a.radius)).abs() < 1e-2 * r, "touches {a:?}"); + assert!((center.distance(b.center) - (r + b.radius)).abs() < 1e-2 * r, "touches {b:?}"); + } + assert!((2..=4).contains(&arcs), "{arcs}"); + } + } + + /// The circle through three points: its center and radius. + fn circumcircle(p: Point, q: Point, s: Point) -> (Point, f64) { + let d = 2.0 * (p.x * (q.y - s.y) + q.x * (s.y - p.y) + s.x * (p.y - q.y)); + let sq = |v: Point| v.x * v.x + v.y * v.y; + let x = (sq(p) * (q.y - s.y) + sq(q) * (s.y - p.y) + sq(s) * (p.y - q.y)) / d; + let y = (sq(p) * (s.x - q.x) + sq(q) * (p.x - s.x) + sq(s) * (q.x - p.x)) / d; + let c = Point::new(x, y); + (c, c.distance(p)) + } + + #[test] + fn unequal_circles_join_round_both() { + let (a, b) = (circle(0.0, 0.0, 30.0), circle(70.0, 0.0, 10.0)); + let sp = smooth_bridge(a, b, 40.0).unwrap(); + assert_smooth(&sp); + let bounds = PathData::single(sp.clone()).bounds().unwrap(); + assert!((bounds.x0 + 30.0).abs() < 1e-2 && (bounds.x1 - 80.0).abs() < 1e-2 && (bounds.y0 + 30.0).abs() < 1e-2, "{bounds:?}"); + // The neck narrows from the big circle towards the small one. + assert!(width_at(&sp, 35.0) > width_at(&sp, 50.0)); + assert!(width_at(&sp, 50.0) < 20.0); + } + + #[test] + fn unequal_circles_join_at_large_radii_overlapping_or_not() { + // With a large radius the arcs' centers lie beyond the smaller circle, so the arcs never + // reach the axis even though their centers are nearer to it than their radius. + for (a, b, r) in [ + (circle(0.0, 0.0, 10.0), circle(25.0, 0.0, 30.0), 100.0), + (circle(0.0, 0.0, 30.0), circle(25.0, 0.0, 10.0), 30.0), + (circle(0.0, 0.0, 30.0), circle(25.0, 0.0, 10.0), 50.0), + (circle(0.0, 0.0, 30.0), circle(60.0, 0.0, 8.0), 300.0), + ] { + let sp = smooth_bridge(a, b, r).unwrap_or_else(|e| panic!("{a:?} {b:?} {r}: {e:?}")); + assert_smooth(&sp); + assert!(outside(&sp, a) && outside(&sp, b)); + // The outline crosses the axis only at the two far ends: it does not cross itself. + let pts = outline(&sp); + let crossings = (0..pts.len()).filter(|&i| (pts[i].y > 0.0) != (pts[(i + 1) % pts.len()].y > 0.0)).count(); + assert_eq!(crossings, 2, "{a:?} {b:?} {r}"); + // It encloses more than the larger circle. + let area = PathData::single(sp).to_bezpath().area().abs(); + assert!(area > PI * a.radius.max(b.radius).powi(2), "{area}"); + } + } + + #[test] + fn overlapping_and_touching_circles_are_joined() { + let (a, b) = (circle(0.0, 0.0, 20.0), circle(30.0, 0.0, 20.0)); + let sp = smooth_bridge(a, b, 10.0).unwrap(); + assert_smooth(&sp); + // The circles cross at x = 15, y = ±√175; the bridge fills in the notch there. + assert!(width_at(&sp, 15.0) > 2.0 * 175f64.sqrt()); + assert!(width_at(&sp, 15.0) < 40.0); + let touching = smooth_bridge(circle(0.0, 0.0, 20.0), circle(40.0, 0.0, 20.0), 10.0).unwrap(); + assert_smooth(&touching); + assert!(width_at(&touching, 20.0) > 1.0); + } + + #[test] + fn far_apart_circles_and_nested_ones_make_no_bridge() { + let (a, b) = (circle(0.0, 0.0, 10.0), circle(100.0, 0.0, 10.0)); + assert_eq!(smooth_bridge(a, b, 5.0), Err(BridgeError::TooFar), "arcs don't reach"); + // The arcs reach both circles (gap 80 < 2 × 45) but cross before they do. + assert_eq!(smooth_bridge(a, b, 45.0), Err(BridgeError::TooFar), "no neck left"); + // A large enough radius bridges them: the neck stays open above (d/2)² − r² over 2r = 120. + assert!(smooth_bridge(a, b, 130.0).is_ok()); + assert_eq!(smooth_bridge(circle(0.0, 0.0, 30.0), circle(5.0, 0.0, 10.0), 10.0), Err(BridgeError::Inside)); + assert_eq!(smooth_bridge(circle(0.0, 0.0, 30.0), circle(0.0, 0.0, 30.0), 10.0), Err(BridgeError::Inside)); + assert_eq!(smooth_bridge(a, b, 0.0), Err(BridgeError::Bad)); + assert_eq!(smooth_bridge(a, b, f64::NAN), Err(BridgeError::Bad)); + assert_eq!(smooth_bridge(circle(f64::INFINITY, 0.0, 10.0), b, 10.0), Err(BridgeError::Bad)); + } + + #[test] + fn huge_circles_bridge_with_finite_anchors_or_are_refused() { + // Squaring these lengths overflows f64. + let (a, b) = (circle(0.0, 0.0, 5e153), circle(1.5e154, 0.0, 5e153)); + let sp = smooth_bridge(a, b, 5e153).unwrap(); + assert!(sp.anchors.iter().all(|q| [q.p, q.h_in, q.h_out].iter().all(|p| p.x.is_finite() && p.y.is_finite()))); + assert_smooth(&sp); + // The two radius sums fit in f64, but not their total. + let (a, b) = (circle(-5e307, 0.0, 1e307), circle(5e307, 0.0, 1e307)); + let sp = smooth_bridge(a, b, 1.5e308).unwrap(); + assert!(sp.anchors.iter().all(|q| [q.p, q.h_in, q.h_out].iter().all(|p| p.x.is_finite() && p.y.is_finite()))); + // The arcs' centers would lie beyond the largest f64. + let (a, b) = (circle(0.0, 0.0, 1e308), circle(1.5e308, 0.0, 1e308)); + assert_eq!(smooth_bridge(a, b, 1e308), Err(BridgeError::Bad)); + } + + #[test] + fn circles_are_told_from_other_paths() { + let round = shapes::ellipse(kurbo::Rect::new(10.0, 20.0, 50.0, 60.0)); + let c = circle_of(&round).unwrap(); + assert!(c.center.distance(Point::new(30.0, 40.0)) < 1e-9 && (c.radius - 20.0).abs() < 1e-9); + let oval = shapes::ellipse(kurbo::Rect::new(0.0, 0.0, 50.0, 40.0)); + assert_eq!(circle_of(&oval), None); + let square = PathData::single(SubPath::polyline(&[Point::ZERO, Point::new(10.0, 0.0), Point::new(10.0, 10.0), Point::new(0.0, 10.0)], true)); + assert_eq!(circle_of(&square), None); + let mut open = round.clone(); + open.subpaths[0].closed = false; + assert_eq!(circle_of(&open), None); + let two = PathData::new(vec![round.subpaths[0].clone(), round.subpaths[0].clone()]); + assert_eq!(circle_of(&two), None); + } +} diff --git a/crates/pdf/src/editing.rs b/crates/pdf/src/editing.rs index a8dd48628c..2fccfb393c 100644 --- a/crates/pdf/src/editing.rs +++ b/crates/pdf/src/editing.rs @@ -27,8 +27,8 @@ const DESCRIPTION: &str = "VectorCraft editing data; page hash "; /// Stands for the hash while the PDF is written: as long as a hash, so writing the hash over it /// keeps every offset. const PLACEHOLDER: &str = "0000000000000000"; -/// Deepest name tree searched for the editing file. -const MAX_DEPTH: usize = 16; +/// The most name tree nodes searched for the editing file. +const MAX_NODES: usize = 1 << 16; /// The native document a PDF carries ([`crate::PdfSettings::preserve_editing`]). #[derive(Clone, Debug, PartialEq, Eq)] @@ -77,12 +77,50 @@ pub fn editing_with(bytes: &[u8], password: Option<&str>) -> Option { editing_in(&crate::pages::open(bytes, password).ok()?) } +/// What the search of a parsed PDF's attachments for the editing file found ([`editing_file_spec`]). +struct Search<'a> { + /// The editing file's file specification, if one was found. + spec: Option>, + /// A name tree key searched names the editing file (set also when its file specification + /// can't be read). + keyed: bool, + /// The name tree has more than [`MAX_NODES`] nodes, so nodes were left unsearched. + cut: bool, +} + +/// The search of a parsed PDF's attachments for the editing file. +fn editing_file_spec(pdf: &Pdf) -> Search<'_> { + let xref = pdf.xref(); + let Some(tree) = xref + .get::>(xref.root_id()) + .and_then(|catalog| catalog.get::>(b"Names")) + .and_then(|names| names.get::>(b"EmbeddedFiles")) + else { + return Search { spec: None, keyed: false, cut: false }; + }; + let (mut keyed, mut cut) = (false, false); + let spec = editing_spec(tree, &mut keyed, &mut cut, xref); + Search { spec, keyed, cut } +} + +/// Does a parsed PDF list the editing file among its attachments, also when [`editing_in`] can't +/// read it (its file specification, its `EF` dictionary or its `F` or `UF` stream can't be +/// resolved)? Also true when the name tree is too large to search to its end. +pub(crate) fn has_editing_file_in(pdf: &Pdf) -> bool { + let search = editing_file_spec(pdf); + search.spec.is_some() || search.keyed || search.cut +} + +/// Is a parsed PDF's attachment name tree too large to search to its end (more than [`MAX_NODES`] +/// nodes)? It may then list an editing file that [`editing_in`] doesn't find, besides the one it +/// reads. +pub(crate) fn editing_search_cut_in(pdf: &Pdf) -> bool { + editing_file_spec(pdf).cut +} + /// [`editing`] of a parsed PDF. pub(crate) fn editing_in(pdf: &Pdf) -> Option { - let xref = pdf.xref(); - let catalog = xref.get::>(xref.root_id())?; - let tree = catalog.get::>(b"Names")?.get::>(b"EmbeddedFiles")?; - let spec = editing_spec(&tree, 0, &mut HashSet::new(), xref)?; + let spec = editing_file_spec(pdf).spec?; let files = spec.get::>(b"EF")?; let stream = files.get::>(b"F").or_else(|| files.get::>(b"UF"))?; let data = stream.decoded().map(|d| d.into_owned()).unwrap_or_default(); @@ -96,10 +134,59 @@ pub(crate) fn editing_in(pdf: &Pdf) -> Option { Some(Editing { data, intact }) } -/// The file specification of the editing file in the name tree node `node`. `seen` holds the indirect -/// nodes already searched, so a node shared by many `Kids` arrays is searched once, not once per path. -fn editing_spec<'a>(node: &Dict<'a>, depth: usize, seen: &mut HashSet, xref: &'a XRef) -> Option> { +/// The first file specification of the editing file in the name tree `tree`, searched in order at +/// any depth, [`MAX_NODES`] nodes at most. After the editing file is found, the walk goes on to the +/// end of the tree, or to the node limit, without reading the nodes' `Names`. An indirect node is +/// searched once, so a node shared by many `Kids` arrays is not searched once per path. `keyed` is +/// set when a key searched names the editing file, and `cut` when nodes are left unsearched. +fn editing_spec<'a>(tree: Dict<'a>, keyed: &mut bool, cut: &mut bool, xref: &'a XRef) -> Option> { + let mut seen = HashSet::::new(); + let mut nodes = vec![tree]; + let mut found = None; + // Nodes still to be searched, counting the ones waiting in `nodes`. + let mut left = MAX_NODES - 1; + while let Some(node) = nodes.pop() { + // Once the editing file is found, only the `Kids` are read, to learn whether the tree is cut. + if found.is_none() { + found = node_spec(&node, keyed, xref); + } + let Some(kids) = node.get::>(b"Kids") else { continue }; + // Only a referenced kid can be shared (a direct kid's `obj_id` is the object holding it). The + // reference is checked before the kid is read, so a shared kid is read once. + let mut kids: Vec> = items(&kids) + .filter_map(|raw| match raw { + MaybeRef::Ref(r) if seen.insert(r.into()) => xref.get::>(r.into()), + MaybeRef::NotRef(Object::Dict(kid)) => Some(kid), + _ => None, + }) + .take(left.saturating_add(1)) + .collect(); + if kids.len() > left { + *cut = true; + kids.truncate(left); + } + left -= kids.len(); + nodes.extend(kids.into_iter().rev()); + } + found +} + +/// The file specification of the editing file among the name tree node `node`'s own `Names`. +/// `keyed` is set when a key names the editing file. +fn node_spec<'a>(node: &Dict<'a>, keyed: &mut bool, xref: &'a XRef) -> Option> { if let Some(names) = node.get::>(b"Names") { + // The keys read as written, so a value that can't be resolved doesn't shift the pairs. + let mut raw = items(&names); + while let (Some(key), Some(_)) = (raw.next(), raw.next()) { + let key = match key { + MaybeRef::NotRef(Object::String(key)) => Some(key), + MaybeRef::Ref(r) => xref.get::>(r.into()), + MaybeRef::NotRef(_) => None, + }; + if key.is_some_and(|key| is_editing_name(&key)) { + *keyed = true; + } + } let mut items = names.iter::>(); while let (Some(_), Some(spec)) = (items.next(), items.next()) { if let Object::Dict(spec) = spec @@ -109,29 +196,19 @@ fn editing_spec<'a>(node: &Dict<'a>, depth: usize, seen: &mut HashSet= MAX_DEPTH { - return None; - } - let kids = node.get::>(b"Kids")?; - // Only a referenced kid can be shared (a direct kid's `obj_id` is the object holding it). The - // reference is checked before the kid is read, so a shared kid is read once. - items(&kids).find_map(|raw| { - let kid = match raw { - MaybeRef::Ref(r) if seen.insert(r.into()) => xref.get::>(r.into())?, - MaybeRef::NotRef(Object::Dict(kid)) => kid, - _ => return None, - }; - editing_spec(&kid, depth + 1, seen, xref) - }) + None } /// A file specification naming the editing file (current or legacy name), in any text string /// encoding. fn is_editing_file(spec: &Dict<'_>) -> bool { - [&b"UF"[..], b"F"].into_iter().filter_map(|k| spec.get::>(k)).any(|name| { - let name = text_string(name.as_bytes()); - name == EDITING_FILE || name == LEGACY_EDITING_FILE - }) + [&b"UF"[..], b"F"].into_iter().filter_map(|k| spec.get::>(k)).any(|name| is_editing_name(&name)) +} + +/// A text string that is the editing file's name (current or legacy), in any encoding. +fn is_editing_name(name: &PdfString<'_>) -> bool { + let name = text_string(name.as_bytes()); + name == EDITING_FILE || name == LEGACY_EDITING_FILE } /// The most decoded page content [`page_hash`] reads in all (bytes). diff --git a/crates/pdf/src/export/writer.rs b/crates/pdf/src/export/writer.rs index b7c967989e..bd241421c7 100644 --- a/crates/pdf/src/export/writer.rs +++ b/crates/pdf/src/export/writer.rs @@ -64,8 +64,8 @@ pub(crate) struct Sheet<'a> { impl Writer { /// A PDF with `set`'s version, standard, compression and colour output, and `doc`'s metadata - /// under `title`, created at `created` (Unix seconds). With `cmyk`, transparency blends in - /// CMYK (unless the colours are converted to RGB). + /// and language under `title`, created at `created` (Unix seconds). With `cmyk`, transparency + /// blends in CMYK (unless the colours are converted to RGB). pub(crate) fn new(doc: &Document, set: &crate::PdfSettings, title: &str, created: Option, cmyk: bool) -> Result { let out = ColorOut::new(doc, set)?; let mut warnings = out.profile_notes.clone(); @@ -111,7 +111,11 @@ impl Writer { created: created.map(date_time), modified: None, }; - let pdf = write::Writer::new(settings, metadata); + // The document language (Document Setup) as the catalog's `Lang` and the XMP packet's + // `dc:language` (ISO 32000-1, 14.9.2): its BCP 47 tag. A language without a tag writes + // none rather than a guess. + let language = vectorcraft_doc::setup::language_tag(&doc.setup.language).map(str::to_string); + let pdf = write::Writer::new_with_language(settings, metadata, language); Ok(Self { pdf, cmyk: out.blends_cmyk(cmyk), diff --git a/crates/pdf/src/pages.rs b/crates/pdf/src/pages.rs index 470432aa8f..ec593baf24 100644 --- a/crates/pdf/src/pages.rs +++ b/crates/pdf/src/pages.rs @@ -261,6 +261,18 @@ impl Opened { crate::editing::editing_in(&self.pdf) } + /// Does the PDF list the editing file among its attachments, also when + /// [`editing`](Self::editing) can't read it? + pub fn has_editing_file(&self) -> bool { + crate::editing::has_editing_file_in(&self.pdf) + } + + /// Is the PDF's attachment name tree too large to search to its end? It may then list an + /// editing file that [`editing`](Self::editing) doesn't find, besides the one it reads. + pub fn editing_search_cut(&self) -> bool { + crate::editing::editing_search_cut_in(&self.pdf) + } + /// The private data of an Illustrator `.ai`, as [`illustrator_data`] reads it. pub fn illustrator_data(&self) -> Option> { private_data(&self.pdf) diff --git a/crates/pdf/src/tests.rs b/crates/pdf/src/tests.rs index 91c037ad84..e2abe87637 100644 --- a/crates/pdf/src/tests.rs +++ b/crates/pdf/src/tests.rs @@ -1449,6 +1449,41 @@ fn empty_and_populated_file_info_preserve_key_presence() { assert!(s.contains("/ViewerPreferences<>"), "viewers should show the document title (#3646)"); } +/// The text of the `/Lang` entry of the catalog of `pdf` (a literal string), if any. +fn catalog_lang(pdf: &[u8]) -> Option { + let xref = crate::patch::Xref::read(pdf).expect("a cross-reference table"); + let root = xref.trailer_ref(pdf, b"/Root").expect("a catalog"); + let (start, end) = xref.dict(pdf, root).expect("the catalog's dictionary"); + let catalog = String::from_utf8_lossy(&pdf[start..end]).into_owned(); + let at = catalog.find("/Lang")? + "/Lang".len(); + let rest = catalog[at..].trim_start().strip_prefix('(').expect("a literal string"); + Some(rest[..rest.find(')').expect("a closed string")].to_string()) +} + +/// The catalog gives the document language chosen in Document Setup as its BCP 47 tag, in +/// exported and printed PDFs, and the XMP packet says it too (#3644). +#[test] +fn the_catalog_gives_the_document_language() { + let mut d = doc(100.0, 100.0); + for (language, tag) in [(None, "en-US"), (Some("French"), "fr"), (Some("German: Swiss"), "de-CH")] { + if let Some(language) = language { + d.setup.language = language.into(); + } + for opts in [PdfOptions::uncompressed(), PdfOptions::default()] { + let bytes = export(&d, &opts).unwrap(); + assert_eq!(catalog_lang(&bytes).as_deref(), Some(tag), "{language:?}"); + } + // Print to PDF writes its file with the same writer. + let printed = print(&d, &PrintOptions { created: Some(1_700_000_000), ..Default::default() }).unwrap(); + assert_eq!(catalog_lang(&printed.bytes).as_deref(), Some(tag), "{language:?}: printed"); + let s = uncompressed(&d); + assert!(s.contains(&format!("{tag}")), "{language:?}: {s}"); + } + // A language without a tag (from a file) writes none rather than a guess. + d.setup.language = "Klingon".into(); + assert_eq!(catalog_lang(&export(&d, &PdfOptions::uncompressed()).unwrap()), None); +} + /// A function or colour space built on itself is refused before the interpreter builds it (by /// recursion, with no cap: a stack overflow), and those of real files are read. #[test] diff --git a/crates/pdf/src/tests/editing.rs b/crates/pdf/src/tests/editing.rs index c4f2900709..b58c953c2f 100644 --- a/crates/pdf/src/tests/editing.rs +++ b/crates/pdf/src/tests/editing.rs @@ -237,3 +237,104 @@ fn a_file_name_written_as_utf16_is_found() { assert_eq!(e.data, b"hello", "/{key}"); } } + +#[test] +fn an_editing_file_whose_data_cannot_be_resolved_is_still_listed() { + // No `EF` dictionary, an `EF` without `F` or `UF`, and an `F` naming no object. + for ef in ["", "/EF << >>", "/EF << /F 9 0 R >>"] { + let objects = [ + "<< /Type /Catalog /Pages 2 0 R /Names << /EmbeddedFiles 3 0 R >> >>".to_string(), + "<< /Type /Pages /Kids [5 0 R] /Count 1 >>".to_string(), + "<< /Names [(a) 4 0 R] >>".to_string(), + format!("<< /Type /Filespec /UF ({EDITING_FILE}) {ef} >>"), + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 10 10] >>".to_string(), + ]; + let opened = open_pdf(&raw_pdf(&objects), None).unwrap(); + assert_eq!(opened.editing(), None, "{ef:?}"); + assert!(opened.has_editing_file(), "{ef:?}"); + } + // A name tree key naming it, with a file specification that names no object or isn't one. + for spec in ["9 0 R", "(not a file specification)"] { + let objects = [ + "<< /Type /Catalog /Pages 2 0 R /Names << /EmbeddedFiles 3 0 R >> >>".to_string(), + "<< /Type /Pages /Kids [4 0 R] /Count 1 >>".to_string(), + format!("<< /Names [(a) 9 0 R ({EDITING_FILE}) {spec}] >>"), + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 10 10] >>".to_string(), + ]; + let opened = open_pdf(&raw_pdf(&objects), None).unwrap(); + assert_eq!(opened.editing(), None, "{spec}"); + assert!(opened.has_editing_file(), "{spec}"); + } + // The key written as an indirect string. + let objects = [ + "<< /Type /Catalog /Pages 2 0 R /Names << /EmbeddedFiles 3 0 R >> >>".to_string(), + "<< /Type /Pages /Kids [4 0 R] /Count 1 >>".to_string(), + "<< /Names [5 0 R 9 0 R] >>".to_string(), + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 10 10] >>".to_string(), + format!("({EDITING_FILE})"), + ]; + assert!(open_pdf(&raw_pdf(&objects), None).unwrap().has_editing_file()); + // A PDF without the editing file, and one with it. + assert!(!open_pdf(&export(&doc(), &PdfOptions::default()).unwrap(), None).unwrap().has_editing_file()); + let opened = open_pdf(&pdf_with(Some(b"native"), false).bytes, None).unwrap(); + assert!(opened.editing().is_some() && opened.has_editing_file()); +} + +#[test] +fn an_editing_file_deep_in_the_name_tree_is_found() { + // Objects 4..=203 are a chain of 200 name tree nodes, each listing the next one; the editing + // file sits in the leaf (object 204), with its data or naming data that can't be resolved. + for ef in ["/EF << /F 206 0 R >>", "/EF << /F 999 0 R >>"] { + let mut objects = vec![ + "<< /Type /Catalog /Pages 2 0 R /Names << /EmbeddedFiles 3 0 R >> >>".to_string(), + "<< /Type /Pages /Kids [207 0 R] /Count 1 >>".to_string(), + "<< /Kids [4 0 R] >>".to_string(), + ]; + for node in 4..=203 { + objects.push(format!("<< /Kids [{} 0 R] >>", node + 1)); + } + objects.push("<< /Names [(a) 205 0 R] >>".to_string()); + objects.push(format!("<< /Type /Filespec /UF ({EDITING_FILE}) {ef} >>")); + objects.push("<< /Length 5 >>\nstream\nhello\nendstream".to_string()); + objects.push("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 10 10] >>".to_string()); + let opened = open_pdf(&raw_pdf(&objects), None).unwrap(); + assert!(opened.has_editing_file(), "{ef}"); + let data = opened.editing().map(|e| e.data); + assert_eq!(data.as_deref(), ef.contains("206").then_some(&b"hello"[..]), "{ef}"); + } + // A name tree with more nodes than are searched may list it. + let objects = [ + "<< /Type /Catalog /Pages 2 0 R /Names << /EmbeddedFiles 3 0 R >> >>".to_string(), + "<< /Type /Pages /Kids [4 0 R] /Count 1 >>".to_string(), + format!("<< /Kids [{}] >>", "<< /Names [] >> ".repeat(70_000)), + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 10 10] >>".to_string(), + ]; + let opened = open_pdf(&raw_pdf(&objects), None).unwrap(); + assert_eq!(opened.editing(), None); + assert!(opened.has_editing_file() && opened.editing_search_cut()); + // One that lists a readable editing file before the nodes left unsearched and another after + // them: the first is read, and the search reads as cut short. + let leaf = |stream: u32| format!("<< /Names [({EDITING_FILE}) << /Type /Filespec /UF ({EDITING_FILE}) /EF << /F {stream} 0 R >> >>] >>"); + let objects = [ + "<< /Type /Catalog /Pages 2 0 R /Names << /EmbeddedFiles 3 0 R >> >>".to_string(), + "<< /Type /Pages /Kids [8 0 R] /Count 1 >>".to_string(), + format!("<< /Kids [4 0 R {}5 0 R] >>", "<< /Names [] >> ".repeat(70_000)), + leaf(6), + leaf(7), + "<< /Length 5 >>\nstream\nfirst\nendstream".to_string(), + "<< /Length 6 >>\nstream\nsecond\nendstream".to_string(), + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 10 10] >>".to_string(), + ]; + let opened = open_pdf(&raw_pdf(&objects), None).unwrap(); + assert_eq!(opened.editing().map(|e| e.data).as_deref(), Some(&b"first"[..])); + assert!(opened.has_editing_file() && opened.editing_search_cut()); + // The same, with the nodes past the limit in a subtree after the one holding the first. + let mut objects = objects; + objects[2] = format!("<< /Kids [4 0 R << /Kids [{}5 0 R] >>] >>", "<< /Names [] >> ".repeat(70_000)); + let opened = open_pdf(&raw_pdf(&objects), None).unwrap(); + assert_eq!(opened.editing().map(|e| e.data).as_deref(), Some(&b"first"[..])); + assert!(opened.has_editing_file() && opened.editing_search_cut()); + // A tree searched to its end. + let opened = open_pdf(&pdf_with(Some(b"native"), false).bytes, None).unwrap(); + assert!(opened.editing().is_some() && !opened.editing_search_cut()); +} diff --git a/crates/plugins/src/lib.rs b/crates/plugins/src/lib.rs index b304e1721e..019dd0d858 100644 --- a/crates/plugins/src/lib.rs +++ b/crates/plugins/src/lib.rs @@ -53,7 +53,7 @@ pub mod wat; pub use dialog::ParamUi; pub use host::{LogLevel, LogLine, Report}; pub use manifest::{Budget, Command, InputKind, Kind, Manifest, Param, ParamSpec}; -pub use runtime::{ABI_VERSION, HEAVY_FUEL, HEAVY_WALL_TIME_MS, Limits, Plugin, heavy_terms}; +pub use runtime::{ABI_VERSION, HEAVY_FUEL, HEAVY_WALL_TIME_MS, LARGE_FUEL, Limits, Plugin, heavy_terms}; #[doc(hidden)] pub use runtime::{BYTES_COPIED_PER_FUEL, FUEL_SLICE}; diff --git a/crates/plugins/src/runtime.rs b/crates/plugins/src/runtime.rs index 5a2db2ff0d..0cb6197e97 100644 --- a/crates/plugins/src/runtime.rs +++ b/crates/plugins/src/runtime.rs @@ -35,6 +35,11 @@ pub const HEAVY_FUEL: u64 = 1_000_000_000; /// Wall-clock budget of a heavy filter's run, in milliseconds. pub const HEAVY_WALL_TIME_MS: u64 = 300_000; +/// Instructions a filter's run may use besides [`Limits::fuel_per_byte`] for each byte of input +/// when Preferences › Plug-ins & Scratch Disks › Plug-in Instruction Budget is Large +/// ([`Plugin::large_limits`]): 5 times the default. +pub const LARGE_FUEL: u64 = 250_000_000; + /// The limit a run reports when its input and parameters together are past half its memory. pub(crate) const SELECTION_TOO_LARGE: &str = "memory budget (the selection is too large to hand over)"; @@ -215,6 +220,12 @@ impl Plugin { pub fn limits(&self) -> &Limits { &self.limits } + /// Its limits with the Large instruction budget: at least [`LARGE_FUEL`] instructions besides + /// those for each byte of input, and every other limit, the time budget included, as it is. A + /// heavy filter keeps its larger budget. + pub fn large_limits(&self) -> Limits { + Limits { fuel_base: self.limits.fuel_base.max(LARGE_FUEL), ..self.limits.clone() } + } /// Module size in bytes. pub fn size(&self) -> usize { self.size diff --git a/crates/plugins/tests/abi.rs b/crates/plugins/tests/abi.rs index abc2cd05eb..26dec0a7d2 100644 --- a/crates/plugins/tests/abi.rs +++ b/crates/plugins/tests/abi.rs @@ -7,7 +7,7 @@ use std::time::{Duration, Instant}; use serde_json::{Value, json}; use vectorcraft_plugins::storage::{Meter, Storage, StorageError}; -use vectorcraft_plugins::{Error, HEAVY_FUEL, HEAVY_WALL_TIME_MS, Kind, Limits, Plugin, Report, heavy_terms, registry, wat as tpl}; +use vectorcraft_plugins::{Error, HEAVY_FUEL, HEAVY_WALL_TIME_MS, Kind, LARGE_FUEL, Limits, Plugin, Report, heavy_terms, registry, wat as tpl}; /// The example Desaturate plug-in, built from `crates/plugins/example`. const DESATURATE: &[u8] = include_bytes!("fixtures/desaturate.wasm"); @@ -259,6 +259,23 @@ fn a_heavy_filter_finishes_what_a_light_one_cannot() { assert_eq!(p.run(INPUT.as_bytes(), b"{}").unwrap(), INPUT.as_bytes()); } +/// The Large instruction budget gives a light filter 5 times the instructions besides those for +/// each byte of input, so it finishes 20 million steps of a loop that its own budget can't, in the +/// same time budget. A heavy filter keeps its larger budget, and every other limit stays. +#[test] +fn the_large_budget_finishes_what_a_light_one_cannot_and_keeps_a_heavy_one() { + let light = Plugin::load(&build(&tpl::spinning(MANIFEST, 20_000_000, INPUT)), Limits::default()).unwrap(); + assert_eq!(light.run(INPUT.as_bytes(), b"{}"), Err(Error::Limit("instruction budget".into()))); + let large = light.large_limits(); + assert_eq!(large, Limits { fuel_base: LARGE_FUEL, ..Limits::default() }); + assert_eq!(LARGE_FUEL, 5 * Limits::default().fuel_base); + assert_eq!(light.run_limited(INPUT.as_bytes(), b"{}", &large).unwrap(), INPUT.as_bytes()); + let heavy = r#"{"id":"test.heavy","name":"Heavy","version":"1","kind":"filter","budget":"heavy"}"#; + let heavy = Plugin::load(&build(&tpl::spinning(heavy, 1, INPUT)), Limits::default()).unwrap(); + assert_eq!(heavy.large_limits(), *heavy.limits()); + assert_eq!((heavy.large_limits().fuel_base, heavy.large_limits().wall_time_ms), (HEAVY_FUEL, HEAVY_WALL_TIME_MS)); +} + #[test] fn an_exporter_returns_its_file_with_an_export_s_budget() { use vectorcraft_plugins::export::{self, Target}; diff --git a/crates/render/src/encode/quantize.rs b/crates/render/src/encode/quantize.rs index 0c873fd598..dc459d4331 100644 --- a/crates/render/src/encode/quantize.rs +++ b/crates/render/src/encode/quantize.rs @@ -190,12 +190,13 @@ pub fn quantize_locked(rgba: &[u8], width: u32, height: u32, o: &PaletteOptions, /// [`quantize`] to the fixed `palette`: each pixel takes its nearest entry, with `o`'s dither, /// transparency and matte; `o.reduction` sets only the distance weights, and `o.colors` is not -/// used. Only the first 255 colors of `palette` are used, leaving room for the transparent entry. -/// Entries no pixel uses are left out. +/// used. Only the first 256 colors of `palette` are used, or the first 255 when a pixel becomes +/// transparent, leaving room for the transparent entry. Entries no pixel uses are left out. pub fn quantize_to(rgba: &[u8], width: u32, height: u32, o: &PaletteOptions, palette: &[[u8; 3]]) -> Indexed { let px = rgba.as_chunks::<4>().0; let colors = opaque_colors(px, o, false); - let mut palette: Vec<[u8; 3]> = palette.iter().take(255).copied().collect(); + let has_clear = o.transparency && px.iter().any(|p| p[3] < 128); + let mut palette: Vec<[u8; 3]> = palette.iter().take(256 - usize::from(has_clear)).copied().collect(); if palette.is_empty() { palette.push(o.matte.unwrap_or([255; 3])); } diff --git a/crates/render/src/encode/tests_palette.rs b/crates/render/src/encode/tests_palette.rs index 836b5fcf09..d9a8a2fc0f 100644 --- a/crates/render/src/encode/tests_palette.rs +++ b/crates/render/src/encode/tests_palette.rs @@ -102,11 +102,18 @@ fn a_given_palette_keeps_the_entries_pixels_use() { assert_eq!(ix.transparent, Some(0)); assert_eq!(ix.palette[1..], [[255, 0, 0], [0, 0, 255]], "unused entries left out, the order kept"); assert_eq!(ix.indices, [1, 2, 0, 1]); - // At most 255 of the given colors are used, leaving room for the transparent entry. + // With no transparent pixel all 256 of the given colors can be used; with one, the first 255 + // leave room for the transparent entry. let many: Vec<[u8; 3]> = (0..300u32).map(|i| [(i % 256) as u8, (i / 256) as u8, 0]).collect(); let all = image(256, 2, |x, y| [x as u8, y as u8, 0]); let ix = quantize_to(&all, 256, 2, &o, &many); - assert!(ix.palette.len() <= 255 && ix.palette.iter().all(|c| many[..255].contains(c)), "{}", ix.palette.len()); + assert!(ix.palette.len() == 256 && ix.palette.iter().all(|c| many[..256].contains(c)), "{}", ix.palette.len()); + assert!(ix.palette.contains(&many[255]), "the 256th color is used"); + let mut clear = all.clone(); + clear[3] = 0; + let ix = quantize_to(&clear, 256, 2, &o, &many); + assert_eq!(ix.transparent, Some(0)); + assert!(ix.palette.len() <= 256 && ix.palette[1..].iter().all(|c| many[..255].contains(c)), "{}", ix.palette.len()); } #[test] diff --git a/crates/three-d/src/lib.rs b/crates/three-d/src/lib.rs index 18d371b420..c6b00ed851 100644 --- a/crates/three-d/src/lib.rs +++ b/crates/three-d/src/lib.rs @@ -13,7 +13,7 @@ mod solid; mod visibility; pub use solid::{ Bevel, BevelShape, DepthPlane, Extrude, FaceMap, Facet, Inflate, MeshFace, PlanarFace, TOO_COMPLEX_SOLID, View, extrude, extrude_face_map, - extrude_mesh_face, inflate, inflate_each, inflate_together, plane, plane_face_map, plane_mesh_face, + extrude_mesh_face, extrude_side_size, inflate, inflate_each, inflate_together, plane, plane_face_map, plane_mesh_face, }; pub use visibility::{VisibleFace, visible_faces}; mod shading; @@ -389,7 +389,9 @@ pub struct Face { pub plane: Option, } -/// Where a face of Revolve's swept side lies on the side surface, unrolled flat: x runs around the +/// Where a face of a side surface lies on it unrolled flat, for the graphics mapped onto it. On +/// Extrude & Bevel's side ([`Facet::surface`]) x runs along the outline and y from the front toward +/// the back. On Revolve's swept side x runs around the /// axis and y along the profile, in points. x is the angle from the middle of the surface times the /// point's own distance from the axis, so a graphic keeps its size at every distance and wraps /// farther around the axis where the profile comes closer to it. y is the length along the profile diff --git a/crates/three-d/src/solid.rs b/crates/three-d/src/solid.rs index 59776a605e..1057d024bd 100644 --- a/crates/three-d/src/solid.rs +++ b/crates/three-d/src/solid.rs @@ -19,6 +19,7 @@ mod inflate; mod membrane; mod outline; mod rings; +mod side; #[cfg(test)] pub(crate) use build::EXTRUDED; @@ -27,7 +28,7 @@ pub(crate) use build::PLANES; #[cfg(test)] use build::{Camera, cuts, edge_distance, newell, section}; pub(crate) use build::{Face3, Keep, extrude_faces, plane_faces}; -pub use build::{extrude, plane}; +pub use build::{extrude, extrude_side_size, plane}; pub use face_map::{FaceMap, MeshFace, extrude_face_map, extrude_mesh_face, plane_face_map, plane_mesh_face}; pub(crate) use inflate::inflate_faces; #[cfg(test)] @@ -218,11 +219,14 @@ pub struct Extrude { /// Keep the faces of a closed solid that are turned away from the viewer (Draw Hidden Faces, /// and the classic Wireframe surface), drawn behind the faces turned toward it. pub hidden: bool, + /// Graphics are mapped onto the side: the pieces of the walls and bevels of the solid's longest + /// contour carry a [`Facet::surface`]. Off by default, which leaves the facets without one. + pub map_surface: bool, } impl Default for Extrude { fn default() -> Self { - Self { depth: 50.0, twist: 0.0, taper: 1.0, cap: true, bevel: None, hidden: false } + Self { depth: 50.0, twist: 0.0, taper: 1.0, cap: true, bevel: None, hidden: false, map_surface: false } } } @@ -253,21 +257,24 @@ impl Default for Inflate { } } -/// A planar face of a solid that a graphic can be mapped onto: Extrude & Bevel's front cap (the -/// art itself, or a plane's only face) or its back cap. +/// A face of a solid that a graphic can be mapped onto: Extrude & Bevel's front cap (the art itself, +/// or a plane's only face), its back cap, or its side (the walls and bevels, unrolled flat: +/// [`Facet::surface`]). Only the caps are planar. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum PlanarFace { Front, Back, + Side, } impl PlanarFace { - pub const ALL: [PlanarFace; 2] = [Self::Front, Self::Back]; + pub const ALL: [PlanarFace; 3] = [Self::Front, Self::Back, Self::Side]; pub fn id(self) -> &'static str { match self { Self::Front => "front", Self::Back => "back", + Self::Side => "side", } } @@ -300,13 +307,16 @@ pub struct Facet { /// The planar end of the solid the facet is: Extrude & Bevel's front or back cap, or a plane /// (its front). `None` for every other facet. pub end: Option, - /// For a piece of Inflate's front or puffed back built for graphics ([`Inflate::map_surface`]): - /// where its corners lie in the art's plane, as offsets from the center of the bounds the solid - /// was built with ([`crate::SurfaceCell`]). The back's corners are where they were in the art - /// before the twist and taper turned and scaled it. + /// For a piece of Extrude & Bevel's side built for graphics ([`Extrude::map_surface`]): where + /// its corners lie on the side unrolled flat, for a graphic mapped onto it. x runs along the + /// outline and y from the front toward the back ([`crate::SurfaceCell`]). For a piece of + /// Inflate's front or puffed back built for graphics ([`Inflate::map_surface`]): where its + /// corners lie in the art's plane, as offsets from the center of the bounds the solid was built + /// with. The back's corners are where they were in the art before the twist and taper turned + /// and scaled it. pub surface: Option, /// The face of Inflate's solid that a facet with a [`Facet::surface`] is a piece of: its front - /// or its puffed back. + /// or its puffed back. `None` for every other facet, Extrude & Bevel's side included. pub membrane: Option, /// The face's plane in view space and the projection it was drawn with, for its depth at a /// point of the drawing ([`Facet::depth_at`]). `None` for a face whose corners lie more than @@ -396,6 +406,7 @@ impl Facet { // A revolved cap is not one of the planar faces graphics map onto. end: None, away: false, + // Revolve's graphics are drawn from its faces, before they become facets. surface: None, membrane: None, plane: face.plane, diff --git a/crates/three-d/src/solid/build.rs b/crates/three-d/src/solid/build.rs index 9cff25bab5..ed68f9508e 100644 --- a/crates/three-d/src/solid/build.rs +++ b/crates/three-d/src/solid/build.rs @@ -5,6 +5,7 @@ use super::rings::{ CURVE_PIECES, MAX_PIECES, MAX_PLANE_POINTS, MAX_SOLID_POINTS, Ring, Span, TOO_COMPLEX_SURFACE, curve_pieces, inset, left, signed_area, solid_rings_traced, square_corners, }; +use super::side; use super::{ Bevel, DepthPlane, Extrude, Facet, FillRule, MAX_FACES, MAX_SOLID_FACES, ParamCurve, PathData, PlanarFace, Point, Rect, Revolve, V3, View, eye_distance, perspective_scale, @@ -251,11 +252,13 @@ impl<'a> Builder<'a> { /// wall with `cuts` (see [`cuts`]) as `cuts[i]` quads along edge `i`. `outward` is the /// direction (before rotation) the band faces away from the solid, for orienting normals. pub(super) fn band(&mut self, a: &[V3], b: &[V3], cuts: &[usize], outward: impl Fn(usize) -> V3) -> Result<(), String> { - self.curved_band(a, b, cuts, outward, None) + self.curved_band(a, b, cuts, outward, None, None) } /// [`Builder::band`], with `curves` the pieces of curve the rings' edges follow and the /// outlines at `a` and `b`: a quad whose edge is not cut keeps its edges along the profile curved. + /// With `side`, each quad carries where its corners lie on the side unrolled flat + /// ([`Facet::surface`]). pub(super) fn curved_band( &mut self, a: &[V3], @@ -263,6 +266,7 @@ impl<'a> Builder<'a> { cuts: &[usize], outward: impl Fn(usize) -> V3, mut curves: Option, + side: Option, ) -> Result<(), String> { let n = a.len().min(b.len()); // At 0 and 1, the corners themselves. @@ -297,6 +301,21 @@ impl<'a> Builder<'a> { && let Some(f) = self.facets.last_mut() { f.side = true; + if let Some(s) = side.as_ref() + && let (Some([x0, x1]), Some(page)) = (s.x.get(i).copied(), f.contours.first()) + { + let (u0, u1) = (x0 + (x1 - x0) * s0, x0 + (x1 - x0) * s1); + let [y0, y1] = s.y; + // The face shows the side's outside when it was neither turned around to + // show its inside (on a hollow solid) nor kept turned away. + let n = normal.unit(); + let outward = !f.away && f.normal[0] * n.0 + f.normal[1] * n.1 + f.normal[2] * n.2 > 0.0; + f.surface = Some(crate::SurfaceCell { + page: page.clone(), + uv: vec![Point::new(u0, y0), Point::new(u1, y0), Point::new(u1, y1), Point::new(u0, y1)], + outward, + }); + } } if let Some(w) = curves.as_mut().filter(|_| pieces == 1) && let Some(span) = w.spans.get(i).copied().flatten() @@ -355,6 +374,13 @@ pub(super) struct WallCurves<'a> { pub(super) budget: &'a mut Budget, } +/// Where a band of the side lies on the side unrolled flat ([`super::side`]): the x of each end of +/// each edge of its rings, and the y of its two rings. +pub(super) struct SideBand<'a> { + pub(super) x: &'a [[f64; 2]], + pub(super) y: [f64; 2], +} + /// Where a point of the art goes in view space at one step: [`Camera::place`] after a [`Turn`], /// at depth `z`, as one affine map worked out once for the step. pub(super) struct Placing { @@ -669,7 +695,17 @@ pub(crate) fn extrude_faces(path: &PathData, rule: FillRule, bounds: Rect, optio }) .collect(); let mut budget = Budget::default(); - for ((ring, traced), pieces) in rings.iter().zip(&traced).zip(&pieces) { + // With graphics on the side, the longest contour's pieces carry where they lie on it unrolled. + let unrolled = o + .map_surface + .then(|| { + let k = side::longest(&rings)?; + let y = side::across_steps(&steps.iter().map(|s| (s.inset, s.t)).collect::>(), o.depth); + Some((k, side::along_ring(rings.get(k)?)?, y)) + }) + .flatten(); + for (r, ((ring, traced), pieces)) in rings.iter().zip(&traced).zip(&pieces).enumerate() { + let unrolled = unrolled.as_ref().filter(|(k, ..)| *k == r); let placed: Vec> = steps.iter().map(|s| ring_at(ring, s)).collect(); for (k, pair) in placed.windows(2).enumerate() { let ([a, c], Some(s0), Some(s1)) = (pair, steps.get(k), steps.get(k + 1)) else { continue }; @@ -686,7 +722,8 @@ pub(crate) fn extrude_faces(path: &PathData, rule: FillRule, bounds: Rect, optio // stay straight, within the sampling tolerance. let (near, far) = (along.get(k).filter(|_| k == 0), along.get(k + 1).filter(|_| k + 2 == steps.len())); let curves = (near.is_some() || far.is_some()).then(|| WallCurves { spans: &traced.spans, near, far, budget: &mut budget }); - b.curved_band(a, c, pieces, |i| outward(ring, i, face), curves)?; + let side = unrolled.and_then(|(_, x, y)| Some(SideBand { x, y: [*y.get(k)?, *y.get(k + 1)?] })); + b.curved_band(a, c, pieces, |i| outward(ring, i, face), curves, side)?; } } if o.cap { @@ -707,6 +744,31 @@ pub(crate) fn extrude_faces(path: &PathData, rule: FillRule, bounds: Rect, optio Ok(b.finish()) } +/// The size of Extrude & Bevel's side unrolled flat ([`super::side`]), for a solid of `path` built +/// as [`extrude`] builds it: the length of its longest contour's outline, the length across its +/// bevels and walls, front to back, and the width about x = 0 that does not reach the side's cut. +/// `None` with a depth of 0, for invalid bounds, and for a shape [`extrude`] refuses. +pub fn extrude_side_size(path: &PathData, rule: FillRule, bounds: Rect, options: Extrude) -> Option<(f64, f64, f64)> { + check_bounds(bounds).ok()?; + let o = options.sanitized(); + if o.depth <= 0.0 { + return None; + } + let steps = steps(&o); + let (bands, caps) = (steps.len().saturating_sub(1), if o.cap { 2 } else { 0 }); + let size = bounds.width().max(bounds.height()); + let most = curve_pieces(path, size, bands, caps).ok()?; + let side = steps.iter().map(|s| s.inset).find(|w| *w != 0.0).unwrap_or(0.0); + let traced: Vec = solid_rings_traced(path, rule, size, MAX_SOLID_POINTS, most).ok()?.iter().map(|r| square_corners(r, side)).collect(); + let rings: Vec<&[Point]> = traced.iter().map(|r| r.points.as_slice()).collect(); + // A solid past the face limit is refused, as [`extrude_faces`] refuses it. + let edges = rings.iter().map(|r| r.len()).fold(0usize, usize::saturating_add); + if edges.saturating_mul(bands).saturating_add(caps) > MAX_SOLID_FACES { + return None; + } + side::size(&rings, &steps.iter().map(|s| (s.inset, s.t)).collect::>(), o.depth) +} + #[cfg(test)] thread_local! { /// How many Rotate planes (and Extrude & Bevel solids with no depth) this thread has built, for diff --git a/crates/three-d/src/solid/face_map.rs b/crates/three-d/src/solid/face_map.rs index ac99348ba3..51a6709df0 100644 --- a/crates/three-d/src/solid/face_map.rs +++ b/crates/three-d/src/solid/face_map.rs @@ -145,7 +145,8 @@ impl FaceMap { /// The map of Extrude & Bevel's cap `face` for a solid built with `bounds`, `options` and `view`, /// as [`super::extrude`] builds it. With a depth of 0 the art is a plane, whose only face is the -/// front. `None` for a hollow solid (no caps), for the back of a plane, and for invalid bounds. +/// front. `None` for a hollow solid (no caps), for the back of a plane, for the side (which is not +/// planar), and for invalid bounds. pub fn extrude_face_map(bounds: Rect, options: Extrude, view: View, face: PlanarFace) -> Option { check_bounds(bounds).ok()?; let o = options.sanitized(); @@ -159,6 +160,7 @@ pub fn extrude_face_map(bounds: Rect, options: Extrude, view: View, face: Planar let (t, side) = match face { PlanarFace::Front => (0.0, 1.0), PlanarFace::Back => (1.0, -1.0), + PlanarFace::Side => return None, }; let placing = Placing::new(&camera, bounds.center(), Turn::new(bounds, o.twist, o.taper, t), o.depth / 2.0 - o.depth * t); let at = placing.place(bounds.center()); @@ -235,7 +237,7 @@ impl MeshFace { /// Extrude & Bevel's cap `face` in the solid's mesh ([`MeshFace`]), for a solid built with /// `bounds`, `options` and `view`, as [`extrude_face_map`] maps it on the page. With a depth of 0 /// the art is a plane ([`plane_mesh_face`]). `None` for a hollow solid, for the back of a plane, -/// and for invalid bounds. +/// for the side, and for invalid bounds. pub fn extrude_mesh_face(bounds: Rect, options: Extrude, view: View, face: PlanarFace) -> Option { check_bounds(bounds).ok()?; let o = options.sanitized(); @@ -249,6 +251,7 @@ pub fn extrude_mesh_face(bounds: Rect, options: Extrude, view: View, face: Plana let (t, side) = match face { PlanarFace::Front => (0.0, 1.0), PlanarFace::Back => (1.0, -1.0), + PlanarFace::Side => return None, }; let placing = Placing::new(&camera, bounds.center(), Turn::new(bounds, o.twist, o.taper, t), o.depth / 2.0 - o.depth * t); Some(MeshFace::new(&camera, &placing, bounds.center(), side, false)) diff --git a/crates/three-d/src/solid/side.rs b/crates/three-d/src/solid/side.rs new file mode 100644 index 0000000000..2a285246ec --- /dev/null +++ b/crates/three-d/src/solid/side.rs @@ -0,0 +1,133 @@ +//! Extrude & Bevel's side unrolled flat, for the graphics mapped onto it ([`super::Facet::surface`]). +//! +//! x runs along the outline of the solid's longest contour, through its corners and curves, and y +//! runs from the front cap's edge toward the back cap's, across the bevels and the walls. Both are +//! lengths in points: x along the art's own outline (the front cap's edge, or with a bevel carved +//! into the shape the walls' outline), y along the outline's steps (the slant +//! of each bevel step and the depth of the walls), before the twist and the taper, which carry the +//! graphic with the side. x is 0 where the contour's top crosses the vertical line through the +//! middle of its bounds and grows clockwise around the outline as the front is seen on the page, so +//! a graphic reads the right way round from outside the side. y is 0 half way along the steps. The +//! side is cut at the anchor of the contour nearest half way around from x = 0. + +use super::rings::signed_area; +use super::{Point, Rect}; + +/// The length of the outline of `ring`. +fn perimeter(ring: &[Point]) -> f64 { + ring.iter().zip(ring.iter().cycle().skip(1)).take(ring.len()).map(|(a, b)| a.distance(*b)).sum() +} + +/// The ring of `rings` with the longest outline (the first of equal ones), which carries the side's +/// graphics. `None` when no ring has a finite length above 0. +pub(super) fn longest(rings: &[&[Point]]) -> Option { + rings + .iter() + .map(|r| perimeter(r)) + .enumerate() + .filter(|(_, l)| l.is_finite() && *l > 0.0) + .fold(None, |best: Option<(usize, f64)>, (k, l)| if best.is_some_and(|(_, top)| top >= l) { best } else { Some((k, l)) }) + .map(|(k, _)| k) +} + +/// The x of each end of each edge of `ring` (point `i` to point `i + 1`, the last back to the first), +/// as the module describes. `None` for a ring with no length or bounds that are not finite. +pub(super) fn along_ring(ring: &[Point]) -> Option> { + let n = ring.len(); + if n < 2 { + return None; + } + let edges = || ring.iter().zip(ring.iter().cycle().skip(1)).map(|(a, b)| (*a, *b)); + let lengths: Vec = edges().map(|(a, b)| a.distance(b)).collect(); + let total: f64 = lengths.iter().sum(); + if !total.is_finite() || total <= 0.0 { + return None; + } + let mut starts = Vec::with_capacity(n); + let mut at = 0.0; + for l in &lengths { + starts.push(at); + at += l; + } + let bounds = ring.iter().fold(None, |b: Option, p| Some(b.map_or(Rect::from_points(*p, *p), |b| b.union_pt(*p))))?; + let middle = bounds.center().x; + // Where x = 0: the crossing of the middle line nearest the top, as a length along the ring. + let mut origin: Option<(f64, f64)> = None; + let mut keep = |y: f64, s: f64| { + if origin.is_none_or(|(top, _)| y < top) { + origin = Some((y, s)); + } + }; + for ((a, b), (s, l)) in edges().zip(starts.iter().zip(&lengths)) { + if (a.x - middle) * (b.x - middle) > 0.0 { + continue; + } + if a.x == b.x { + // An edge along the middle line: its upper end. + if a.y <= b.y { keep(a.y, *s) } else { keep(b.y, s + l) } + } else { + let t = (middle - a.x) / (b.x - a.x); + keep(a.y + (b.y - a.y) * t, s + l * t); + } + } + let (_, origin) = origin?; + // The cut: the anchor nearest half way around from the origin. + let opposite = (origin + total / 2.0).rem_euclid(total); + let round = |d: f64| { + let d = d.rem_euclid(total); + d.min(total - d) + }; + let cut = starts + .iter() + .copied() + .fold(None, |best: Option, s| if best.is_some_and(|b| round(b - opposite) <= round(s - opposite)) { best } else { Some(s) })?; + let from_cut = (origin - cut).rem_euclid(total); + // The ring runs clockwise on the page (y down) when it encloses positive area: x grows along it. + let sign = if signed_area(ring) >= 0.0 { 1.0 } else { -1.0 }; + Some( + starts + .iter() + .zip(&lengths) + .map(|(s, l)| { + let a = (s - cut).rem_euclid(total) - from_cut; + [a * sign, (a + l) * sign] + }) + .collect(), + ) +} + +/// The y of each of an extrusion's `steps`, each its inset (points) and its depth fraction (0 front, +/// 1 back) of a solid `depth` points deep: the length along the steps from their middle, growing +/// toward the back. +pub(super) fn across_steps(steps: &[(f64, f64)], depth: f64) -> Vec { + let mut out = Vec::with_capacity(steps.len()); + let mut at = 0.0; + for (k, (inset, t)) in steps.iter().enumerate() { + if let Some((i0, t0)) = k.checked_sub(1).and_then(|k| steps.get(k)) { + at += (inset - i0).hypot(depth * (t - t0)); + } + out.push(at); + } + let middle = at / 2.0; + out.into_iter().map(|y| y - middle).collect() +} + +/// The size of Extrude & Bevel's side unrolled, around the longest of `rings` and across the steps +/// `steps` (each inset and depth fraction) of a solid `depth` points deep: the length around it, +/// the length across it, and the width about x = 0 that does not reach the side's cut (twice the +/// distance from x = 0 to the nearer end of the cut side). `None` when the side has no length +/// either way. +pub(super) fn size(rings: &[&[Point]], steps: &[(f64, f64)], depth: f64) -> Option<(f64, f64, f64)> { + let ring = rings.get(longest(rings)?)?; + let across = across_steps(steps, depth); + let height = across.last().zip(across.first()).map_or(0.0, |(b, a)| b - a); + let width = perimeter(ring); + let xs = along_ring(ring)?; + let (lo, hi) = xs.iter().flatten().fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), x| (lo.min(*x), hi.max(*x))); + let span = 2.0 * (-lo).min(hi); + (width.is_finite() && height.is_finite() && width > 0.0 && height > 0.0).then_some((width, height, span.clamp(0.0, width))) +} + +#[cfg(test)] +#[path = "tests_side.rs"] +mod tests; diff --git a/crates/three-d/src/solid/tests.rs b/crates/three-d/src/solid/tests.rs index 4e1a7f3247..6e9cce82fc 100644 --- a/crates/three-d/src/solid/tests.rs +++ b/crates/three-d/src/solid/tests.rs @@ -554,9 +554,11 @@ fn malformed_and_degenerate_input_is_bounded() { cap: true, bevel: Some(Bevel { width: f64::NAN, height: 1e12, repeat: usize::MAX, space: 7.0, ..Bevel::default() }), hidden: false, + map_surface: true, }; let f = extrude(&p, FillRule::EvenOdd, b, wild, View { rotation_x: f64::NAN, perspective: 900.0, ..front() }).unwrap(); assert!(f.iter().flat_map(|f| f.contours.iter().flatten()).all(|q| q.x.is_finite() && q.y.is_finite())); + assert!(f.iter().filter_map(|f| f.surface.as_ref()).flat_map(|c| c.uv.iter()).all(|q| q.x.is_finite() && q.y.is_finite())); assert!( inflate( &p, diff --git a/crates/three-d/src/solid/tests_side.rs b/crates/three-d/src/solid/tests_side.rs new file mode 100644 index 0000000000..f2d7ec722a --- /dev/null +++ b/crates/three-d/src/solid/tests_side.rs @@ -0,0 +1,96 @@ +use vectorcraft_geom::{BezPath, FillRule, PathData, Point, Rect}; + +use super::super::{Bevel, Extrude, View, extrude, extrude_side_size}; +use super::{across_steps, along_ring, longest}; + +fn square(r: Rect, hole: Option) -> PathData { + let mut b = BezPath::new(); + b.move_to((r.x0, r.y0)); + b.line_to((r.x1, r.y0)); + b.line_to((r.x1, r.y1)); + b.line_to((r.x0, r.y1)); + b.close_path(); + if let Some(h) = hole { + b.move_to((h.x0, h.y0)); + b.line_to((h.x0, h.y1)); + b.line_to((h.x1, h.y1)); + b.line_to((h.x1, h.y0)); + b.close_path(); + } + PathData::from_bezpath(&b) +} + +/// x is 0 at the top of the middle line and grows clockwise on the page; the side is cut at the +/// anchor nearest half way around (the first of two equally near). +#[test] +fn x_runs_clockwise_from_the_top_middle() { + let ring = [Point::new(0.0, 0.0), Point::new(10.0, 0.0), Point::new(10.0, 10.0), Point::new(0.0, 10.0)]; + assert_eq!(along_ring(&ring).unwrap(), vec![[-5.0, 5.0], [5.0, 15.0], [-25.0, -15.0], [-15.0, -5.0]]); + // The same outline run the other way gives each point the same x, apart from the seam, which + // is now at (0, 10), its first anchor of the two equally near. + let back: Vec = ring.iter().rev().copied().collect(); + let x = along_ring(&back).unwrap(); + assert_eq!(x, vec![[25.0, 15.0], [15.0, 5.0], [5.0, -5.0], [-5.0, -15.0]]); + assert_eq!(along_ring(&[Point::ZERO, Point::ZERO]), None); +} + +#[test] +fn y_runs_across_the_steps_from_their_middle() { + // A 4 × 3 pt bevel step, then 20 pt of wall, on a solid 30 pt deep. + let y = across_steps(&[(0.0, 0.0), (-4.0, 0.1), (-4.0, 0.1 + 20.0 / 30.0)], 30.0); + let expected = [-12.5, -7.5, 12.5]; + for (a, b) in y.iter().zip(expected) { + assert!((a - b).abs() < 1e-9, "{y:?}"); + } +} + +/// With graphics on the side, every piece of the walls of the longest contour carries its place on +/// the side unrolled, and no other facet does: x along the outline and y from the front to the back. +#[test] +fn the_longest_contours_walls_carry_their_place_on_the_side() { + let (outer, inner) = (Rect::new(0.0, 0.0, 100.0, 60.0), Rect::new(30.0, 20.0, 70.0, 40.0)); + let path = square(outer, Some(inner)); + let o = Extrude { depth: 40.0, map_surface: true, ..Extrude::default() }; + // Seen from above: the top wall faces the viewer and keeps its x on the page. + let top = View { rotation_x: -90.0, ..View::default() }; + let facets = extrude(&path, FillRule::NonZero, outer, o, top).unwrap(); + let cells: Vec<_> = facets.iter().filter_map(|f| f.surface.as_ref().map(|c| (f, c))).collect(); + assert!(!cells.is_empty()); + assert!(cells.iter().all(|(f, c)| f.side && f.end.is_none() && c.uv.len() == 4 && c.page.len() == 4)); + let seen: Vec<_> = cells.iter().filter(|(_, c)| c.outward).collect(); + assert_eq!(seen.len(), 1, "only the top wall of the outline faces the viewer"); + for (_, c) in seen { + for (uv, page) in c.uv.iter().zip(&c.page) { + assert!((page.x - (50.0 + uv.x)).abs() < 1e-6, "{uv:?} {page:?}"); + assert!(uv.y.abs() <= 20.0 + 1e-9); + } + } + // Only the outline's top wall is drawn (the walls seen edge-on have no area on the page, and the + // bottom wall faces away); the hole's walls carry none. Without graphics no facet carries one. + assert_eq!(cells.len(), 1); + let turned = View { rotation_x: -60.0, rotation_y: 30.0, ..View::default() }; + let hollow = extrude(&path, FillRule::NonZero, outer, Extrude { cap: false, ..o }, turned).unwrap(); + let hollow: Vec<_> = hollow.iter().filter_map(|f| f.surface.as_ref()).collect(); + // A hollow solid shows the insides of its far walls: they carry a cell that is not outward. + assert!(hollow.iter().any(|c| c.outward) && hollow.iter().any(|c| !c.outward), "{}", hollow.len()); + let plain = extrude(&path, FillRule::NonZero, outer, Extrude { map_surface: false, ..o }, top).unwrap(); + assert!(plain.iter().all(|f| f.surface.is_none())); + assert_eq!(plain.len(), facets.len()); +} + +#[test] +fn the_side_measures_around_the_outline_and_across_the_bevels() { + let outer = Rect::new(0.0, 0.0, 100.0, 60.0); + let path = square(outer, None); + let plain = Extrude { depth: 40.0, ..Extrude::default() }; + // The cut is at a bottom corner, 110 pt each way from the top's middle: 220 pt about x = 0 + // stay clear of it. + assert_eq!(extrude_side_size(&path, FillRule::NonZero, outer, plain), Some((320.0, 40.0, 220.0))); + // A 3 × 4 pt classic bevel outside adds its 5 pt slant and takes 4 pt of the wall. + let bevel = Extrude { bevel: Some(Bevel { width: 3.0, height: 4.0, ..Bevel::default() }), ..plain }; + let (w, h, span) = extrude_side_size(&path, FillRule::NonZero, outer, bevel).unwrap(); + assert!((w - 320.0).abs() < 1e-9 && (h - 41.0).abs() < 1e-9 && (span - 220.0).abs() < 1e-9, "{w} {h} {span}"); + assert_eq!(extrude_side_size(&path, FillRule::NonZero, outer, Extrude { depth: 0.0, ..plain }), None); + let rings = [&[Point::ZERO, Point::new(1.0, 0.0), Point::new(0.0, 1.0)][..], &[Point::ZERO, Point::new(5.0, 0.0), Point::new(0.0, 5.0)][..]]; + assert_eq!(longest(&rings), Some(1)); +} diff --git a/crates/tools/src/builder/map.rs b/crates/tools/src/builder/map.rs index 6b524e9af9..437ecde69a 100644 --- a/crates/tools/src/builder/map.rs +++ b/crates/tools/src/builder/map.rs @@ -519,6 +519,58 @@ pub fn sample_polyline(pts: &[Point], step: f64) -> Vec { out } +#[cfg(test)] +thread_local! { + /// The edges [`hatch`] has tested against a scanline on this thread. + pub(super) static HATCH_EDGE_TESTS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// A region's edges in [`hatch`]'s rotated space, met in order of rising scanline. Each line tests +/// only the edges that span it, and the edges with a NaN or infinite end height. +pub(super) struct EdgeSweep { + /// The edges with finite, unequal end heights, by lower end. + edges: Vec<(Point, Point)>, + /// How many of `edges` have reached the active list. + next: usize, + /// The edges whose lower end is at or below the last line and whose upper end is above it. + active: Vec<(Point, Point)>, + /// The edges with a NaN or infinite end height. + loose: Vec<(Point, Point)>, +} + +impl EdgeSweep { + pub(super) fn new(mut edges: Vec<(Point, Point)>) -> Self { + let mut loose = vec![]; + edges.retain(|&(a, c)| { + let finite = a.y.is_finite() && c.y.is_finite(); + if !finite { + loose.push((a, c)); + } + // An edge with equal end heights never crosses a scanline. + finite && a.y != c.y + }); + edges.sort_unstable_by(|(a, c), (b, d)| a.y.min(c.y).total_cmp(&b.y.min(d.y))); + EdgeSweep { edges, next: 0, active: vec![], loose } + } + + /// Pushes the x of each edge crossing the scanline at `y` onto `xs`, in no particular order. + /// `y` is not NaN and never decreases from one call to the next. + pub(super) fn crossings(&mut self, y: f64, xs: &mut Vec) { + while let Some(&(a, c)) = self.edges.get(self.next).filter(|(a, c)| a.y.min(c.y) <= y) { + self.active.push((a, c)); + self.next += 1; + } + self.active.retain(|(a, c)| a.y.max(c.y) > y); + #[cfg(test)] + HATCH_EDGE_TESTS.with(|n| n.set(n.get() + self.active.len() + self.loose.len())); + for (a, c) in self.active.iter().chain(&self.loose) { + if (a.y <= y) != (c.y <= y) { + xs.push(a.x + (y - a.y) / (c.y - a.y) * (c.x - a.x)); + } + } + } +} + /// Diagonal hatch lines filling `path` (the Shape Builder's grey mesh highlight), `gap` apart. pub fn hatch(path: &BezPath, gap: f64) -> BezPath { let mut out = BezPath::new(); @@ -563,6 +615,7 @@ pub fn hatch(path: &BezPath, gap: f64) -> BezPath { } let gap = gap.max((y1 - y0) / 400.0).max(1e-6); let start = (y0 / gap).floor() * gap + gap * 0.5; + let mut sweep = EdgeSweep::new(edges); let mut xs: Vec = vec![]; // Counted, not summed: far from the origin `y + gap` can round back to `y`. The gap is at least // a 400th of the height, so 402 lines cover it. @@ -572,11 +625,7 @@ pub fn hatch(path: &BezPath, gap: f64) -> BezPath { break; } xs.clear(); - for (a, c) in &edges { - if (a.y <= y) != (c.y <= y) { - xs.push(a.x + (y - a.y) / (c.y - a.y) * (c.x - a.x)); - } - } + sweep.crossings(y, &mut xs); xs.sort_by(f64::total_cmp); for pair in xs.as_chunks::<2>().0 { out.move_to(unrot(Point::new(pair[0], y))); diff --git a/crates/tools/src/builder/tests.rs b/crates/tools/src/builder/tests.rs index 219c0028f3..dc31c1ba79 100644 --- a/crates/tools/src/builder/tests.rs +++ b/crates/tools/src/builder/tests.rs @@ -1133,6 +1133,275 @@ fn hatch_far_from_the_origin_ends() { assert!(hatch(&bp, 4.0).elements().len() <= 2 * 402); } +/// [`hatch`] as it tested every edge on every scanline, the reference the sweep must match. +fn hatch_every_edge(path: &BezPath, gap: f64) -> BezPath { + let mut out = BezPath::new(); + let b = path.bounding_box(); + if b.width() <= 0.0 || b.height() <= 0.0 { + return out; + } + let s = std::f64::consts::FRAC_1_SQRT_2; + let rot = |p: Point| Point::new((p.x + p.y) * s, (p.y - p.x) * s); + let unrot = |p: Point| Point::new((p.x - p.y) * s, (p.x + p.y) * s); + let mut edges: Vec<(Point, Point)> = vec![]; + let mut first = Point::ZERO; + let mut last = Point::ZERO; + kurbo::flatten(path.iter(), gap.max(1e-3) * 0.1, |el| match el { + kurbo::PathEl::MoveTo(p) => { + if last != first { + edges.push((rot(last), rot(first))); + } + first = p; + last = p; + } + kurbo::PathEl::LineTo(p) => { + edges.push((rot(last), rot(p))); + last = p; + } + kurbo::PathEl::ClosePath => { + if last != first { + edges.push((rot(last), rot(first))); + } + last = first; + } + _ => {} + }); + if last != first { + edges.push((rot(last), rot(first))); + } + let (mut y0, mut y1) = (f64::INFINITY, f64::NEG_INFINITY); + for (a, c) in &edges { + y0 = y0.min(a.y.min(c.y)); + y1 = y1.max(a.y.max(c.y)); + } + let gap = gap.max((y1 - y0) / 400.0).max(1e-6); + let start = (y0 / gap).floor() * gap + gap * 0.5; + let mut xs: Vec = vec![]; + for i in 0..402u32 { + let y = start + f64::from(i) * gap; + if y.partial_cmp(&y1) != Some(std::cmp::Ordering::Less) { + break; + } + xs.clear(); + for (a, c) in &edges { + if (a.y <= y) != (c.y <= y) { + xs.push(a.x + (y - a.y) / (c.y - a.y) * (c.x - a.x)); + } + } + xs.sort_by(f64::total_cmp); + for pair in xs.as_chunks::<2>().0 { + out.move_to(unrot(Point::new(pair[0], y))); + out.line_to(unrot(Point::new(pair[1], y))); + } + } + out +} + +/// A path's elements with every coordinate as its bits, so NaN and -0.0 compare exactly. +fn path_bits(p: &BezPath) -> Vec<(u8, Vec)> { + let bits = |pts: &[Point]| pts.iter().flat_map(|p| [p.x.to_bits(), p.y.to_bits()]).collect(); + p.elements() + .iter() + .map(|el| match *el { + kurbo::PathEl::MoveTo(a) => (0, bits(&[a])), + kurbo::PathEl::LineTo(a) => (1, bits(&[a])), + kurbo::PathEl::QuadTo(a, b) => (2, bits(&[a, b])), + kurbo::PathEl::CurveTo(a, b, c) => (3, bits(&[a, b, c])), + kurbo::PathEl::ClosePath => (4, vec![]), + }) + .collect() +} + +/// A closed polygon through `pts`. +fn polygon(pts: impl IntoIterator) -> BezPath { + let mut bp = BezPath::new(); + for (i, p) in pts.into_iter().enumerate() { + if i == 0 { + bp.move_to(p); + } else { + bp.line_to(p); + } + } + bp.close_path(); + bp +} + +/// A polygon of `n` sides inscribed in the circle of radius `r` about the origin. +fn circle_polygon(n: u32, r: f64) -> BezPath { + polygon((0..n).map(|i| { + let t = std::f64::consts::TAU * f64::from(i) / f64::from(n); + Point::new(r * t.cos(), r * t.sin()) + })) +} + +/// The paths the hatch is checked on: many edges, a random star, holes, several subpaths, a +/// sliver, curves, edges along the hatch, repeated outlines, an open path, far coordinates, an +/// empty path and NaN and infinite coordinates. +fn hatch_cases() -> Vec<(&'static str, BezPath)> { + let mut seed = 0x2545_f491_4f6c_dd1d_u64; + let mut rand = move || { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + (seed >> 11) as f64 / (1u64 << 53) as f64 + }; + let star = polygon((0..300).map(|i| { + let t = std::f64::consts::TAU * f64::from(i) / 300.0; + let r = 100.0 + 300.0 * rand(); + Point::new(r * t.cos(), r * t.sin()) + })); + let mut holes = shapes::rectangle(Rect::new(0.0, 0.0, 300.0, 200.0)).to_bezpath(); + holes.extend(polygon([(50.0, 50.0), (50.0, 150.0), (120.0, 150.0), (120.0, 50.0)].map(Point::from))); + holes.extend(polygon([(180.0, 40.0), (260.0, 100.0), (180.0, 160.0)].map(Point::from))); + holes.extend(circle_polygon(40, 30.0).iter().map(|el| match el { + kurbo::PathEl::MoveTo(p) => kurbo::PathEl::MoveTo(p + kurbo::Vec2::new(400.0, 100.0)), + kurbo::PathEl::LineTo(p) => kurbo::PathEl::LineTo(p + kurbo::Vec2::new(400.0, 100.0)), + other => other, + })); + let mut repeated = BezPath::new(); + for _ in 0..7 { + repeated.extend(shapes::rectangle(Rect::new(0.0, 0.0, 50.0, 50.0)).to_bezpath()); + } + let mut open = BezPath::new(); + open.move_to((0.0, 0.0)); + open.line_to((120.0, 10.0)); + open.line_to((60.0, 90.0)); + vec![ + ("2,000-sided circle", circle_polygon(2000, 500.0)), + ("300-point star", star), + ("holes and subpaths", holes), + ("sliver", polygon([(0.0, 0.0), (900.0, 1.0), (900.0, 1.002)].map(Point::from))), + ("curves", kurbo::Circle::new((10.0, -20.0), 300.0).to_path(0.01)), + ("edges along the hatch", polygon([(0.0, 0.0), (10.0, 10.0), (0.0, 20.0), (-10.0, 10.0)].map(Point::from))), + ("repeated outlines", repeated), + ("open path", open), + ("far from the origin", shapes::rectangle(Rect::new(0.0, 1e17, 64.0, 1e17 + 64.0)).to_bezpath()), + ("empty", BezPath::new()), + ("NaN", polygon([(0.0, 0.0), (100.0, f64::NAN), (100.0, 100.0), (0.0, 80.0)].map(Point::from))), + ("infinite", polygon([(0.0, 0.0), (f64::INFINITY, 50.0), (100.0, 100.0)].map(Point::from))), + ] +} + +#[test] +fn hatch_matches_testing_every_edge() { + for (name, bp) in hatch_cases() { + for gap in [0.5, 4.0, 40.0] { + assert_eq!(path_bits(&hatch(&bp, gap)), path_bits(&hatch_every_edge(&bp, gap)), "{name} at gap {gap}"); + } + } +} + +#[test] +fn hatch_tests_only_the_edges_spanning_each_line() { + let bp = circle_polygon(2000, 500.0); + let before = map::HATCH_EDGE_TESTS.with(std::cell::Cell::get); + let h = hatch(&bp, 4.0); + let tests = map::HATCH_EDGE_TESTS.with(std::cell::Cell::get) - before; + // Each line crosses the circle once, so it has one segment. + let lines = h.elements().len() / 2; + assert!(lines > 200, "{lines}"); + assert!(tests * 20 < lines * 2000, "{tests} edge tests on {lines} lines of 2,000 edges"); +} + +#[test] +fn hatch_sweep_finds_the_crossings_of_every_edge() { + let p = Point::new; + let edges = vec![ + (p(0.0, 0.0), p(1.0, 1.0)), + (p(1.0, 1.0), p(0.0, 2.0)), + (p(3.0, 2.0), p(3.0, -1.0)), + (p(5.0, 1.0), p(9.0, 1.0)), + (p(2.0, -0.0), p(2.0, 0.0)), + (p(4.0, -0.0), p(4.0, 3.0)), + (p(6.0, 0.5), p(6.0, 0.5)), + (p(7.0, f64::NAN), p(7.0, 2.0)), + (p(8.0, 0.0), p(8.0, f64::INFINITY)), + (p(f64::NAN, 0.0), p(1.0, 2.0)), + (p(3.0, 2.0), p(3.0, -1.0)), + (p(3.0, 2.0), p(3.0, -1.0)), + ]; + let mut sweep = map::EdgeSweep::new(edges.clone()); + let mut xs = vec![]; + for y in [-2.0, -1.0, -0.0, 0.0, 0.5, 1.0, 1.0, 1.5, 2.0, 2.5, 3.0, 4.0] { + let mut old: Vec = + edges.iter().filter(|(a, c)| (a.y <= y) != (c.y <= y)).map(|(a, c)| a.x + (y - a.y) / (c.y - a.y) * (c.x - a.x)).collect(); + xs.clear(); + sweep.crossings(y, &mut xs); + old.sort_by(f64::total_cmp); + xs.sort_by(f64::total_cmp); + let bits = |v: &[f64]| v.iter().map(|x| x.to_bits()).collect::>(); + assert_eq!(bits(&xs), bits(&old), "at y = {y}"); + } +} + +fn thread_cpu() -> Option { + let stat = std::fs::read_to_string("/proc/thread-self/schedstat").ok()?; + stat.split_whitespace().next()?.parse().ok().map(std::time::Duration::from_nanos) +} + +/// The time `f` takes: this thread's CPU time where Linux reports it, otherwise the wall clock. +fn cpu_time(f: impl FnOnce()) -> std::time::Duration { + match thread_cpu() { + Some(before) => { + f(); + thread_cpu().map_or(std::time::Duration::ZERO, |after| after.saturating_sub(before)) + } + None => { + let start = std::time::Instant::now(); + f(); + start.elapsed() + } + } +} + +/// Timings of 1,000 hatches by the sweep and by testing every edge, on a 2,000-sided circle of +/// radius 500 and on a 40-sided one, run in turn, 7 runs each. Ignored by default; it prints the +/// median, fastest and slowest run and sets no bound on them: +/// `cargo test --release -p vectorcraft-tools --lib hatch_perf -- --ignored --nocapture`. +#[test] +#[ignore = "a benchmark: run with --ignored --nocapture"] +fn hatch_perf() { + const RUNS: usize = 7; + let ms = |d: std::time::Duration| d.as_secs_f64() * 1000.0; + eprintln!("hatch_perf: {}", if thread_cpu().is_some() { "thread CPU time" } else { "wall clock" }); + for (sides, r) in [(2000, 500.0), (2000, 100.0), (40, 100.0)] { + let bp = circle_polygon(sides, r); + assert_eq!(path_bits(&hatch(&bp, 4.0)), path_bits(&hatch_every_edge(&bp, 4.0))); + let (mut old, mut new) = (vec![], vec![]); + let every = || { + for _ in 0..1000 { + std::hint::black_box(hatch_every_edge(std::hint::black_box(&bp), 4.0)); + } + }; + let sweep = || { + for _ in 0..1000 { + std::hint::black_box(hatch(std::hint::black_box(&bp), 4.0)); + } + }; + for run in 0..RUNS { + // The two take turns going first. + if run % 2 == 0 { + old.push(cpu_time(every)); + new.push(cpu_time(sweep)); + } else { + new.push(cpu_time(sweep)); + old.push(cpu_time(every)); + } + } + old.sort(); + new.sort(); + eprintln!( + "hatch_perf: {sides:>5} sides r {r:>5}: every edge {:>9.3} ms ({:.3}-{:.3}), sweep {:>9.3} ms ({:.3}-{:.3})", + ms(old[RUNS / 2]), + ms(old[0]), + ms(old[RUNS - 1]), + ms(new[RUNS / 2]), + ms(new[0]), + ms(new[RUNS - 1]), + ); + } +} + /// An empty hidden sources group for a Live Paint group made in a test. fn empty_sources(d: &mut Document) -> Arc { let mut g = Node::group(d.alloc_id(), vec![]); diff --git a/crates/tools/src/direct.rs b/crates/tools/src/direct.rs index f9f28eeec0..66cc842a53 100644 --- a/crates/tools/src/direct.rs +++ b/crates/tools/src/direct.rs @@ -384,6 +384,18 @@ pub(crate) fn spines(cx: &ToolContext) -> Vec<(NodeId, PathData)> { v } +/// [`spines`] of the blends that are themselves selected, topmost first. When no selected object +/// is a blend, it returns an empty list without walking the document or building any spine. +pub(crate) fn selected_spines(cx: &ToolContext) -> Vec<(NodeId, PathData)> { + let is_blend = |id: &NodeId| cx.doc.node(*id).is_some_and(|n| matches!(n.kind, NodeKind::Blend { .. })); + if !cx.selection.objects.iter().any(is_blend) { + return vec![]; + } + let mut v = spines(cx); + v.retain(|(id, _)| cx.selection.contains(*id)); + v +} + /// The spine point under `p`: (blend, anchor, where it is). fn hit_spine_point(cx: &ToolContext, p: Point, tol: f64) -> Option<(NodeId, usize, Point)> { spines(cx).into_iter().find_map(|(id, path)| { @@ -395,7 +407,7 @@ fn hit_spine_point(cx: &ToolContext, p: Point, tol: f64) -> Option<(NodeId, usiz /// The segment of a selected blend's spine passing within `tol` of `p`: (blend, segment, t, whether /// it is straight). pub(crate) fn hit_spine_segment(cx: &ToolContext, p: Point, tol: f64) -> Option<(NodeId, usize, f64, bool)> { - spines(cx).into_iter().filter(|(id, _)| cx.selection.contains(*id)).find_map(|(id, path)| { + selected_spines(cx).into_iter().find_map(|(id, path)| { let (si, seg, t, _, dist) = path.nearest(p)?; (dist <= tol).then(|| (id, seg, t, path.subpaths.get(si).is_some_and(|sp| sp.segment_is_line(seg)))) }) @@ -1722,7 +1734,7 @@ impl DirectSelectionTool { // marquee that holds none of them drops the points picked before. let mut spined: Option = None; if !self.group { - let found = spines(cx).into_iter().filter(|(id, _)| cx.selection.contains(*id)).find_map(|(id, path)| { + let found = selected_spines(cx).into_iter().find_map(|(id, path)| { let inside: BTreeSet = path.anchors().filter(|(s, _, a)| *s == 0 && r.contains(a.p)).map(|(_, i, _)| i).collect(); (!inside.is_empty()).then_some((id, inside)) }); diff --git a/crates/tools/src/direct/tests.rs b/crates/tools/src/direct/tests.rs index a0fabb9cb8..50244eb260 100644 --- a/crates/tools/src/direct/tests.rs +++ b/crates/tools/src/direct/tests.rs @@ -416,6 +416,141 @@ fn spine_segments_bend_with_the_anchor_point_tool_and_direct_selection() { assert_eq!(t.pointer(&curved, &PointerEvent::new(PointerKind::Up, 160.0, 345.0)), vec![Action::Commit]); } +/// [`selected_spines`] written as a filter of every spine, for comparing results. +fn every_spine_then_selected(cx: &ToolContext) -> Vec<(NodeId, PathData)> { + spines(cx).into_iter().filter(|(id, _)| cx.selection.contains(*id)).collect() +} + +/// [`hit_spine_segment`] written over [`every_spine_then_selected`], for comparing results. +fn hit_spine_segment_of_every_spine(cx: &ToolContext, p: Point, tol: f64) -> Option<(NodeId, usize, f64, bool)> { + every_spine_then_selected(cx).into_iter().find_map(|(id, path)| { + let (si, seg, t, _, dist) = path.nearest(p)?; + (dist <= tol).then(|| (id, seg, t, path.subpaths.get(si).is_some_and(|sp| sp.segment_is_line(seg)))) + }) +} + +/// [`blend_doc`] with a stored spine the keys are spread along (not pinned to anchors), whose +/// layout builds a [`vectorcraft_doc::blend::Spine`], and the id of the plain rectangle beside it. +fn blend_doc_with_spread_spine() -> (vectorcraft_doc::Document, NodeId, NodeId, NodeId) { + let (mut d, g, k1) = blend_doc(); + let Some(rect) = d.layers[0].children().into_iter().flatten().map(|n| n.id).find(|id| *id != g) else { panic!("rectangle") }; + let mut sp = vectorcraft_geom::SubPath::polyline(&[Point::new(110.0, 310.0), Point::new(210.0, 310.0)], false); + sp.bend_segment(0, 0.5, vectorcraft_geom::Vec2::new(0.0, 20.0)); + let Some(NodeKind::Blend { spec, .. }) = d.node_mut(g).map(|n| &mut n.kind) else { panic!("blend") }; + (spec.spine, spec.key_anchors) = (Some(PathData::single(sp)), vec![]); + (d, g, k1, rect) +} + +/// With no blend among the selected objects, the selected-spine check builds no blend spine; with +/// the blend selected it still finds the spine. +#[test] +fn the_selected_spine_check_builds_no_spine_without_a_selected_blend() { + let (d, g, _, rect) = blend_doc_with_spread_spine(); + let p = paint(); + let mut s = Selection::default(); + s.set([rect]); + let c = cx(&d, &s, &p); + let before = vectorcraft_doc::blend::spines_built(); + assert_eq!(hit_spine_segment(&c, Point::new(160.0, 330.0), 4.0), None); + assert!(selected_spines(&c).is_empty()); + assert_eq!(vectorcraft_doc::blend::spines_built() - before, 0, "no spine built"); + s.set([rect, g]); + let c = cx(&d, &s, &p); + assert!(hit_spine_segment(&c, Point::new(160.0, 330.0), 4.0).is_some_and(|h| h.0 == g)); +} + +/// The selected-spine check gives what a filter of every spine gives, for selections with and +/// without the blend, its key, a stale id, and the blend locked, hidden or without a spine. +#[test] +fn the_selected_spine_check_matches_a_filter_of_every_spine() { + let (d, g, k1, rect) = blend_doc_with_spread_spine(); + let p = paint(); + let mut docs = vec![d.clone()]; + for change in 0..3 { + let mut d = d.clone(); + if let Some(n) = d.node_mut(g) { + match change { + 0 => n.locked = true, + 1 => n.visible = false, + _ => { + if let NodeKind::Blend { spec, .. } = &mut n.kind { + spec.no_spine = true; + } + } + } + } + docs.push(d); + } + let selections: [&[NodeId]; 7] = [&[], &[rect], &[g], &[rect, g], &[g, rect], &[k1], &[NodeId(9_999)]]; + for (di, d) in docs.iter().enumerate() { + for ids in selections { + let mut s = Selection::default(); + s.set(ids.iter().copied()); + let c = cx(d, &s, &p); + assert_eq!(selected_spines(&c), every_spine_then_selected(&c), "doc {di}, {ids:?}"); + for x in (90..=230).step_by(5) { + for y in (295..=340).step_by(5) { + let at = Point::new(f64::from(x), f64::from(y)); + assert_eq!(hit_spine_segment(&c, at, 4.0), hit_spine_segment_of_every_spine(&c, at, 4.0), "doc {di}, {ids:?}, {at:?}"); + } + } + } + } +} + +/// Times the selected-spine check on 20,000 paths and 200 blends with curved spines, against the +/// same check written as a filter of every spine, in one process: 500 points, the median of 7 +/// runs. Case A selects one plain path, case B one blend. +#[test] +#[ignore = "manual large-document timing"] +fn selected_spine_check_timing() { + let mut d = vectorcraft_doc::Document::new(4000.0, 4000.0); + let l = d.layers[0].id; + for i in 0..20_000_u32 { + let (x, y) = (f64::from(i % 200) * 20.0, f64::from(i / 200) * 20.0); + let id = d.alloc_id(); + let r = vectorcraft_geom::shapes::rectangle(Rect::new(x, y, x + 10.0, y + 10.0)); + d.insert(Some(l), 0, vectorcraft_doc::Node::path(id, r, vectorcraft_doc::Appearance::default_art())).unwrap(); + } + let first_path = d.layers[0].children().into_iter().flatten().map(|n| n.id).next(); + let mut blends = vec![]; + for i in 0..200_u32 { + let (x, y) = (f64::from(i % 20) * 200.0, 2050.0 + f64::from(i / 20) * 190.0); + let key = |id: NodeId, x: f64| { + let r = vectorcraft_geom::shapes::rectangle(Rect::new(x, y, x + 20.0, y + 20.0)); + std::sync::Arc::new(vectorcraft_doc::Node::path(id, r, vectorcraft_doc::Appearance::default_art())) + }; + let (g, k1, k2) = (d.alloc_id(), d.alloc_id(), d.alloc_id()); + let mut sp = vectorcraft_geom::SubPath::polyline(&[Point::new(x + 10.0, y + 10.0), Point::new(x + 110.0, y + 10.0)], false); + sp.bend_segment(0, 0.5, vectorcraft_geom::Vec2::new(0.0, 20.0)); + let spec = vectorcraft_doc::BlendSpec { spine: Some(PathData::single(sp)), ..Default::default() }; + let b = vectorcraft_doc::Node::new(g, NodeKind::Blend { children: vec![key(k1, x), key(k2, x + 100.0)], spec: Box::new(spec) }); + d.insert(Some(l), 0, b).unwrap(); + blends.push(g); + } + let points: Vec = (0..500_u32).map(|i| Point::new(f64::from(i * 37 % 4000), f64::from(i * 53 % 4000))).collect(); + let p = paint(); + let (Some(plain), Some(&blend)) = (first_path, blends.first()) else { panic!("fixture") }; + for (case, id) in [("A: one plain path selected", plain), ("B: one blend selected", blend)] { + let mut s = Selection::default(); + s.set([id]); + let c = cx(&d, &s, &p); + let (mut old, mut new) = (vec![], vec![]); + for _ in 0..7 { + let t = std::time::Instant::now(); + let a: Vec<_> = points.iter().map(|q| hit_spine_segment_of_every_spine(&c, *q, 4.0)).collect(); + old.push(t.elapsed()); + let t = std::time::Instant::now(); + let b: Vec<_> = points.iter().map(|q| hit_spine_segment(&c, *q, 4.0)).collect(); + new.push(t.elapsed()); + assert_eq!(a, b, "{case}"); + } + old.sort(); + new.sort(); + eprintln!("{case}: 500 checks, median of 7: every spine then filter {:?}, selected spines {:?}", old[3], new[3]); + } +} + /// Shift held while a curved segment is dragged sends `perpendicular`. The test drags a path's /// segment with Direct Selection, and a blend spine's segment with Direct Selection and with the /// Anchor Point tool. diff --git a/crates/tools/src/draw2/anchor.rs b/crates/tools/src/draw2/anchor.rs index 58664704ad..3389746f2d 100644 --- a/crates/tools/src/draw2/anchor.rs +++ b/crates/tools/src/draw2/anchor.rs @@ -168,7 +168,7 @@ impl AnchorTool { | State::SpineHandle { id, .. } | State::Reshape { id, .. } => Some((cx.selection.contains(id), cx.doc.index_path(id))), }; - for (id, path) in crate::direct::spines(cx).into_iter().filter(|(id, _)| cx.selection.contains(*id)) { + for (id, path) in crate::direct::selected_spines(cx) { let candidate = if let Some((ai, out)) = Self::spine_handle(cx, &path, p, point) { State::SpineHandle { id, ai, out, start: p, began: false } } else if let Some(ai) = Self::spine_point(&path, p, point) { @@ -192,7 +192,7 @@ impl AnchorTool { /// tool switch. Show the handles on selected blends so they stay editable. fn spine_overlays(cx: &ToolContext) -> Vec { let mut out = vec![]; - for (id, path) in crate::direct::spines(cx).into_iter().filter(|(id, _)| cx.selection.contains(*id)) { + for (id, path) in crate::direct::selected_spines(cx) { let anchors: Vec<_> = path.anchors().filter(|(si, _, _)| *si == 0).collect(); if !cx.handles_multiple && anchors.len() > 1 { continue; diff --git a/crates/tools/src/pen.rs b/crates/tools/src/pen.rs index f078b2fbd2..b1077d5a12 100644 --- a/crates/tools/src/pen.rs +++ b/crates/tools/src/pen.rs @@ -708,7 +708,7 @@ fn auto_add_delete(cx: &ToolContext, p: Point, m: Mods, tol: f64) -> Option Option> { - for (id, path) in crate::direct::spines(cx).into_iter().filter(|(id, _)| cx.selection.contains(*id)) { + for (id, path) in crate::direct::selected_spines(cx) { let Some(NodeKind::Blend { children, spec }) = cx.doc.node(id).map(|n| &n.kind) else { continue }; let keys = vectorcraft_doc::live::blend_spine(children, spec).and_then(|(_, a)| a).unwrap_or_default(); if let Some((_, ai, _)) = path.anchors().find(|(_, _, a)| a.p.distance(p) <= tol) { diff --git a/crates/ui-egui/src/addons/pathtools.rs b/crates/ui-egui/src/addons/pathtools.rs index 688771c829..8a1666b260 100644 --- a/crates/ui-egui/src/addons/pathtools.rs +++ b/crates/ui-egui/src/addons/pathtools.rs @@ -1,11 +1,12 @@ //! Path Precision Tools in the interface: its submenu (Object › Plug-ins › Path Precision Tools), //! which selects its tools, opens its panels and runs Split / Add Points at Crossings, Set Corners… ([`set_corners`]), Divide into -//! Dashes ([`dashes`]), Expand Dashes into Paths, Convert to Parametric Shape and Tangent Circle… ([`tangent_circle`]); the Anchor Inspector panel (the selected +//! Dashes ([`dashes`]), Expand Dashes into Paths, Smooth Bridge ([`bridge`]), Convert to Parametric Shape and Tangent Circle… ([`tangent_circle`]); the Anchor Inspector panel (the selected //! anchor's position and handles as numbers, the add-on's anchor edits, the Corner Tool's values, //! [`corner`], and the Shared Edge Merge Tool's, [`shared_edge`]); the Parametric Shape panel //! ([`shape`]); and its tools' options dialog (a double-click on the tool). Everything acts through `addon.pathtools.*` and //! `tool.setOption`. +pub mod bridge; pub mod corner; pub mod dashes; pub mod set_corners; @@ -74,6 +75,7 @@ pub fn menu() -> Vec { Item::Cmd("Split at Crossings", "addon.pathtools.crossings", json!({ "cut": true })), Item::Cmd("Divide into Dashes…", dashes::COMMAND, Value::Null), Item::Cmd("Expand Dashes into Paths", "addon.pathtools.expandDashes", json!({})), + Item::Cmd("Smooth Bridge…", bridge::COMMAND, Value::Null), Item::Cmd("Convert to Parametric Shape", "addon.pathtools.shape.convert", json!({})), Item::Cmd("Tangent Circle…", tangent_circle::COMMAND, Value::Null), Item::Cmd("Common Tangents…", COMMON_TANGENTS, json!({ "tangents": "all", "centerline": false })), diff --git a/crates/ui-egui/src/addons/pathtools/bridge.rs b/crates/ui-egui/src/addons/pathtools/bridge.rs new file mode 100644 index 0000000000..4b9926d616 --- /dev/null +++ b/crates/ui-egui/src/addons/pathtools/bridge.rs @@ -0,0 +1,92 @@ +//! Smooth Bridge in the interface: its dialog (the arcs' radius as a percentage of the smaller +//! circle's radius, Keep Originals), which previews on the canvas and runs `addon.pathtools.bridge` +//! on OK. + +use egui::Ui; +use serde_json::{Value, json}; + +use crate::VectorcraftApp; +use crate::dialogs::{DialogSpec, form}; +use crate::state::Dialog; +use crate::widgets; + +/// The command, and its dialog's kind. +pub const COMMAND: &str = "addon.pathtools.bridge"; +pub const KIND: &str = "smoothBridge"; +/// The radius the command takes (%), and its default. +const RADII: std::ops::RangeInclusive = 1.0..=1000.0; +const RADIUS: f64 = 100.0; +const LABEL_W: f32 = 60.0; +const FIELD_W: f32 = 90.0; + +/// The dialog's fields to start with: the command's defaults. +pub(crate) fn fields() -> Value { + json!({ "radius": RADIUS, "keepOriginals": false }) +} + +pub(crate) const SPEC: DialogSpec = + DialogSpec { heading: |_| tl!("Smooth Bridge").to_string(), body, confirm, preview: true, min_width: 280.0, ..DialogSpec::FORM }; + +/// The command's parameters from the dialog's fields. +fn params(d: &Dialog) -> Value { + json!({ "radius": d.f64("radius", RADIUS), "keepOriginals": d.bool("keepOriginals") }) +} + +fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool { + widgets::label_row(ui, tl!("Radius:"), LABEL_W, |ui| { + if let Some(v) = widgets::range_field(ui, ("dlg-num", "radius"), d.f64("radius", RADIUS), RADII, "%", 0, FIELD_W) { + d.fields.insert("radius".into(), json!(v)); + } + }); + form::check(ui, d, "keepOriginals", tl!("Keep Originals")); + form::preview(app, ui, d, "Smooth Bridge", COMMAND, params(d)); + false +} + +/// OK: run the command (keep its preview) and close. +fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + form::commit_preview(app, COMMAND, params(d)) +} + +#[cfg(test)] +mod tests { + use serde_json::json; + use vectorcraft_engine::Session; + + use crate::tests_labels::painted_text; + use crate::{VectorcraftApp, menus}; + + fn circle(app: &mut VectorcraftApp, x: f64, r: f64) -> u64 { + app.run("shape.ellipse", json!({"x": x - r, "y": 100.0 - r, "width": 2.0 * r, "height": 2.0 * r})).unwrap()["id"].as_u64().unwrap() + } + + #[test] + fn smooth_bridge_opens_its_dialog_previews_and_runs_on_ok() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let (a, b) = (circle(&mut app, 100.0, 20.0), circle(&mut app, 160.0, 20.0)); + app.run("select.set", json!({"ids": [a, b]})).unwrap(); + let entries = menus::menu_entries(&app); + let item = entries.iter().find(|e| e.path == ["Object", "Plug-ins", "Path Precision Tools"] && e.label == "Smooth Bridge…").unwrap(); + let (cmd, p) = menus::click_target(&item.label, item.command.as_deref().unwrap(), &item.params); + menus::invoke(&mut app, &cmd, p); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(super::KIND)); + let shown = painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + for s in ["Smooth Bridge", "Radius:", "Keep Originals", "Preview"] { + assert!(shown.contains(s), "{s} in {shown}"); + } + let count = |app: &VectorcraftApp| app.session.doc().unwrap().doc.layers[0].children().unwrap().len(); + app.ui.dialog.as_mut().unwrap().fields.insert("preview".into(), json!(true)); + painted_text(&mut app, |app, ui| crate::dialogs::show(app, ui.ctx())); + assert_eq!(count(&app), 1, "previewed: one outline in place of the circles"); + crate::dialogs::cancel(&mut app); + assert_eq!(count(&app), 2, "rolled back"); + menus::invoke(&mut app, &cmd, serde_json::Value::Null); + let n = app.session.doc().unwrap().history.undo.len(); + app.ui.dialog.as_mut().unwrap().fields.insert("keepOriginals".into(), json!(true)); + crate::dialogs::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(app.session.doc().unwrap().history.undo.len(), n + 1); + assert_eq!(count(&app), 3, "the circles and the outline above them"); + } +} diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index b7903ebd8e..a05dcedb38 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -82,6 +82,7 @@ impl VectorcraftApp { slices: None, print_tiling: None, live_paint_gaps: None, + find_font: None, hidden_chars: Default::default(), spelling: Default::default(), selection_marks: Default::default(), @@ -89,6 +90,7 @@ impl VectorcraftApp { selection_box: None, selection_bounds: None, content_bounds: None, + three_d_exportable: None, pixel_aligned: None, symbol_instances: None, plugin_keys: Default::default(), diff --git a/crates/ui-egui/src/caches.rs b/crates/ui-egui/src/caches.rs index c2fd1de1d8..be5ff73c54 100644 --- a/crates/ui-egui/src/caches.rs +++ b/crates/ui-egui/src/caches.rs @@ -42,6 +42,10 @@ pub struct CanvasCache { pub print_tiling: Option, /// The gap lines View → Show Live Paint Gaps draws for (document uid, revision). pub live_paint_gaps: Option, + /// Type → Find Font's list of the document's fonts and whether the document misses one, for a + /// version of the document's content and of the available fonts: the dialog reads them every + /// frame. + pub find_font: Option, /// The marks Type → Show Hidden Characters drew on each text object in the last frame. A frame /// that does not draw them drops them ([`canvas::show`]). pub hidden_chars: canvas::HiddenChars, @@ -61,6 +65,9 @@ pub struct CanvasCache { pub selection_bounds: Option<((u64, u64), Option)>, /// [`VectorcraftApp::content_bounds`] for (document uid, revision). pub content_bounds: Option<((u64, u64), Option)>, + /// Whether the 3D and Materials panel's Export 3D Object button is available (a selected + /// object has a 3D effect that `assets.add3D` exports) for (document uid, revision). + pub three_d_exportable: Option<((u64, u64), bool)>, /// The Transform panel's Align to Pixel Grid state (on, off or mixed, and whether every /// selected object can be aligned) for (document uid, revision). pub pixel_aligned: Option<((u64, u64), Option)>, @@ -114,6 +121,32 @@ pub type SliceCache = ((u64, u64), std::sync::Arc>); +/// [`CanvasCache::find_font`]: the document's fonts as `text.fonts` lists them, and whether +/// [`vectorcraft_engine::cmd::fontfiles::missing_fonts`] finds any (`None` until it is asked). +#[derive(Clone, Debug)] +pub struct FindFontCache { + /// The document and the content and fonts the answers were worked out from. + pub key: FontsKey, + pub fonts: std::sync::Arc>, + pub missing: Option, +} + +/// A document's uid, a version of its content (compared by identity) and the font database's +/// generation ([`vectorcraft_text::FontDb::generation`]). The weak reference keeps the version's +/// allocation, so a later version is never placed at the same address while the key is kept. +#[derive(Clone, Debug)] +pub struct FontsKey { + pub uid: u64, + pub doc: std::sync::Weak, + pub generation: u64, +} + +impl PartialEq for FontsKey { + fn eq(&self, other: &Self) -> bool { + self.uid == other.uid && self.generation == other.generation && std::sync::Weak::ptr_eq(&self.doc, &other.doc) + } +} + /// [`CanvasCache::pixel_aligned`]: the selected objects' Align to Pixel Grid, on or off when they /// agree and `None` when they differ, with whether every one can be aligned. pub type PixelAligned = (Option, bool); diff --git a/crates/ui-egui/src/canvas/drag.rs b/crates/ui-egui/src/canvas/drag.rs index f605e5e947..bdda812306 100644 --- a/crates/ui-egui/src/canvas/drag.rs +++ b/crates/ui-egui/src/canvas/drag.rs @@ -317,7 +317,7 @@ pub(super) fn drag_art_out(app: &VectorcraftApp, ui: &Ui, resp: &egui::Response, // The art the drag started with: the release rolls the move back to it, and an Alt-copy's // copies, selected while it previews, go with that. let ids = it.selection.objects.clone(); - egui::DragAndDrop::set_payload(ui.ctx(), widgets::PanelDrag::Art(ids)); + widgets::drag_art(ui.ctx(), st.uid, ids); true } diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 252587139e..b96f5a7af0 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -478,6 +478,7 @@ registry! { RenameArtboards: [rename_artboards::KIND] => rename_artboards::SPEC, PathToolOptions: [crate::addons::pathtools::KIND] => crate::addons::pathtools::OPTIONS_SPEC, DivideDashes: [crate::addons::pathtools::dashes::KIND] => crate::addons::pathtools::dashes::SPEC, + SmoothBridge: [crate::addons::pathtools::bridge::KIND] => crate::addons::pathtools::bridge::SPEC, TangentCircle: [crate::addons::pathtools::tangent_circle::KIND] => crate::addons::pathtools::tangent_circle::SPEC, SetCorners: [crate::addons::pathtools::set_corners::KIND] => crate::addons::pathtools::set_corners::SPEC, NearestSwatch: [crate::addons::color::nearest::KIND] => crate::addons::color::nearest::SPEC, @@ -546,8 +547,8 @@ fn hidden_controls(d: &Dialog) -> &'static [&'static str] { } // The selected rows and Randomize's seed. Some(DialogKind::Recolor) => &["__seed", "__sel"], - // The view, zoom, download speed, selected color table entry and the preset name being typed. - Some(DialogKind::SaveForWeb) => &["__color", "__kbps", "__presetName", "__view", "__zoom"], + // The view, zoom, download speed, selected color table entries and the preset name being typed. + Some(DialogKind::SaveForWeb) => &["__color", "__colors", "__kbps", "__presetName", "__view", "__zoom"], // The link that keeps width and height in proportion. Some(DialogKind::Shape | DialogKind::TransformEach) => &["__constrain"], // The attention filter, the Keys section, the search text and the key being recorded. @@ -845,6 +846,10 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { } let focus_first = focus_first && !clicked; let spec = spec(&d.kind); + // Opened over another dialog, which Cancel shows again: that one keeps where it was scrolled to. + if d.fields.get(PARENT).is_some_and(|p| !p.is_null()) { + modal::over_parent(ctx); + } if let Some(window) = spec.window { return window(app, ctx); } @@ -887,14 +892,16 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { if focus_first { ui.data_mut(|m| m.insert_temp(widgets::dialog_focus_flag(), true)); } + // When the dialog is taller than the window, its body scrolls, and the heading and the + // buttons stay in view. if let Some(body) = spec.body_with_actions { - match body(app, ui, &mut d) { + match modal::body_rows(ui, |ui| body(app, ui, &mut d)) { DialogAction::None => {} DialogAction::Confirm => ok = true, DialogAction::Cancel => cancel = true, } } else { - cancel = (spec.body)(app, ui, &mut d); + cancel = modal::body_rows(ui, |ui| (spec.body)(app, ui, &mut d)); } // Taken (the flag is gone): done. Still there (the window's measuring frame): next frame. if focus_first && ui.data_mut(|m| m.remove_temp::(widgets::dialog_focus_flag())).is_none() { @@ -1075,6 +1082,9 @@ mod tests_perspective; #[cfg(test)] mod tests_modal; +#[cfg(test)] +mod tests_scroll; + #[cfg(test)] mod tests_rectangular_grid; diff --git a/crates/ui-egui/src/dialogs/brush_art_options.rs b/crates/ui-egui/src/dialogs/brush_art_options.rs index 62d4a2e368..64ea036fa2 100644 --- a/crates/ui-egui/src/dialogs/brush_art_options.rs +++ b/crates/ui-egui/src/dialogs/brush_art_options.rs @@ -9,7 +9,7 @@ //! open). //! Scatter: per value (`size`, `spacing`, `scatter` %, `rotation` °) `…Min`, `…Max` and `…Mode` //! (`fixed` | `random` | `pressure` | `tilt` | `bearing` | `rotation`), `rotationRelativeTo` (`page` | -//! `path`). +//! `path`), `hueJitter` (°). //! Art: `width` (%), `widthMode` (`fixed` | `pressure` | `tilt` | `bearing` | `rotation`), //! `widthMax` (the width at the heaviest pen pressure, upright or at 180°, %), `scaleMode` (`proportional` | `stretch` | `betweenGuides`), `guideStart` and //! `guideEnd` (% of the art's length), `direction` (`leftToRight` …), `flipAlong`, `flipAcross`, @@ -187,6 +187,7 @@ pub(super) fn fields(b: &Brush, def: Value, f: &mut Map) { f.insert(mode_key(key), json!(mode.id())); } f.insert("rotationRelativeTo".into(), json!(if s.rotation_relative_to_path { "path" } else { "page" })); + f.insert("hueJitter".into(), json!(s.hue_jitter)); } BrushKind::Art(a) => { let (mode, start, end) = match a.scale { @@ -268,6 +269,7 @@ pub(super) fn params(d: &Dialog) -> Value { p[*key] = json!([clamped(d, &min_key(key), range), clamped(d, &max_key(key), range)]); } p["modes"] = json!(SCATTER.map(|(key, _)| scatter_mode(d, key).id())); + p["hue_jitter"] = json!(clamped(d, "hueJitter", Scatter::HUE_JITTER_RANGE)); p } "art" => { @@ -457,6 +459,9 @@ fn scatter_body(ui: &mut egui::Ui, d: &mut Dialog) { ui.add_space(4.0); let relative = [("page", tl!("Page")), ("path", tl!("Path"))]; super::form::choice(ui, d, "rotationRelativeTo", tl!("Rotation relative to:"), (LABEL_W, 104.0), &relative); + ui.add_space(4.0); + // Each copy turns its colors' hue by its own amount up to this many degrees either way. + widgets::label_row(ui, tl!("Hue Jitter:"), LABEL_W, |ui| number(ui, d, "hueJitter", Scatter::HUE_JITTER_RANGE, "°", true)); } fn art_body(ui: &mut egui::Ui, d: &mut Dialog) { diff --git a/crates/ui-egui/src/dialogs/brush_options/tests.rs b/crates/ui-egui/src/dialogs/brush_options/tests.rs index 670396947c..de59668708 100644 --- a/crates/ui-egui/src/dialogs/brush_options/tests.rs +++ b/crates/ui-egui/src/dialogs/brush_options/tests.rs @@ -153,6 +153,7 @@ fn scatter_options_show_each_value_with_its_mode_and_ok_applies_them() { "Random", "Rotation relative to:", "Page", + "Hue Jitter:", "Colorization", "Method:", "Tints", @@ -163,10 +164,11 @@ fn scatter_options_show_each_value_with_its_mode_and_ok_applies_them() { let d = app.ui.dialog.as_ref().unwrap(); assert_eq!((d.f64("sizeMin", 0.0), d.f64("sizeMax", 0.0), d.str("sizeMode")), (60.0, 140.0, "random".into())); assert_eq!((d.str("rotationRelativeTo"), d.str("colorization")), ("page".into(), "tints".into())); - // Values are kept within their ranges (rotation here); Fixed takes the first value. + assert_eq!(d.f64("hueJitter", -1.0), 0.0); + // Values are kept within their ranges (rotation and hue jitter here); Fixed takes the first value. set( &mut app, - json!({"sizeMode": "fixed", "sizeMin": 5000, "spacingMode": "pressure", "rotationMin": -400, "rotationRelativeTo": "path", "colorization": "hueShift"}), + json!({"sizeMode": "fixed", "sizeMin": 5000, "spacingMode": "pressure", "rotationMin": -400, "rotationRelativeTo": "path", "colorization": "hueShift", "hueJitter": 400}), ); assert!(shown(&mut app).contains("Hue Shift")); super::super::confirm(&mut app).unwrap(); @@ -177,12 +179,14 @@ fn scatter_options_show_each_value_with_its_mode_and_ok_applies_them() { (&json!([5000.0, 140.0]), &json!(-180.0), &json!(["fixed", "pressure", "random", "random"])) ); assert_eq!((&def["rotation_relative_to_path"], &def["colorization"]["method"]), (&json!(true), &json!("hueShift"))); + assert_eq!(def["hue_jitter"], json!(180.0)); assert!(def["colorization"]["key"].is_object(), "the art's colour as the key: {def}"); assert!(drawn_height(&app, id) > before, "the stroke redraws with the bigger confetti"); // Opened again, it shows what was set. app.run("ui.brushOptions", json!({"name": "Confetti"})).unwrap(); let d = app.ui.dialog.as_ref().unwrap(); assert_eq!((d.str("sizeMode"), d.str("spacingMode"), d.str("colorization")), ("fixed".into(), "pressure".into(), "hueShift".into())); + assert_eq!(d.f64("hueJitter", 0.0), 180.0); } #[test] diff --git a/crates/ui-egui/src/dialogs/char_style_options.rs b/crates/ui-egui/src/dialogs/char_style_options.rs index b4abf8c6e2..c07f7af647 100644 --- a/crates/ui-egui/src/dialogs/char_style_options.rs +++ b/crates/ui-egui/src/dialogs/char_style_options.rs @@ -1036,6 +1036,7 @@ fn content_id(ui: &egui::Ui) -> egui::Id { /// (as drawn last frame). The section list stays put while the content scrolls. Returns whether /// the dialog asks to be canceled (never: Cancel comes from the button row in `dialogs::show`). fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { + super::modal::fits_itself(ui); let window = ui.ctx().memory(|m| m.area_rect(ui.layer_id().id)).map_or(0.0, |r| r.height()); let content = ui.ctx().data(|m| m.get_temp::(content_id(ui))).unwrap_or(0.0); let rest = (window - content).max(0.0); diff --git a/crates/ui-egui/src/dialogs/color_picker.rs b/crates/ui-egui/src/dialogs/color_picker.rs index 5ce5e64e53..758832cd92 100644 --- a/crates/ui-egui/src/dialogs/color_picker.rs +++ b/crates/ui-egui/src/dialogs/color_picker.rs @@ -384,6 +384,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> DialogAction { let p = picked(d); let original = d.fields.get("original").and_then(color_value).unwrap_or(p.color); let gamut = gamut_fix(app, ui.ctx(), "picker-gamut", &p.color); + super::modal::fits_itself(ui); let (side, values_w, button_w, stacked) = layout_size(ui); let field_w = side + SLIDER_GAP + SLIDER_W; let content_w = if stacked { field_w.max(values_w) } else { field_w + COLUMN_GAP + values_w }; diff --git a/crates/ui-egui/src/dialogs/dimension.rs b/crates/ui-egui/src/dialogs/dimension.rs index 1a08c4d377..3a977e76c6 100644 --- a/crates/ui-egui/src/dialogs/dimension.rs +++ b/crates/ui-egui/src/dialogs/dimension.rs @@ -4,7 +4,7 @@ use super::DialogSpec; use crate::{VectorcraftApp, state::Dialog, theme::Tokens, widgets}; use egui::{RichText, Ui}; use serde_json::{Value, json}; -use vectorcraft_doc::dimension::DimensionOptions; +use vectorcraft_doc::dimension::{ArrowStyle, DimensionOptions}; pub const KIND: &str = "dimensionOptions"; pub(super) const SPEC: DialogSpec = DialogSpec { @@ -32,6 +32,10 @@ const UNITS: Choices = &[ ]; const LINE_TYPES: Choices = &[("solid", "Solid"), ("dashed", "Dashed"), ("dotted", "Dotted")]; const ARROWS: Choices = &[("filled", "Filled"), ("open", "Open"), ("tick", "Tick"), ("none", "None")]; +/// The style of each `ARROWS` entry, in the same order. +const ARROW_STYLES: [ArrowStyle; 4] = [ArrowStyle::Filled, ArrowStyle::Open, ArrowStyle::Tick, ArrowStyle::None]; +/// The size of an Arrow Style preview: a line with the head at its right end. +const ARROW_PREVIEW: egui::Vec2 = egui::vec2(40.0, 16.0); const POSITIONS: Choices = &[("away", "Away from the Line"), ("between", "Between Line and Object")]; const ALIGNMENTS: Choices = &[("left", "Left"), ("center", "Center"), ("right", "Right")]; @@ -69,6 +73,29 @@ fn choose(ui: &mut Ui, fields: &mut serde_json::Map, key: &str, l }); changed } +/// The Arrow Style dropdown: each style shows a drawn preview of its arrowhead before its name, in +/// the open list and in the closed field. +fn arrow_style(ui: &mut Ui, fields: &mut serde_json::Map, id: &str) -> bool { + const KEY: &str = "arrowStyle"; + let mut changed = false; + widgets::label_row(ui, tl!("Arrow Style:"), 96.0, |ui| { + let current = fields.get(KEY).and_then(Value::as_str).unwrap_or_default(); + let shown = ARROWS.iter().position(|(v, _)| *v == current); + let names: Vec<&str> = ARROWS.iter().map(|(_, s)| tl!(*s)).collect(); + let icon = |ui: &Ui, rect: egui::Rect, i: usize, ink: egui::Color32, _: bool| { + if let Some(style) = ARROW_STYLES.get(i) { + crate::panels::stroke::paint_arrow(ui, rect, style.arrowhead().as_ref(), false, ink); + } + }; + if let Some((value, _)) = + widgets::dropdown_icon_names_sized(ui, ("dimension", id), shown, &names, 150.0, ARROW_PREVIEW, icon).and_then(|i| ARROWS.get(i)) + { + fields.insert(KEY.into(), json!(value)); + changed = true; + } + }); + changed +} fn number(ui: &mut Ui, fields: &mut serde_json::Map, key: &str, label: &str, range: (f64, f64), suffix: &str) -> bool { let mut changed = false; widgets::label_row(ui, tl!(label), 96.0, |ui| { @@ -160,7 +187,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool { color(ui, f, "lineColor"); }); ui.horizontal(|ui| { - choose(ui, f, "arrowStyle", "Arrow Style:", ARROWS); + arrow_style(ui, f, "arrowStyle"); number(ui, f, "arrowScale", "Arrow Scale:", (1.0, 1000.0), "%"); }); }); @@ -310,7 +337,7 @@ pub fn properties_section(app: &mut VectorcraftApp, ui: &mut Ui) { changed |= number(ui, &mut f, "lineWeight", "Line Weight:", (0.1, 100.0), "pt"); changed |= color(ui, &mut f, "lineColor"); }); - ui.horizontal(|ui| changed |= choose(ui, &mut f, "arrowStyle", "Arrow Style:", ARROWS)); + ui.horizontal(|ui| changed |= arrow_style(ui, &mut f, "props-arrowStyle")); ui.horizontal(|ui| { changed |= number(ui, &mut f, "fontSize", "Font Size:", (1.0, 1000.0), "pt"); changed |= color(ui, &mut f, "textColor"); @@ -377,4 +404,56 @@ mod tests { assert!(text.contains(label), "{label}: {text}"); } } + + /// Whether a frame drew a picture (a textured mesh) just before the text `name` on its line. + fn picture_before(out: &egui::FullOutput, name: &str) -> bool { + fn collect(s: &egui::Shape, texts: &mut Vec<(String, egui::Rect)>, pictures: &mut Vec) { + match s { + egui::Shape::Text(t) => texts.push((t.galley.text().to_owned(), t.visual_bounding_rect())), + egui::Shape::Mesh(m) if m.texture_id != egui::TextureId::default() => pictures.push(m.calc_bounds()), + egui::Shape::Vec(v) => v.iter().for_each(|s| collect(s, texts, pictures)), + _ => {} + } + } + let (mut texts, mut pictures) = (vec![], vec![]); + for c in &out.shapes { + collect(&c.shape, &mut texts, &mut pictures); + } + texts + .iter() + .filter(|(t, _)| t == name) + .any(|(_, r)| pictures.iter().any(|p| p.max.x <= r.min.x + 1.0 && r.min.x - p.max.x < 16.0 && p.min.y < r.max.y && p.max.y > r.min.y)) + } + + /// The frame `f` draws, once its previews are loaded. + fn frame(app: &mut VectorcraftApp, mut f: impl FnMut(&mut VectorcraftApp, &mut Ui)) -> egui::FullOutput { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + ctx.run_ui(egui::RawInput::default(), |ui| f(app, ui)).textures_delta.clear(); + ctx.run_ui(egui::RawInput::default(), |ui| f(app, ui)) + } + + /// The Arrow Style field of the Tool Options and of Properties shows the style's arrowhead, + /// drawn, before its name (#8049). + #[test] + fn arrow_style_shows_a_drawn_arrowhead() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("tool.options", json!({"tool":"dimension"})).unwrap(); + let out = frame(&mut app, |app, ui| super::super::show(app, ui.ctx())); + assert!(picture_before(&out, "Filled"), "Tool Options"); + app.ui.dialog = None; + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run("dimension.create", json!({"a":[10,10],"b":[110,10],"options":{"arrowStyle":"tick"}})).unwrap(); + let out = frame(&mut app, properties_section); + assert!(picture_before(&out, "Tick"), "Properties"); + } + + /// Each Arrow Style entry previews the style its value names. + #[test] + fn arrow_previews_follow_the_listed_styles() { + assert_eq!(ARROWS.len(), ARROW_STYLES.len()); + for ((value, _), style) in ARROWS.iter().zip(ARROW_STYLES) { + assert_eq!(serde_json::to_value(style).unwrap(), json!(value)); + } + } } diff --git a/crates/ui-egui/src/dialogs/form.rs b/crates/ui-egui/src/dialogs/form.rs index c57671803e..b46f35a79f 100644 --- a/crates/ui-egui/src/dialogs/form.rs +++ b/crates/ui-egui/src/dialogs/form.rs @@ -111,7 +111,7 @@ fn lengths(kind: &str) -> &'static [&'static str] { /// number: fields that ↑/↓ step by one (Shift: ten) and that do math, as the distances do. fn suffix(kind: &str, key: &str) -> Option<&'static str> { match (kind, key) { - ("rotate" | "shear" | "reflect" | "move" | "lineSegment", "angle") => Some("°"), + ("rotate" | "shear" | "reflect" | "move" | "lineSegment", "angle") | ("shear", "axisAngle") => Some("°"), ("scale", "sx" | "sy") | ("spiral", "decay") => Some("%"), _ => None, } @@ -138,6 +138,7 @@ fn order(kind: &str) -> &'static [&'static str] { "spiral" => &["radius", "decay", "segments"], "artboardOptions" => &["name", "width", "height"], "lineSegment" => &["length", "angle"], + "shear" => &["angle", "axis", "axisAngle"], _ => &[], } } @@ -163,8 +164,7 @@ fn choices(kind: &str, key: &str) -> Vec<(&'static str, &'static str)> { match (kind, key) { ("offsetPath", "joins") => vec![("miter", tl!("Miter")), ("round", tl!("Round")), ("bevel", tl!("Bevel"))], ("average", "axis") => vec![axis("horizontal", "Horizontal"), axis("vertical", "Vertical"), axis("both", "Both")], - ("reflect", "axis") => vec![axis("horizontal", "Horizontal"), axis("vertical", "Vertical"), axis("angle", "Angle")], - ("shear", "axis") => vec![axis("horizontal", "Horizontal"), axis("vertical", "Vertical")], + ("reflect" | "shear", "axis") => vec![axis("horizontal", "Horizontal"), axis("vertical", "Vertical"), axis("angle", "Angle")], _ => vec![], } } @@ -368,11 +368,19 @@ pub(super) fn grid_then(ui: &mut egui::Ui, d: &mut Dialog, unit: Unit, more: imp if lengths.contains(&k.as_str()) { length_field(ui, d, &k, &humanized(&k), unit); } else if let Some(suffix) = suffix(&d.kind, &k) { - let row = row_label(ui, &humanized(&k)); + let label = match (d.kind.as_str(), k.as_str()) { + ("shear", "axisAngle") => tl!("Axis Angle").into(), + _ => humanized(&k), + }; + // Shear's Axis Angle is the axis while the Angle axis is chosen, and keeps its value otherwise. + let enabled = d.kind != "shear" || k != "axisAngle" || d.str("axis") == "angle"; + let row = row_label(ui, &label); ui.label_inputs_by(row.id, |ui| { - if let Some(v) = crate::widgets::plain_field(ui, ("dlg-num", &k), d.f64(&k, 0.0), suffix, 3, FIELD_W) { - d.fields.insert(k, json!(v)); - } + ui.add_enabled_ui(enabled, |ui| { + if let Some(v) = crate::widgets::plain_field(ui, ("dlg-num", &k), d.f64(&k, 0.0), suffix, 3, FIELD_W) { + d.fields.insert(k, json!(v)); + } + }); }); ui.end_row(); } else if let Some(ends) = skew_ends(&d.kind, &k) { diff --git a/crates/ui-egui/src/dialogs/freehand.rs b/crates/ui-egui/src/dialogs/freehand.rs index 205507a7b5..78fdd8bdd1 100644 --- a/crates/ui-egui/src/dialogs/freehand.rs +++ b/crates/ui-egui/src/dialogs/freehand.rs @@ -334,22 +334,65 @@ fn body(_app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { /// Side of the Blob Brush tip preview's square, in points. const TIP_PREVIEW: f32 = 64.0; -/// The Blob Brush's tip preview: a square with the tip at its Angle and Roundness and a line along -/// its long axis, and beside it three dabs of the tip, the middle one darker. A click or a drag in -/// the square points the Angle at the pointer and gives the square the keyboard focus; screen -/// readers get it as the Angle slider, and its keys step the Angle as a dialog slider's do -/// ([`widgets::stepped_area`]) within -180° to 180°. +/// Half the length of the Blob Brush tip in its preview, in points. +const TIP_LONG: f32 = 18.0; + +/// How far from a Roundness dot of the tip preview a press still takes the dot, in points. +const TIP_DOT_REACH: f32 = 8.0; + +/// The Blob Brush's tip preview: a square with the tip at its Angle and Roundness, a line with an +/// arrowhead along its long axis and a black dot at each end of its short axis, and beside it three +/// dabs of the tip, the middle one darker. A click or a drag that starts on a dot sets the +/// Roundness from the pointer's distance from the center along the short axis +/// ([`blob_tip_roundness_at`]) until the release, inside the square or out of it, and gives the +/// Roundness slider the keyboard focus. A click or a drag that starts anywhere else in the square +/// points the Angle at the pointer and gives the Angle slider the focus. Screen readers get the +/// square as the Angle slider and then the Roundness slider, and their keys step the Angle within +/// -180° to 180° and the Roundness within 0% to 100% as a dialog slider's do +/// ([`widgets::stepped_area`]). fn blob_tip_preview(ui: &mut egui::Ui, d: &mut Dialog) { let t = Tokens::get(ui.ctx()); let (rect, _) = ui.allocate_exact_size(egui::vec2(CONTENT_W, TIP_PREVIEW), egui::Sense::hover()); let square = egui::Rect::from_min_size(rect.min, egui::vec2(TIP_PREVIEW, TIP_PREVIEW)); + let center = square.center(); let response = ui.interact(square, ui.scope_id().with("freehand-tip-angle"), egui::Sense::click_and_drag()); + // Whether the press that started this click or drag was on a dot: it is kept until the release. + let on_dot = response.id.with("on-dot"); + let near_dot = |p: egui::Pos2, d: &Dialog| { + blob_tip_dots(center, d.f64("angle", 0.0), d.f64("roundness", 100.0)).iter().any(|dot| dot.distance(p) <= TIP_DOT_REACH) + }; + let mut started = ui.data(|m| m.get_temp::(on_dot)); + if started.is_none() && response.is_pointer_button_down_on() { + let pressed = ui.input(|i| i.pointer.press_origin()).is_some_and(|p| near_dot(p, d)); + ui.data_mut(|m| m.insert_temp(on_dot, pressed)); + started = Some(pressed); + } + // A click whose press and release came in the same frame: its press is among this frame's events. + let dot_drag = started.unwrap_or_else(|| { + let press = ui.input(|i| { + i.events.iter().rev().find_map(|e| match e { + egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: true, .. } => Some(*pos), + _ => None, + }) + }); + response.clicked() && press.is_some_and(|p| near_dot(p, d)) + }); + if !response.is_pointer_button_down_on() { + ui.data_mut(|m| m.remove_temp::(on_dot)); + } if let Some((p, _)) = widgets::pointer_phase(&response) { - let delta = p - square.center(); - if delta.length_sq() > 1.0 { + let delta = p - center; + if dot_drag { + d.fields.insert("roundness".into(), json!(blob_tip_roundness_at(delta, d.f64("angle", 0.0)))); + } else if delta.length_sq() > 1.0 { d.fields.insert("angle".into(), json!(f64::from((-delta.y).atan2(delta.x)).to_degrees().round())); } } + if dot_drag && response.is_pointer_button_down_on() { + ui.ctx().set_cursor_icon(egui::CursorIcon::Grabbing); + } else if response.hover_pos().is_some_and(|p| near_dot(p, d)) && !response.is_pointer_button_down_on() { + ui.ctx().set_cursor_icon(egui::CursorIcon::Grab); + } let painter = ui.painter_at(rect); painter.rect_filled(square, 2.0, t.input); painter.rect_stroke(square, 2.0, egui::Stroke::new(1.0, t.input_border), egui::StrokeKind::Inside); @@ -358,11 +401,17 @@ fn blob_tip_preview(ui: &mut egui::Ui, d: &mut Dialog) { if let Some(a) = widgets::stepped_area(ui, &response, tl!("Angle"), Some(shown)) { d.fields.insert("angle".into(), json!(a)); } - let a = d.f64("angle", 0.0).clamp(-180.0, 180.0).to_radians(); - // The long axis on screen (y down: a positive angle tilts it up to the right) and the short one. - let u = egui::vec2(a.cos() as f32, -a.sin() as f32); - let v = egui::vec2(-u.y, u.x); - let long = 18.0; + // The Roundness slider takes the focus and the keys only: the square's response reads the pointer. + let roundness = ui.interact(square, ui.scope_id().with("freehand-tip-roundness"), egui::Sense::focusable_noninteractive()); + if dot_drag && (response.drag_started() || response.clicked()) { + widgets::focus_by_pointer(ui, roundness.id); + } + let shown = widgets::SliderValue::field(d.f64("roundness", 100.0), 0.0..=100.0, "%", 0); + if let Some(r) = widgets::stepped_area(ui, &roundness, tl!("Roundness"), Some(shown)) { + d.fields.insert("roundness".into(), json!(r)); + } + let (u, v) = blob_tip_axes(d.f64("angle", 0.0)); + let long = TIP_LONG; let short = long * blob_tip_short_ratio(d.f64("roundness", 100.0)); let dab = |center: egui::Pos2, color: egui::Color32| { let points = (0..32) @@ -373,15 +422,44 @@ fn blob_tip_preview(ui: &mut egui::Ui, d: &mut Dialog) { .collect(); painter.add(egui::Shape::convex_polygon(points, color, egui::Stroke::NONE)); }; - let center = square.center(); dab(center, t.text); - painter.line_segment([center, center + u * 25.0], egui::Stroke::new(1.0, t.accent)); + painter.line_segment([center, center + u * 22.0], egui::Stroke::new(1.0, t.accent)); + let arrowhead = vec![center + u * 28.0, center + u * 22.0 + v * 3.0, center + u * 22.0 - v * 3.0]; + painter.add(egui::Shape::convex_polygon(arrowhead, t.accent, egui::Stroke::NONE)); + // Black with a white rim, so a dot shows on the tip and on the square in either theme. + for dot in blob_tip_dots(center, d.f64("angle", 0.0), d.f64("roundness", 100.0)) { + painter.circle(dot, 3.0, egui::Color32::BLACK, egui::Stroke::new(1.0, egui::Color32::WHITE)); + } let strip = square.right() + 2.5 * long; for (i, color) in [t.text_dim, t.text, t.text_dim].into_iter().enumerate() { dab(egui::pos2(strip + i as f32 * 1.5 * long, center.y), color); } } +/// The tip preview's long axis on screen at Angle `angle` (degrees, y down: a positive angle tilts +/// it up to the right), and its short axis. +fn blob_tip_axes(angle: f64) -> (egui::Vec2, egui::Vec2) { + let a = angle.clamp(-180.0, 180.0).to_radians(); + let u = egui::vec2(a.cos() as f32, -a.sin() as f32); + (u, egui::vec2(-u.y, u.x)) +} + +/// The two Roundness dots of the tip preview centered on `center`: the ends of the tip's short +/// axis at Angle `angle` and Roundness `roundness`. +fn blob_tip_dots(center: egui::Pos2, angle: f64, roundness: f64) -> [egui::Pos2; 2] { + let (_, v) = blob_tip_axes(angle); + let short = v * (TIP_LONG * blob_tip_short_ratio(roundness)); + [center + short, center - short] +} + +/// The Roundness, in whole percent from 0 to 100, that a dot of the tip preview dragged to `offset` +/// from the preview's center gives at Angle `angle`: the distance along the tip's short axis, on +/// either side of the center, as a percentage of half the tip's length. +fn blob_tip_roundness_at(offset: egui::Vec2, angle: f64) -> f64 { + let (_, v) = blob_tip_axes(angle); + (f64::from(offset.dot(v).abs() / TIP_LONG) * 100.0).round().clamp(0.0, 100.0) +} + /// The preview tip's short axis as a fraction of its long axis: Roundness in percent, with 0 /// percent drawn as 0.1 percent, the minimum the brush draws with. fn blob_tip_short_ratio(roundness: f64) -> f32 { diff --git a/crates/ui-egui/src/dialogs/freehand/tests.rs b/crates/ui-egui/src/dialogs/freehand/tests.rs index 8f23bd537b..6ec010a8bd 100644 --- a/crates/ui-egui/src/dialogs/freehand/tests.rs +++ b/crates/ui-egui/src/dialogs/freehand/tests.rs @@ -54,6 +54,30 @@ fn the_tip_preview_is_as_flat_as_the_tip_the_brush_draws() { } } +/// A Roundness dot of the tip preview gives its distance from the center along the tip's short +/// axis as a percentage of half the tip's length, on either side and at any Angle: 0% at the +/// center, 100% at half the length and past it. A move along the long axis leaves it as it is, and +/// the dots drawn for a Roundness give that Roundness back. +#[test] +fn a_roundness_dot_sets_its_distance_along_the_short_axis() { + for angle in [0.0, 30.0, 90.0, -135.0, 180.0] { + let (u, v) = blob_tip_axes(angle); + for (along, want) in [(0.0, 0.0), (4.5, 25.0), (-9.0, 50.0), (18.0, 100.0), (-18.0, 100.0), (40.0, 100.0), (-400.0, 100.0)] { + for sideways in [0.0, 7.0, -30.0] { + assert_eq!(blob_tip_roundness_at(v * along + u * sideways, angle), want, "angle {angle}, {along} along, {sideways} sideways"); + } + } + let center = egui::pos2(32.0, 32.0); + for roundness in [0.0, 1.0, 37.0, 50.0, 99.0, 100.0] { + let [a, b] = blob_tip_dots(center, angle, roundness); + assert!(((a - center) + (b - center)).length() < 1e-4, "the dots face each other across the center"); + for dot in [a, b] { + assert_eq!(blob_tip_roundness_at(dot - center, angle), roundness, "angle {angle}"); + } + } + } +} + /// The labels the open dialog paints. fn painted(app: &mut VectorcraftApp) -> String { crate::tests_labels::painted_text(app, |app, ui| super::super::show(app, ui.ctx())) diff --git a/crates/ui-egui/src/dialogs/modal.rs b/crates/ui-egui/src/dialogs/modal.rs index c7bedbe2b1..c5acd64e18 100644 --- a/crates/ui-egui/src/dialogs/modal.rs +++ b/crates/ui-egui/src/dialogs/modal.rs @@ -2,8 +2,9 @@ //! window with no title bar that opens centred and moves by dragging its heading (the band from its //! top edge down to the heading), as a title bar would, showing the arrow until it is dragged. Where //! it was moved to stays, per window, for the session, and the window never leaves the screen. Rows -//! too many for the screen's height scroll inside it ([`scrolled_rows`]), so its heading and buttons -//! stay in view. +//! too many for the screen's height scroll inside it ([`scrolled_rows`], [`body_rows`]), so its +//! heading and buttons stay in view. A window without such rows that is still too tall or too wide +//! for the screen scrolls as a whole on that axis. use egui::{Id, Rect, Vec2}; @@ -35,11 +36,97 @@ pub(crate) fn show_at(ctx: &egui::Context, title: &str, id: Id, initial: Vec2 .title_bar(false) .anchor(egui::Align2::CENTER_CENTER, offset(ctx, id, initial)) .frame(egui::Frame::window(&ctx.global_style()).fill(t.panel).inner_margin(egui::Margin::same(margin))) - .show(ctx, add)?; - keep_rest(ctx, id, shown.response.rect.height()); + .show(ctx, |ui| { + // Just opened: what scrolls in the window starts at its top, wherever it was left when + // the window last closed. + if opened(ctx, id) { + ctx.data_mut(|m| { + m.insert_temp(id.with(TOP_ROWS_KEY), true); + m.insert_temp(id.with(TOP_WHOLE_KEY), true); + }); + } + // A window whose contents are wider than the screen has room for, or taller without + // rows that scroll ([`scrolled_rows`], [`body_rows`]), scrolls as a whole on that axis, + // so none of it is out of reach. The contents keep their ids whether the window scrolls + // or not, so a field being edited keeps its text when that changes. + let [wide, tall] = ctx.data(|m| m.get_temp::<[bool; 2]>(id.with(WHOLE_KEY))).unwrap_or_default(); + let scope = egui::UiBuilder::new().scope_id(id.with("modal-contents")); + let (r, contents) = if wide || tall { + let room = whole_room(ctx, margin); + let mut area = egui::ScrollArea::new([wide, tall]); + if ctx.data_mut(|m| m.remove_temp::(id.with(TOP_WHOLE_KEY))).is_some() { + area = area.scroll_offset(Vec2::ZERO); + } + let out = area + .id_salt("modal-whole") + .max_width(room.x) + .max_height(room.y) + .min_scrolled_width(room.x) + .min_scrolled_height(room.y) + .show(ui, |ui| ui.scope_builder(scope, add).inner); + (out.inner, out.content_size) + } else { + let r = ui.scope_builder(scope, add).inner; + (r, ui.min_rect().size()) + }; + ctx.data_mut(|m| m.insert_temp(id.with(CONTENTS_KEY), contents)); + r + })?; + keep_rest(ctx, id, shown.response.rect.height(), margin); shown.inner } +/// Mark the modal window drawn next in this pass as opened over the one drawn in the pass before, +/// which it hides until it closes and shows that one again (Import Shortcut Set over Keyboard +/// Shortcuts). The window under it keeps where it was scrolled to. +pub(crate) fn over_parent(ctx: &egui::Context) { + let pass = ctx.cumulative_pass_nr(); + ctx.data_mut(|m| m.insert_temp(Id::unique(OVER_KEY), pass)); +} + +/// Whether modal window `id`, drawn in this pass, opened in it: it was not drawn in the pass before, +/// and none of the windows drawn in the pass before was one opened over it ([`over_parent`]). +fn opened(ctx: &egui::Context, id: Id) -> bool { + let pass = ctx.cumulative_pass_nr(); + ctx.data_mut(|m| { + // The windows drawn in this pass so far and in the pass before. + let (at, now, prev) = m.get_temp::<(u64, Vec, Vec)>(Id::unique(LAST_KEY)).unwrap_or_default(); + let (mut now, prev) = if at == pass { + (now, prev) + } else if at.saturating_add(1) == pass { + (vec![], now) + } else { + (vec![], vec![]) + }; + let before: Vec = prev.iter().copied().filter(|&other| other != id).collect(); + now.push(id); + m.insert_temp(Id::unique(LAST_KEY), (pass, now, prev)); + let last = std::mem::replace(m.get_temp_mut_or(id.with(SHOWN_KEY), u64::MAX), pass); + if last != u64::MAX && last.saturating_add(1) >= pass { + return false; + } + // Shown again as the window opened over it closed. + if before.iter().any(|over| m.get_temp::(over.with(HOLDS_KEY)) == Some(id)) { + return false; + } + // Opened over the window drawn last in the pass before, it holds that one; otherwise none. + match before.last().copied().filter(|_| m.get_temp::(Id::unique(OVER_KEY)) == Some(pass)) { + Some(under) => { + m.insert_temp(id.with(HOLDS_KEY), under); + } + None => { + m.remove::(id.with(HOLDS_KEY)); + } + } + true + }) +} + +/// The room for the contents of a modal window with `margin` inside its frame. +fn whole_room(ctx: &egui::Context, margin: i8) -> Vec2 { + (ctx.content_rect().size() - Vec2::splat(2.0 * (super::EDGE_GAP + f32::from(margin)))).max(Vec2::ZERO) +} + /// The layer of the backdrop behind a modal dialog window, which takes the clicks the rest of /// the app would get. pub(crate) fn backdrop() -> egui::LayerId { @@ -86,34 +173,158 @@ pub(super) fn handle(id: Id) -> Id { id.with("modal-drag") } -/// Under a modal window's id: how tall its [`scrolled_rows`] were drawn this frame, and how tall -/// the rest of it was when last drawn. +/// Under a modal window's id: how tall its [`scrolled_rows`] (or [`body_rows`]) were drawn this +/// frame, and how tall the rest of it was when last drawn. const ROWS_KEY: &str = "modal-rows"; const REST_KEY: &str = "modal-rest"; +/// Under a modal window's id: its contents drew [`scrolled_rows`] of their own or fit themselves to +/// the screen ([`fits_itself`]) this frame (`OWN_ROWS_KEY`), or last frame (`OWN_BEFORE_KEY`). +const OWN_ROWS_KEY: &str = "modal-own-rows"; +const OWN_BEFORE_KEY: &str = "modal-own-before"; +/// Under a modal window's id: how tall its [`body_rows`] would be without scrolling, this frame. +const BODY_KEY: &str = "modal-body"; +/// Under a modal window's id: how large its contents would be without scrolling as a whole, this +/// frame. +const CONTENTS_KEY: &str = "modal-contents"; +/// Under a modal window's id, for the next frame: its [`body_rows`] scroll (`TALL_KEY`), and on +/// which axes ([wide, tall]) it scrolls as a whole (`WHOLE_KEY`). +const TALL_KEY: &str = "modal-tall"; +const WHOLE_KEY: &str = "modal-whole"; +/// Under a modal window's id: the pass it was last drawn in (`SHOWN_KEY`), and, since it opened, +/// its rows (`TOP_ROWS_KEY`) or the window as a whole (`TOP_WHOLE_KEY`) have not scrolled yet, so +/// they start at the top when they first do. +const SHOWN_KEY: &str = "modal-shown"; +const TOP_ROWS_KEY: &str = "modal-top-rows"; +const TOP_WHOLE_KEY: &str = "modal-top-whole"; +/// For all modal windows: the pass the last one was drawn in, the ids of those drawn in that pass +/// and of those drawn in the pass before it (`LAST_KEY`), and the pass +/// in which the window drawn next was marked as opened over another ([`over_parent`], `OVER_KEY`). +/// Under a modal window's id: the window it was opened over and hides (`HOLDS_KEY`). +const LAST_KEY: &str = "modal-last"; +const OVER_KEY: &str = "modal-over"; +const HOLDS_KEY: &str = "modal-holds"; /// Rows of the modal window `ui` is in (one list of them per window) that scroll if the window /// would be taller than the screen. Their height is the screen's less the rest of the window as /// last drawn (a frame late, as only the drawn window knows its height). /// Rows that fit are as tall as they are. pub(crate) fn scrolled_rows(ui: &mut egui::Ui, salt: impl egui::AsIdSalt, add: impl FnOnce(&mut egui::Ui) -> R) -> R { - let id = ui.layer_id().id; - let rest = ui.ctx().data(|m| m.get_temp::(id.with(REST_KEY))).unwrap_or(0.0); - let room = (ui.ctx().content_rect().height() - rest - 2.0 * super::EDGE_GAP).max(0.0); - // As tall as the room at once: by itself a scroll area grows a frame at a time with the window. - let rows = ui.scope(|ui| egui::ScrollArea::vertical().id_salt(salt).max_height(room).min_scrolled_height(room).show(ui, add).inner); - ui.ctx().data_mut(|m| m.insert_temp(id.with(ROWS_KEY), rows.response.rect.height())); - rows.inner + fits_itself(ui); + let (r, drawn, _) = rows(ui, salt, true, add); + ui.ctx().data_mut(|m| m.insert_temp(ui.layer_id().id.with(ROWS_KEY), drawn)); + r } -/// After modal window `id` is drawn `height` tall: keep the height of all of it but its -/// [`scrolled_rows`] for the next frame. If the rows were sized by a different one (the window just -/// opened, or what is around them changed), the next frame is drawn at once, for the rows to fit -/// without waiting for input. -fn keep_rest(ctx: &egui::Context, id: Id, height: f32) { - let Some(rows) = ctx.data_mut(|m| m.remove_temp::(id.with(ROWS_KEY))) else { return }; - let rest = (height - rows).max(0.0); - let used = ctx.data_mut(|m| std::mem::replace(m.get_temp_mut_or(id.with(REST_KEY), 0.0), rest)); - if (used - rest).abs() > 0.5 { +/// Mark the contents of the modal window `ui` is in as fitting themselves to the screen (sizing +/// what scrolls in them from the screen's height), so neither [`body_rows`] nor the window +/// scroll them again. +pub(crate) fn fits_itself(ui: &egui::Ui) { + ui.ctx().data_mut(|m| m.insert_temp(ui.layer_id().id.with(OWN_ROWS_KEY), true)); +} + +/// The body of a shared dialog window. While the window would be taller than the screen has room +/// for, the body scrolls as [`scrolled_rows`] do, so the heading and the buttons stay in view; +/// otherwise it is drawn as it is. A body that fits itself ([`fits_itself`]) is drawn as it is. +pub(crate) fn body_rows(ui: &mut egui::Ui, add: impl FnOnce(&mut egui::Ui) -> R) -> R { + let id = ui.layer_id().id; + let (r, drawn, body) = rows(ui, "dialog-body", body_scrolls(ui.ctx(), id), add); + if !ui.ctx().data(|m| m.get_temp::(id.with(OWN_ROWS_KEY))).unwrap_or(false) { + ui.ctx().data_mut(|m| { + m.insert_temp(id.with(ROWS_KEY), drawn); + m.insert_temp(id.with(BODY_KEY), body); + }); + } + r +} + +/// Whether the [`body_rows`] of modal window `id` scroll in this frame. +fn body_scrolls(ctx: &egui::Context, id: Id) -> bool { + let own = ctx.data(|m| m.get_temp::(id.with(OWN_BEFORE_KEY))).unwrap_or(false); + !own && ctx.data(|m| m.get_temp::(id.with(TALL_KEY))).unwrap_or(false) +} + +/// While the [`body_rows`] of the modal window `ui` is in scroll: how tall they are drawn. +pub(crate) fn body_view(ui: &egui::Ui) -> Option { + let id = ui.layer_id().id; + body_scrolls(ui.ctx(), id).then(|| rows_room(ui.ctx(), id)) +} + +/// How modal window `id` scrolls: while its [`body_rows`] scroll, how tall they are drawn; and on +/// which axes ([wide, tall]) the window scrolls as a whole. +#[cfg(test)] +pub(crate) fn scrolling(ctx: &egui::Context, id: Id) -> (Option, [bool; 2]) { + let body = body_scrolls(ctx, id).then(|| rows_room(ctx, id)); + (body, ctx.data(|m| m.get_temp::<[bool; 2]>(id.with(WHOLE_KEY))).unwrap_or_default()) +} + +/// The height of a list `height` tall at most, with a scroll bar of its own, in the [`body_rows`] +/// of the modal window `ui` is in: while the body scrolls, no taller than the body is drawn, so +/// the list and its bar can be scrolled into view whole. +pub(crate) fn list_height(ui: &egui::Ui, height: f32) -> f32 { + body_view(ui).map_or(height, |view| view.min(height)) +} + +/// The height rows that scroll in modal window `id` are drawn: the screen's less the rest of the +/// window as last drawn. +fn rows_room(ctx: &egui::Context, id: Id) -> f32 { + let rest = ctx.data(|m| m.get_temp::(id.with(REST_KEY))).unwrap_or(0.0); + (ctx.content_rect().height() - rest - 2.0 * super::EDGE_GAP).max(0.0) +} + +/// [`scrolled_rows`] without marking the window's body as having rows of its own or keeping their +/// height. Also returns how tall the rows were drawn and how tall they would be without scrolling. +/// Rows that do not `scroll` are as tall as they are, with no +/// scroll area (which would take the scroll requests of their fields from the window's). The rows +/// keep their ids either way, so a field being edited keeps its text when they start or stop +/// scrolling. +fn rows(ui: &mut egui::Ui, salt: impl egui::AsIdSalt, scroll: bool, add: impl FnOnce(&mut egui::Ui) -> R) -> (R, f32, f32) { + let id = ui.layer_id().id; + let room = rows_room(ui.ctx(), id); + let scope = egui::UiBuilder::new().scope_id(ui.make_persistent_id(&salt).with("modal-rows")); + if !scroll { + let rows = ui.scope_builder(scope, add); + let height = rows.response.rect.height(); + return (rows.inner, height, height); + } + // As tall as the room at once: by itself a scroll area grows a frame at a time with the window. + let mut area = egui::ScrollArea::vertical().id_salt(salt).max_height(room).min_scrolled_height(room); + if ui.ctx().data_mut(|m| m.remove_temp::(id.with(TOP_ROWS_KEY))).is_some() { + area = area.scroll_offset(Vec2::ZERO); + } + let rows = ui.scope(|ui| area.show(ui, |ui| ui.scope_builder(scope, add).inner)); + (rows.inner.inner, rows.response.rect.height(), rows.inner.content_size.y) +} + +/// After modal window `id` (with `margin` inside its frame) is drawn `height` tall: keep the height +/// of all of it but its [`scrolled_rows`] for the next frame. If the rows were sized by a different +/// one (the window just opened, or what is around them changed), the next frame is drawn at once, +/// for the rows to fit without waiting for input. From the next frame on, [`body_rows`] scroll +/// while the window would be taller than the screen has room for without them scrolling; a window +/// without rows that scroll scrolls as a whole while its contents would be taller than the room, +/// and any window scrolls sideways while its contents would be wider. +fn keep_rest(ctx: &egui::Context, id: Id, height: f32, margin: i8) { + let rows = ctx.data_mut(|m| m.remove_temp::(id.with(ROWS_KEY))); + let body = ctx.data_mut(|m| m.remove_temp::(id.with(BODY_KEY))); + let contents = ctx.data_mut(|m| m.remove_temp::(id.with(CONTENTS_KEY))).unwrap_or_default(); + let own = ctx.data_mut(|m| m.remove_temp::(id.with(OWN_ROWS_KEY))).unwrap_or(false); + ctx.data_mut(|m| m.insert_temp(id.with(OWN_BEFORE_KEY), own)); + let room = whole_room(ctx, margin); + let screen = ctx.content_rect().height() - 2.0 * super::EDGE_GAP; + let tall = match (rows, body) { + (Some(rows), Some(body)) if !own => height - rows + body > screen + 0.5, + _ => false, + }; + // A window that fits itself to the screen's height can still be too wide for it. + let whole = [contents.x > room.x + 0.5, !own && rows.is_none() && contents.y > room.y + 0.5]; + let was_tall = ctx.data_mut(|m| std::mem::replace(m.get_temp_mut_or(id.with(TALL_KEY), false), tall)); + let was_whole = ctx.data_mut(|m| std::mem::replace(m.get_temp_mut_or(id.with(WHOLE_KEY), [false; 2]), whole)); + let mut repaint = tall != was_tall || whole != was_whole; + if let Some(rows) = rows { + let rest = (height - rows).max(0.0); + let used = ctx.data_mut(|m| std::mem::replace(m.get_temp_mut_or(id.with(REST_KEY), 0.0), rest)); + repaint |= (used - rest).abs() > 0.5; + } + if repaint { ctx.request_repaint(); } } @@ -159,4 +370,159 @@ mod tests { // Larger than the screen: its top left stays in view. assert_eq!(on_screen(r(-10.0, -10.0, 900.0, 700.0), screen), r(0.0, 0.0, 900.0, 700.0)); } + + /// Draw `frames` frames of a 400×300 screen from `time`, the first with `events`, with the modal + /// windows named in `open` open, in that order: the first a heading and 60 rows, in + /// [`scrolled_rows`] when `in_rows`, and any other a short alert. A window named "over …" is + /// opened over the one before it ([`over_parent`]). Returns whether a first row could be seen in + /// the last frame (inside the screen and its clip). + fn first_row_seen(ctx: &egui::Context, open: &[&str], in_rows: bool, events: Vec, time: &mut f64, frames: usize) -> bool { + let screen = Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(400.0, 300.0)); + let add = |ui: &mut egui::Ui| { + for i in 0..60 { + ui.label(format!("Row {i}")); + } + }; + let mut events = Some(events); + let mut seen = false; + for _ in 0..frames { + *time += 1.0 / 60.0; + let input = + egui::RawInput { screen_rect: Some(screen), events: events.take().unwrap_or_default(), time: Some(*time), ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| { + for (i, &name) in open.iter().enumerate() { + if name.starts_with("over ") { + over_parent(ui.ctx()); + } + show(ui.ctx(), name, Id::unique(("modal-reopen-test", name)), 0.0, 8, |ui| { + heading(ui, "Top"); + if i > 0 { + ui.label("Alert"); + } else if in_rows { + scrolled_rows(ui, "rows", add); + } else { + add(ui); + } + }); + } + }); + out.textures_delta.clear(); + seen = out.shapes.iter().any(|c| match &c.shape { + egui::Shape::Text(t) => { + let r = t.visual_bounding_rect(); + t.galley.text() == "Row 0" && screen.contains_rect(r) && c.clip_rect.contains_rect(r) + } + _ => false, + }); + } + seen + } + + /// A wheel turn far down, at the middle of the 400×300 screen. + fn wheel_down() -> Vec { + let wheel = egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: egui::vec2(0.0, -3000.0), + phase: egui::TouchPhase::Move, + source: egui::MouseWheelSource::Unknown, + modifiers: egui::Modifiers::NONE, + }; + vec![egui::Event::PointerMoved(egui::pos2(200.0, 200.0)), wheel] + } + + #[test] + fn a_window_that_scrolled_opens_again_at_its_top() { + for in_rows in [false, true] { + let ctx = egui::Context::default(); + crate::theme::apply(&ctx, Default::default()); + let mut time = 0.0; + assert!(first_row_seen(&ctx, &["A"], in_rows, vec![], &mut time, 4), "rows {in_rows}: the window opens at its top"); + assert!(!first_row_seen(&ctx, &["A"], in_rows, wheel_down(), &mut time, 60), "rows {in_rows}: the wheel scrolls the first row away"); + first_row_seen(&ctx, &[], in_rows, vec![], &mut time, 2); + assert!(first_row_seen(&ctx, &["A"], in_rows, vec![], &mut time, 4), "rows {in_rows}: opened again, the window starts at its top"); + } + } + + #[test] + fn a_window_hidden_under_one_opened_over_it_keeps_its_scroll() { + // As Keyboard Shortcuts is while Import Shortcut Set is open over it: it is not drawn, but it + // did not close. A window that another replaced did close. Either may have shown an alert + // of its own, drawn after it in the same passes. + let others: [(&[&str], bool); 4] = [(&["over B"], true), (&["over B", "Alert"], true), (&["C"], false), (&["C", "Alert"], false)]; + let mut wrong = vec![]; + for in_rows in [false, true] { + for (other, kept) in others { + let ctx = egui::Context::default(); + crate::theme::apply(&ctx, Default::default()); + let mut time = 0.0; + first_row_seen(&ctx, &["A"], in_rows, vec![], &mut time, 4); + if first_row_seen(&ctx, &["A"], in_rows, wheel_down(), &mut time, 60) { + wrong.push(format!("rows {in_rows}: the wheel does not scroll A")); + } + if !first_row_seen(&ctx, other, in_rows, vec![], &mut time, 4) { + wrong.push(format!("rows {in_rows}: {other:?} does not open at its top")); + } + if first_row_seen(&ctx, &["A"], in_rows, vec![], &mut time, 4) == kept { + wrong.push(format!("rows {in_rows}: after {other:?}, A {} where it was scrolled to", if kept { "is not" } else { "is still" })); + } + } + } + assert!(wrong.is_empty(), "{wrong:#?}"); + } + + #[test] + fn a_field_keeps_its_text_and_focus_when_the_window_starts_or_stops_scrolling() { + // A field's edit state and the keyboard focus are kept under its id, so typing goes on into + // the same field when the screen's height changes whether the body or the window scrolls. + let mut wrong = vec![]; + for in_body in [false, true] { + let ctx = egui::Context::default(); + crate::theme::apply(&ctx, Default::default()); + let window = Id::unique("modal-field-id-test"); + let mut text = String::from("12"); + let mut time = 0.0; + let mut field = None; + let mut focus_given = false; + let mut seen = vec![]; + for (height, typed) in [(900.0, "3"), (300.0, "4"), (900.0, "5")] { + let screen = Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(400.0, height)); + for i in 0..4 { + time += 1.0 / 60.0; + // Typed once the window has settled at this height. + let events = if i == 3 { vec![egui::Event::Text(typed.into())] } else { vec![] }; + let input = egui::RawInput { screen_rect: Some(screen), events, time: Some(time), ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| { + show(ui.ctx(), "Test", window, 0.0, 8, |ui| { + heading(ui, "Top"); + let mut add = |ui: &mut egui::Ui| { + let r = ui.text_edit_singleline(&mut text); + for i in 0..30 { + ui.label(format!("Row {i}")); + } + r.id + }; + field = Some(if in_body { body_rows(ui, add) } else { add(ui) }); + }); + }); + out.textures_delta.clear(); + // The field is given the focus once, after the first frame; a resize that took it + // away would leave the keys typed after it untaken. + if let Some(id) = field.filter(|_| !focus_given) { + ctx.memory_mut(|m| m.request_focus(id)); + focus_given = true; + } + } + let key = if in_body { window.with(TALL_KEY) } else { window.with(WHOLE_KEY) }; + let scrolls = ctx.data(|m| m.get_temp::(key).unwrap_or(false) || m.get_temp::<[bool; 2]>(key).is_some_and(|a| a[1])); + seen.push((scrolls, text.clone(), ctx.memory(|m| m.focused()) == field && field.is_some())); + } + let want = [(false, "123", true), (true, "1234", true), (false, "12345", true)]; + let want: Vec<_> = want.iter().map(|&(s, t, f)| (s, t.to_string(), f)).collect(); + if seen != want { + wrong.push((in_body, seen)); + } + } + // Only the short screen scrolls, and the field keeps its focus and takes each key. + assert_eq!(wrong, vec![], "(body, [(scrolls, text, focused)]) that went wrong"); + } } diff --git a/crates/ui-egui/src/dialogs/para_style_options.rs b/crates/ui-egui/src/dialogs/para_style_options.rs index 9a9da0c164..b64815b8dd 100644 --- a/crates/ui-egui/src/dialogs/para_style_options.rs +++ b/crates/ui-egui/src/dialogs/para_style_options.rs @@ -982,6 +982,7 @@ fn content_id(ui: &egui::Ui) -> egui::Id { /// (as drawn last frame). The section list stays put while the content scrolls. Returns whether /// the dialog asks to be canceled (never: Cancel comes from the button row in `dialogs::show`). fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { + super::modal::fits_itself(ui); let window = ui.ctx().memory(|m| m.area_rect(ui.layer_id().id)).map_or(0.0, |r| r.height()); let content = ui.ctx().data(|m| m.get_temp::(content_id(ui))).unwrap_or(0.0); let rest = (window - content).max(0.0); diff --git a/crates/ui-egui/src/dialogs/print.rs b/crates/ui-egui/src/dialogs/print.rs index ebaad1749a..dd8db94418 100644 --- a/crates/ui-egui/src/dialogs/print.rs +++ b/crates/ui-egui/src/dialogs/print.rs @@ -251,7 +251,8 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { ui.vertical(|ui| { ui.set_width(500.0); ui.label(egui::RichText::new(tl!(section)).font(theme::semibold(14.0)).color(t.text_strong)); - egui::ScrollArea::vertical().id_salt(("print", section)).max_height(360.0).auto_shrink([false, false]).show(ui, |ui| match section { + let list_h = super::modal::list_height(ui, 360.0); + egui::ScrollArea::vertical().id_salt(("print", section)).max_height(list_h).auto_shrink([false, false]).show(ui, |ui| match section { "Marks and Bleed" => super::save_pdf::marks_and_bleeds(app, ui, d), "Output" => output(ui, d, &preview), "Graphics" => graphics(ui, d), diff --git a/crates/ui-egui/src/dialogs/save_for_web.rs b/crates/ui-egui/src/dialogs/save_for_web.rs index 589d1dfdce..c412bc2dcb 100644 --- a/crates/ui-egui/src/dialogs/save_for_web.rs +++ b/crates/ui-egui/src/dialogs/save_for_web.rs @@ -2,13 +2,16 @@ //! as the web image Save writes, beside the original (Original, Optimized, 2-Up and 4-Up views, //! each with its file size and download time), and the settings: format (GIF, JPEG, PNG-8, //! PNG-24), colour reduction, colours, dither, transparency and matte, interlacing, web snap, -//! lossy, JPEG quality, the colour table (lock, map to transparent, web shift, sort), image size -//! and anti-aliasing, Clip to Artboard, sRGB, metadata, slices and HTML output, and presets. +//! lossy, JPEG quality, the colour table (lock, map to transparent, web shift, sort, Delete Color +//! and Restore Generated Table), image size and anti-aliasing, Clip to Artboard, sRGB, metadata, +//! slices and HTML output, and presets. //! //! Fields are the `document.exportForWeb` settings (`webExport.settings` gives them; set one with //! `ui.dialog.set`, or `preset` to load a preset), plus the dialog's own: `__view` (`original`, //! `optimized`, `2up`, `4up`), `__zoom` (`fit` or a percentage), `__kbps` (connection speed), -//! `__color` (the colour table's selected colour, by source), `__presetName` (shown while saving a +//! `__color` (the colour table's selected colour, by source: the one Lock, Transparent and Web +//! Shift edit, and where a Shift-click range starts), `__colors` (every selected color, by source, +//! which Delete Color deletes; when it is empty, `__color` alone), `__presetName` (shown while saving a //! preset) and `__hasSlices`. Optimize to File Size… (`__optimizeOpen: true`) shows `__optimizeK` (the desired size in K), //! `__optimizeStart` (`current`, `auto`) and with slices `__optimizeUse` (`allSlices`, //! `eachSlice`, `currentSlice`); `__optimizeGo: true` runs `webExport.optimizeToFileSize` and @@ -52,6 +55,8 @@ pub(super) const SPEC: DialogSpec = DialogSpec { /// The preview area (panes and their captions) and the settings column. const PREVIEW_W: f32 = 620.0; +/// The narrowest the panes get in a narrow window. +const MIN_PREVIEW_W: f32 = 240.0; const PREVIEW_H: f32 = 470.0; const SIDE_W: f32 = 296.0; const GAP: f32 = 16.0; @@ -107,10 +112,10 @@ fn remembered(app: &VectorcraftApp) -> WebSettings { /// Reset (Cancel with Alt or Option held, or `ui.dialogReset`): the settings go back to the /// remembered ones on the document's active artboard ([`remembered`]), and a pending `preset`, a /// pending Done (`discard`, which a failed Done leaves), the preset name being typed and the -/// selected color table entry are dropped. The view, zoom, connection speed and `path` stay, +/// selected color table entries are dropped. The view, zoom, connection speed and `path` stay, /// nothing is remembered or written, and the dialog stays open. fn reset(app: &VectorcraftApp, d: &mut Dialog) -> Result<(), String> { - for key in ["preset", "discard", "__presetName", "__color"] { + for key in ["preset", "discard", "__presetName", "__color", "__colors"] { d.fields.remove(key); } d.fields.extend(settings_fields(&remembered(app))); @@ -532,10 +537,19 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { } let settings = settings_of(app, d); let mut browser = false; - ui.horizontal_top(|ui| { + // In a window too narrow for both, the panes are narrower, so the settings beside them and the + // buttons below stay in view. The room is the screen's (the window's own width follows what it + // drew last), less a column for the bar of the body while it scrolls; the settings column is as + // wide as it was drawn last. + let bar = if super::modal::body_view(ui).is_some() { ui.spacing().scroll.allocated_width() } else { 0.0 }; + let room = ui.ctx().content_rect().width() - 2.0 * (f32::from(super::MARGIN) + super::EDGE_GAP) - bar; + let rest_id = egui::Id::unique("save-for-web-beside-panes"); + let rest = ui.ctx().data(|m| m.get_temp::(rest_id)).unwrap_or(ui.spacing().item_spacing.x + GAP + SIDE_W); + let preview_w = (room.min(ui.available_width()) - rest).clamp(MIN_PREVIEW_W, PREVIEW_W); + let row = ui.horizontal_top(|ui| { ui.vertical(|ui| { - ui.set_width(PREVIEW_W); - browser = preview_area(app, ui, d, &settings); + ui.set_width(preview_w); + browser = preview_area(app, ui, d, &settings, preview_w); }); ui.add_space(GAP); ui.vertical(|ui| { @@ -543,6 +557,10 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { side(app, ui, d, settings.as_ref().ok()); }); }); + let drawn = row.response.rect.width() - preview_w; + if (ui.ctx().data_mut(|m| std::mem::replace(m.get_temp_mut_or(rest_id, rest), drawn)) - drawn).abs() > 0.5 { + ui.ctx().request_repaint(); + } optimize_on_enter(ui.ctx(), d); if browser && let Err(e) = app.run("file.saveForWeb.browser", params(d)) { app.status(e); @@ -550,16 +568,16 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { false } -/// The view tabs, the panes and the zoom and speed row. Returns whether Preview in Browser was -/// clicked. -fn preview_area(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, settings: &Result) -> bool { +/// The view tabs, the panes (`width` wide) and the zoom and speed row. Returns whether Preview in +/// Browser was clicked. +fn preview_area(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, settings: &Result, width: f32) -> bool { let t = Tokens::get(ui.ctx()); let view = VIEWS.iter().position(|v| *v == d.str("__view")).unwrap_or(2); if let Some(i) = widgets::tab_bar(ui, &VIEW_LABELS, view) { d.fields.insert("__view".into(), json!(VIEWS[i])); } ui.add_space(4.0); - let (area, resp) = ui.allocate_exact_size(egui::vec2(PREVIEW_W, PREVIEW_H), egui::Sense::click_and_drag()); + let (area, resp) = ui.allocate_exact_size(egui::vec2(width, PREVIEW_H), egui::Sense::click_and_drag()); let pan_id = egui::Id::unique("save-for-web-pan"); let mut pan: egui::Vec2 = ui.ctx().data(|m| m.get_temp(pan_id)).unwrap_or_default(); if resp.dragged() { @@ -604,6 +622,17 @@ fn preview_area(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, set } ui.add_space(6.0); let mut browser = false; + // Preview in Browser goes on a row of its own when the panes are too narrow for it beside the + // two lists (its width as `widgets::secondary_button` draws it). + let label = tl!("Preview in Browser"); + let button_w = (ui.painter().layout_no_wrap(label.to_string(), crate::theme::semibold(12.5), t.text).size().x + 32.0).max(72.0); + let mut beside = false; + let mut button = |ui: &mut egui::Ui| { + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + let b = ui.add_enabled(!io::is_web(app), |ui: &mut egui::Ui| widgets::secondary_button(ui, label)); + browser = b.on_disabled_hover_text(tl!("Needs the desktop app")).clicked(); + }); + }; ui.horizontal(|ui| { let z = ZOOMS.iter().position(|z| *z == d.str("__zoom")).unwrap_or(2); let zoom = ui.name_inputs(tl!("Zoom"), |ui| widgets::dropdown(ui, "sfw-zoom", ZOOM_LABELS[z], &ZOOM_LABELS, 110.0)); @@ -620,11 +649,15 @@ fn preview_area(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, set { d.fields.insert("__kbps".into(), json!(s)); } - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - let b = ui.add_enabled(!io::is_web(app), |ui: &mut egui::Ui| widgets::secondary_button(ui, tl!("Preview in Browser"))); - browser = b.on_disabled_hover_text(tl!("Needs the desktop app")).clicked(); - }); + beside = ui.available_width() >= button_w; + if beside { + button(ui); + } }); + if !beside { + ui.add_space(4.0); + ui.horizontal(button); + } browser } @@ -729,7 +762,8 @@ fn side(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, s: Option<& presets_row(app, ui, d, s); optimize_rows(ui, d, s, &art_key(app)); widgets::divider(ui); - egui::ScrollArea::vertical().id_salt("sfw-settings").max_height(PREVIEW_H - 40.0).auto_shrink([false, true]).show(ui, |ui| { + let list_h = super::modal::list_height(ui, PREVIEW_H - 40.0); + egui::ScrollArea::vertical().id_salt("sfw-settings").max_height(list_h).auto_shrink([false, true]).show(ui, |ui| { let choice = |ui: &mut egui::Ui, d: &mut Dialog, key: &str, label: &str, options: &[(&str, &str)]| { form::choice(ui, d, key, label, (LABEL_W, FIELD_W), options); }; @@ -737,7 +771,12 @@ fn side(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, s: Option<& let format = s.map_or(WebFormat::Gif, |s| s.format); match format { WebFormat::Gif | WebFormat::Png8 => { + let reduction = d.str("reduction"); choice(ui, d, "reduction", tl!("Reduction:"), &pairs(&Reduction::ALL, Reduction::id, Reduction::label)); + // Another reduction makes a new palette. + if d.str("reduction") != reduction { + restore_table(d); + } colors_row(ui, d); choice(ui, d, "dither", tl!("Dither:"), &pairs(&Dither::ALL, Dither::id, Dither::label)); if Dither::from_id(&d.str("dither")).is_some_and(|x| x != Dither::None) { @@ -765,7 +804,9 @@ fn side(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog, s: Option<& choice(ui, d, "metadata", tl!("Metadata:"), &pairs(&WebMetadata::ALL, WebMetadata::key, WebMetadata::label)); if format.palette() { widgets::divider(ui); - color_table(ui, d, s); + if let Err(e) = color_table(ui, d, s) { + app.status(e); + } } widgets::divider(ui); image_size(app, ui, d, s); @@ -1043,10 +1084,13 @@ fn matte_row(ui: &mut egui::Ui, d: &mut Dialog) { }); } -/// The colour table of the current settings' preview: swatches (the selected one ringed; locked -/// ones with a square, web-safe ones with a diamond, transparent ones over the grid) and the -/// buttons that edit the selected colour, plus the sort order. -fn color_table(ui: &mut egui::Ui, d: &mut Dialog, s: Option<&WebSettings>) { +/// The colour table of the current settings' preview: swatches (the selected ones ringed; locked +/// ones with a square, web-safe ones with a diamond, transparent ones over the grid), the buttons +/// that edit the selected colour, Delete Color and the table's menu, plus the sort order. A click +/// selects one color, a Shift-click the colors from the anchor, and a Ctrl-click +/// (Command-click on macOS) adds or removes one. Returns an error for a deletion that would leave +/// no color. +fn color_table(ui: &mut egui::Ui, d: &mut Dialog, s: Option<&WebSettings>) -> Result<(), String> { let t = Tokens::get(ui.ctx()); let cache: Option = ui.ctx().data(|m| m.get_temp(cache_id())); let key = s.map(|s| s.to_json().to_string()); @@ -1054,10 +1098,20 @@ fn color_table(ui: &mut egui::Ui, d: &mut Dialog, s: Option<&WebSettings>) { let Some(shot) = shot else { widgets::subheader(ui, tl!("Color Table")); widgets::dim_label(ui, tl!("Shown with the optimised preview.")); - return; + // A Custom table the preview can't use (a deletion that left only colors mapped to + // transparent) can still go back to the generated palette. + if s.is_some_and(|s| s.color_table.is_custom()) && widgets::flat_button_fit(ui, tl!("Restore Generated Table"), 88.0).clicked() { + restore_table(d); + } + return Ok(()); }; + let table = s.map(|s| s.color_table.clone()).unwrap_or_default(); widgets::subheader(ui, &crate::i18n::tn(shot.colors.len() as u64, "Color Table ({n} color)", "Color Table ({n} colors)")); + if table.is_custom() { + widgets::dim_label(ui, tl!("Custom")); + } let selected = d.str("__color"); + let picked = selection(d); // (colour shown, source, transparent, locked, web-safe, mapped by hand) let rows: Vec<(TableColor, bool)> = shot .colors @@ -1069,6 +1123,9 @@ fn color_table(ui: &mut egui::Ui, d: &mut Dialog, s: Option<&WebSettings>) { let per_row = ((SIDE_W - 8.0) / (CELL + 2.0)).floor().max(1.0) as usize; let lines = rows.len().div_ceil(per_row).max(1); let (area, resp) = ui.allocate_exact_size(egui::vec2(SIDE_W - 8.0, lines as f32 * (CELL + 2.0)), egui::Sense::click()); + // The colors that can be selected, in table order (for Shift-click ranges). + let order: Vec = rows.iter().filter(|(c, mapped)| !c.transparent || *mapped).map(|(c, _)| hex(c.source)).collect(); + let mut clicked = None; let p = ui.painter(); for (i, (c, mapped)) in rows.iter().enumerate() { let r = egui::Rect::from_min_size( @@ -1102,14 +1159,17 @@ fn color_table(ui: &mut egui::Ui, d: &mut Dialog, s: Option<&WebSettings>) { } // The transparent entry itself isn't a colour to edit. let pickable = !c.transparent || *mapped; - let picked = pickable && hex(c.source) == selected; - p.rect_stroke(r, 0.0, egui::Stroke::new(if picked { 2.0 } else { 1.0 }, if picked { t.accent } else { t.border }), egui::StrokeKind::Outside); + let ringed = pickable && picked.iter().any(|h| h.eq_ignore_ascii_case(&hex(c.source))); + p.rect_stroke(r, 0.0, egui::Stroke::new(if ringed { 2.0 } else { 1.0 }, if ringed { t.accent } else { t.border }), egui::StrokeKind::Outside); if pickable && resp.clicked() && resp.interact_pointer_pos().is_some_and(|pos| r.contains(pos)) { - d.fields.insert("__color".into(), json!(hex(c.source))); + clicked = Some(hex(c.source)); } } + if let Some(c) = clicked { + let m = ui.input(|i| i.modifiers); + pick(d, &order, &c, m.shift, m.command); + } ui.add_space(4.0); - let table = s.map(|s| s.color_table.clone()).unwrap_or_default(); let on = |list: &[String]| list.iter().any(|h| h.eq_ignore_ascii_case(&selected)); ui.horizontal(|ui| { ui.add_enabled_ui(!selected.is_empty(), |ui| { @@ -1130,6 +1190,23 @@ fn color_table(ui: &mut egui::Ui, d: &mut Dialog, s: Option<&WebSettings>) { } }); }); + // Delete Color (the button and the table's menu) and Restore Generated Table. + let (mut delete, mut restore) = (false, false); + ui.horizontal(|ui| { + delete |= widgets::icon_button_enabled(ui, "trash-2", tl!("Delete Color"), false, !picked.is_empty(), 24.0).clicked(); + let menu = widgets::icon_button(ui, "menu", tl!("Color Table"), false, 24.0); + let open = menu.clicked(); + let _ = widgets::popover(&menu, open, |ui| { + if widgets::menu_item(ui, tl!("Delete Color"), !picked.is_empty(), false) { + delete = true; + ui.close(); + } + if widgets::menu_item(ui, tl!("Restore Generated Table"), table.is_custom(), false) { + restore = true; + ui.close(); + } + }); + }); let sort = table.sort; widgets::label_row(ui, tl!("Order:"), LABEL_W, |ui| { let labels = ColorSort::ALL.map(ColorSort::label); @@ -1139,6 +1216,118 @@ fn color_table(ui: &mut egui::Ui, d: &mut Dialog, s: Option<&WebSettings>) { set_table(d, "sort", json!(o.id())); } }); + if restore { + restore_table(d); + } + if delete { + let palette: Vec = + shot.colors.iter().filter(|c| !c.transparent).map(|c| hex(c.source)).chain(shot.mapped.iter().map(|c| hex(*c))).collect(); + delete_colors(d, &palette)?; + } + Ok(()) +} + +/// The colour table's selected colors, by source: `__colors`, else `__color`. +pub(super) fn selection(d: &Dialog) -> Vec { + let many: Vec = + d.fields.get("__colors").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str).map(str::to_ascii_lowercase).collect(); + if !many.is_empty() { + return many; + } + let one = d.str("__color"); + if one.is_empty() { vec![] } else { vec![one.to_ascii_lowercase()] } +} + +/// A click on the table's color `color`: it alone is selected and becomes the anchor (`__color`); +/// with `shift`, the colors from the anchor to it in table order (`order`), the anchor unchanged; +/// with `command` (Ctrl, or Command on macOS), it is added to the selection and becomes the anchor, +/// or taken out, and the anchor moves to the last color left in the selection. +pub(super) fn pick(d: &mut Dialog, order: &[String], color: &str, shift: bool, command: bool) { + let color = color.to_ascii_lowercase(); + let at = |c: &str| order.iter().position(|o| o.eq_ignore_ascii_case(c)); + if shift && let (Some(a), Some(b)) = (at(&d.str("__color")), at(&color)) { + let range: Vec = order[a.min(b)..=a.max(b)].iter().map(|c| c.to_ascii_lowercase()).collect(); + d.fields.insert("__colors".into(), json!(range)); + return; + } + let mut set = selection(d); + let anchor = if command { + match set.iter().position(|c| *c == color) { + Some(i) => { + set.remove(i); + set.last().cloned() + } + None => { + set.push(color.clone()); + Some(color) + } + } + } else { + set = vec![color.clone()]; + Some(color) + }; + d.fields.insert("__colors".into(), json!(set)); + match anchor { + Some(c) => d.fields.insert("__color".into(), json!(c)), + None => d.fields.remove("__color"), + }; +} + +/// Delete Color: the selected colors join the color table's `deleted` list and leave its other +/// lists. The first deletion fixes the palette (`customPalette`) to `palette`, the table's colors +/// (by source) with the deleted ones, so the colors left do not change. A deletion that leaves no +/// color, or only colors mapped to transparent, is refused with nothing changed. The selection is +/// cleared. +pub(super) fn delete_colors(d: &mut Dialog, palette: &[String]) -> Result<(), String> { + let picked = selection(d); + if picked.is_empty() { + return Ok(()); + } + let list = |d: &Dialog, key: &str| -> Vec { + d.fields + .get("colorTable") + .and_then(|t| t.get(key)) + .and_then(Value::as_array) + .into_iter() + .flatten() + .filter_map(Value::as_str) + .map(str::to_ascii_lowercase) + .collect() + }; + let mut custom = list(d, "customPalette"); + if custom.is_empty() { + custom = palette.iter().map(|c| c.to_ascii_lowercase()).collect(); + } + let mut deleted = list(d, "deleted"); + for c in &picked { + if !deleted.contains(c) { + deleted.push(c.clone()); + } + } + // A color has to stay that is neither deleted nor mapped to transparent. + let clear: Vec = list(d, "transparent").into_iter().filter(|c| !picked.contains(c)).collect(); + if custom.iter().all(|c| deleted.contains(c) || clear.contains(c)) { + return Err(webexport::KEEP_ONE.into()); + } + for key in ["locked", "transparent", "webShift"] { + if list(d, key).iter().any(|c| picked.contains(c)) { + for c in &picked { + toggle(d, key, c, false); + } + } + } + set_table(d, "customPalette", json!(custom)); + set_table(d, "deleted", json!(deleted)); + d.fields.remove("__colors"); + d.fields.remove("__color"); + Ok(()) +} + +/// Restore Generated Table: no deleted colors and no fixed palette; the reduction makes the +/// palette again. +pub(super) fn restore_table(d: &mut Dialog) { + set_table(d, "deleted", json!([])); + set_table(d, "customPalette", json!([])); } /// Add `color` to the colour table's `list`, or take it out. diff --git a/crates/ui-egui/src/dialogs/save_pdf.rs b/crates/ui-egui/src/dialogs/save_pdf.rs index cb515c8944..edfb66e7f4 100644 --- a/crates/ui-egui/src/dialogs/save_pdf.rs +++ b/crates/ui-egui/src/dialogs/save_pdf.rs @@ -429,7 +429,8 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { ui.vertical(|ui| { ui.set_width(500.0); ui.label(egui::RichText::new(tl!(section)).font(theme::semibold(14.0)).color(t.text_strong)); - egui::ScrollArea::vertical().id_salt(("save-pdf", section)).max_height(360.0).auto_shrink([false, false]).show(ui, |ui| match section { + let list_h = super::modal::list_height(ui, 360.0); + egui::ScrollArea::vertical().id_salt(("save-pdf", section)).max_height(list_h).auto_shrink([false, false]).show(ui, |ui| match section { "Compression" => compression(ui, d), "Marks and Bleeds" => marks_and_bleeds(app, ui, d), "Output" => output(ui, d), diff --git a/crates/ui-egui/src/dialogs/shortcut_import.rs b/crates/ui-egui/src/dialogs/shortcut_import.rs index 0516695233..e6c9a6ee0a 100644 --- a/crates/ui-egui/src/dialogs/shortcut_import.rs +++ b/crates/ui-egui/src/dialogs/shortcut_import.rs @@ -670,6 +670,7 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { let (keys_h, rows_h) = list_heights(ctx.content_rect().height() - rest, keys_open); let (mut apply, mut cancel, mut copy, mut lists) = (false, false, false, 0.0); crate::dialogs::modal::show(ctx, tl!("Import Shortcut Set"), id, -20.0, 20, |ui| { + crate::dialogs::modal::fits_itself(ui); ui.set_width(NAME_W + TARGET_W + CHORD_W + 220.0); crate::dialogs::modal::heading(ui, tl!("Import Shortcut Set")); ui.add_space(10.0); diff --git a/crates/ui-egui/src/dialogs/symbol_options.rs b/crates/ui-egui/src/dialogs/symbol_options.rs index 146e02c6eb..9d73ad769d 100644 --- a/crates/ui-egui/src/dialogs/symbol_options.rs +++ b/crates/ui-egui/src/dialogs/symbol_options.rs @@ -8,7 +8,8 @@ //! `exportType` (`movieClip` | `graphic`), `type` (`dynamic` | //! `static`; a new symbol is dynamic), `registration` (0..8, the 9-point grid; //! 4 = centre), `alignToPixelGrid` (bool, off for a new symbol), `__edit` (true when editing an -//! existing symbol). Help: +//! existing symbol), `__keepArt` (true when a new symbol leaves the selection as ordinary art). +//! Help: //! . use serde_json::{Map, Value, json}; @@ -69,15 +70,23 @@ const EXPORT_TYPES: [(&str, &str); 2] = [("movieClip", "Movie Clip"), ("graphic" pub(super) const SPEC: DialogSpec = DialogSpec { heading: |_| tl!("Symbol Options").into(), body, confirm, min_width: 320.0, ..DialogSpec::FORM }; -/// Open Symbol Options to name a new symbol made from the selection. -pub fn open(app: &mut VectorcraftApp) -> Result { +/// Open Symbol Options to name a new symbol made from the selection. With `keep_art`, OK leaves +/// the selection as ordinary art instead of replacing it with an instance. +pub fn open(app: &mut VectorcraftApp, keep_art: bool) -> Result { let st = app.session.active().ok_or("no document open")?; if st.selection.is_empty() { return Err("nothing selected".into()); } let name = st.doc.unique_symbol_name("New Symbol"); - let mut fields = - json!({ "name": name, "exportType": "movieClip", "type": "dynamic", "registration": 4, "alignToPixelGrid": false, "__edit": false }); + let mut fields = json!({ + "name": name, + "exportType": "movieClip", + "type": "dynamic", + "registration": 4, + "alignToPixelGrid": false, + "__edit": false, + "__keepArt": keep_art, + }); if let Some(o) = fields.as_object_mut() { o.extend(slice_fields(None)); } @@ -193,6 +202,9 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { } else { let mut params = json!({ "name": name, "exportType": export, "type": kind, "registration": registration, "alignToPixelGrid": pixel }); merge(&mut params, slice_params(d)); + if d.bool("__keepArt") { + params["keepArt"] = json!(true); + } app.run("symbol.new", params) }; if r.is_ok() { diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index dec8b5853c..0a9e32a385 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -2890,6 +2890,61 @@ fn the_blob_brush_tip_preview_is_a_named_slider_with_arrow_keys() { assert_eq!(angle(&app), -44.0, "the drag gives the preview the focus"); } +/// A drag that starts on a black dot of the Blob Brush tip preview sets the Roundness from the +/// pointer's distance from the center along the tip's short axis, leaves the Angle as it is, goes +/// on past the square's edge (stopping at 100%), and gives the Roundness slider the focus, whose +/// keys step the Roundness by 1% (10% with Shift) within 0% to 100%. A drag that starts anywhere +/// else sets only the Angle, and Tab goes from the Angle slider to the Roundness slider. +#[test] +fn a_drag_on_a_blob_brush_tip_dot_sets_the_roundness() { + use egui::Key::{ArrowDown, ArrowRight, ArrowUp, End, Home, Tab}; + use egui::Modifiers as M; + let mut app = app(); + app.run("tool.options", json!({"tool": "blobBrush"})).unwrap(); + let values = |app: &VectorcraftApp| { + let d = app.ui.dialog.as_ref().expect("Blob Brush Tool Options is open"); + (d.f64("angle", f64::NAN), d.f64("roundness", f64::NAN)) + }; + let mut f = Frames::new(); + f.run(&mut app, vec![]); + let out = f.run(&mut app, vec![]); + let (_, value, text) = slider_node(&out, "Roundness"); + assert_eq!((value, text.as_deref()), (Some(100.0), Some("100%"))); + let center = f.control(&mut app, "Roundness", egui::accesskit::Role::Slider); + // At 0° the dots are straight above and below the center, 18 pt from it at 100%. A click + // pressed 6 pt from the upper dot and released 11 pt from it in the same frame takes the dot. + let (down, up) = (center + egui::vec2(0.0, -12.0), center + egui::vec2(0.0, -7.0)); + let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: M::NONE }; + f.run(&mut app, vec![egui::Event::PointerMoved(down), button(down, true), egui::Event::PointerMoved(up), button(up, false)]); + assert_eq!(values(&app), (0.0, 39.0), "a click that starts on the upper dot"); + f.drag(&mut app, center + egui::vec2(0.0, -7.0), egui::vec2(1.0, -11.0)); + assert_eq!(values(&app), (0.0, 100.0), "the upper dot dragged out to the tip's length"); + f.drag(&mut app, center + egui::vec2(0.0, -18.0), egui::vec2(1.0, 9.0)); + assert_eq!(values(&app), (0.0, 50.0), "the upper dot dragged half way to the center"); + f.drag(&mut app, center + egui::vec2(0.0, 9.0), egui::vec2(3.0, 60.0)); + assert_eq!(values(&app), (0.0, 100.0), "the lower dot dragged out of the square"); + f.drag(&mut app, center + egui::vec2(0.0, 18.0), egui::vec2(0.0, -18.0)); + assert_eq!(values(&app), (0.0, 0.0), "the lower dot dragged to the center"); + let mut seen = vec![]; + for (key, mods, want) in + [(ArrowUp, M::NONE, 1.0), (ArrowRight, M::SHIFT, 11.0), (ArrowDown, M::NONE, 10.0), (End, M::NONE, 100.0), (Home, M::NONE, 0.0)] + { + f.key(&mut app, key, mods); + seen.push((key, mods.shift, values(&app))); + assert_eq!(values(&app), (0.0, want), "{seen:?}"); + } + let out = f.run(&mut app, vec![]); + assert_eq!(slider_node(&out, "Roundness").2.as_deref(), Some("0%")); + // With a 0% tip the dots are at the center; a drag that starts away from them sets the Angle. + f.drag(&mut app, center + egui::vec2(20.0, 0.0), egui::vec2(0.0, -20.0)); + assert_eq!(values(&app), (45.0, 0.0), "the drag ends up to the right"); + f.key(&mut app, ArrowRight, M::NONE); + assert_eq!(values(&app), (46.0, 0.0), "the drag gives the Angle slider the focus"); + f.key(&mut app, Tab, M::NONE); + f.key(&mut app, ArrowUp, M::NONE); + assert_eq!(values(&app), (46.0, 1.0), "Tab goes on to the Roundness slider"); +} + /// Screen readers can set the Blob Brush tip preview's Angle to a number: the slider offers the /// set-value action, a fraction rounds to the whole degrees the field shows, a number past -180° to /// 180° sets the nearer end, the last request in a frame wins, and a value that is not a finite diff --git a/crates/ui-egui/src/dialogs/tests_print.rs b/crates/ui-egui/src/dialogs/tests_print.rs index cad38bb984..00b45e0db7 100644 --- a/crates/ui-egui/src/dialogs/tests_print.rs +++ b/crates/ui-egui/src/dialogs/tests_print.rs @@ -428,13 +428,17 @@ fn request(action: egui::accesskit::Action, target_node: egui::accesskit::NodeId egui::Event::AccessKitActionRequest(ActionRequest { action, target_node, target_tree: TreeId::ROOT, data: None }) } -/// Type `typed` into Scale W, which shows `shown` (the first field that does, before H), and Tab out. +/// Type `typed` into Scale W, which shows `shown` (the leftmost field that does, before H), and Tab out. fn type_w(screen: &mut Screen, app: &mut VectorcraftApp, shown: &str, typed: &str) { let key = |key, modifiers| egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers }; screen.run(app, vec![]); let out = screen.run(app, vec![]); let nodes = &out.platform_output.accesskit_update.as_ref().expect("an accessibility tree").nodes; - let w = nodes.iter().find(|(_, n)| n.role() == egui::accesskit::Role::TextInput && n.value().is_some_and(|v| v.starts_with(shown))); + // W is left of H on their row (the tree lists its nodes in no particular order). + let w = nodes + .iter() + .filter(|(_, n)| n.role() == egui::accesskit::Role::TextInput && n.value().is_some_and(|v| v.starts_with(shown))) + .min_by(|(_, a), (_, b)| a.bounds().map_or(f64::MAX, |r| r.x0).total_cmp(&b.bounds().map_or(f64::MAX, |r| r.x0))); screen.run(app, vec![request(egui::accesskit::Action::Focus, w.expect("the Scale W field").0)]); screen.run(app, vec![key(egui::Key::A, egui::Modifiers::COMMAND), egui::Event::Text(typed.into())]); screen.run(app, vec![key(egui::Key::Tab, egui::Modifiers::NONE)]); diff --git a/crates/ui-egui/src/dialogs/tests_save_for_web.rs b/crates/ui-egui/src/dialogs/tests_save_for_web.rs index 17c565e454..e27f4b766c 100644 --- a/crates/ui-egui/src/dialogs/tests_save_for_web.rs +++ b/crates/ui-egui/src/dialogs/tests_save_for_web.rs @@ -727,6 +727,141 @@ fn colour_table_buttons_edit_the_lists() { assert_eq!(d.fields["colorTable"], json!({"locked": [], "webShift": ["#123456"], "sort": "hue"})); } +/// A click selects one color, a Shift-click the range from the last one clicked, a Ctrl-click +/// (Command-click) adds or removes one; Delete Color deletes the whole selection in one edit, +/// takes it out of the other lists, fixes the palette and refuses to delete every color. +#[test] +fn colour_table_selection_and_delete_color() { + let mut d = Dialog::new(save_for_web::KIND, json!({})); + let order: Vec = ["#000000", "#111111", "#222222", "#333333"].map(String::from).to_vec(); + let sel = |d: &Dialog| save_for_web::selection(d); + assert!(sel(&d).is_empty()); + save_for_web::pick(&mut d, &order, "#111111", false, false); + assert_eq!(sel(&d), ["#111111"]); + save_for_web::pick(&mut d, &order, "#333333", true, false); + assert_eq!((sel(&d), d.str("__color")), (vec!["#111111".to_string(), "#222222".into(), "#333333".into()], "#111111".into())); + save_for_web::pick(&mut d, &order, "#222222", false, true); + assert_eq!(sel(&d), ["#111111", "#333333"]); + save_for_web::pick(&mut d, &order, "#000000", false, true); + assert_eq!((sel(&d), d.str("__color")), (vec!["#111111".to_string(), "#333333".into(), "#000000".into()], "#000000".into())); + save_for_web::pick(&mut d, &order, "#000000", false, true); + assert_eq!((sel(&d), d.str("__color")), (vec!["#111111".to_string(), "#333333".into()], "#333333".into())); + // A Shift-click back from the anchor. + save_for_web::pick(&mut d, &order, "#222222", false, false); + save_for_web::pick(&mut d, &order, "#000000", true, false); + assert_eq!(sel(&d), ["#000000", "#111111", "#222222"]); + // `__color` alone (an agent's selection) is the selection too. + d.fields.remove("__colors"); + d.fields.insert("__color".into(), json!("#222222")); + assert_eq!(sel(&d), ["#222222"]); + + save_for_web::toggle(&mut d, "locked", "#222222", true); + save_for_web::toggle(&mut d, "locked", "#000000", true); + save_for_web::toggle(&mut d, "webShift", "#333333", true); + save_for_web::pick(&mut d, &order, "#333333", false, true); + save_for_web::delete_colors(&mut d, &order).unwrap(); + assert_eq!(d.fields["colorTable"], json!({"locked": ["#000000"], "webShift": [], "customPalette": order, "deleted": ["#222222", "#333333"]})); + assert!(!d.fields.contains_key("__colors") && !d.fields.contains_key("__color") && sel(&d).is_empty()); + // Nothing selected: nothing deleted. + let before = d.fields.clone(); + save_for_web::delete_colors(&mut d, &order).unwrap(); + assert_eq!(d.fields, before); + // The colors left can't all go: refused, nothing changed. + save_for_web::pick(&mut d, &order, "#000000", false, false); + save_for_web::pick(&mut d, &order, "#111111", false, true); + let before = d.fields.clone(); + assert_eq!(save_for_web::delete_colors(&mut d, &order), Err(vectorcraft_engine::cmd::webexport::KEEP_ONE.to_string())); + assert_eq!(d.fields, before); + // Nor can the last color that is not mapped to transparent. + save_for_web::toggle(&mut d, "transparent", "#111111", true); + save_for_web::pick(&mut d, &order, "#000000", false, false); + let before = d.fields.clone(); + assert_eq!(save_for_web::delete_colors(&mut d, &order), Err(vectorcraft_engine::cmd::webexport::KEEP_ONE.to_string())); + assert_eq!(d.fields, before); + // Restore Generated Table. + save_for_web::restore_table(&mut d); + assert_eq!((&d.fields["colorTable"]["deleted"], &d.fields["colorTable"]["customPalette"]), (&json!([]), &json!([]))); +} + +/// Click the dialog's text `label` with the pointer (frames a quarter second apart). +fn click_text(app: &mut VectorcraftApp, label: &str) { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let frame = |app: &mut VectorcraftApp, events: Vec| { + let time = ctx.input(|i| i.time) + 0.25; + let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 1000.0))); + let raw = egui::RawInput { screen_rect, events, time: Some(time), ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| show(app, ui.ctx())); + out.textures_delta.clear(); + fn walk(s: &egui::Shape, v: &mut Vec<(String, egui::Rect)>) { + match s { + egui::Shape::Text(t) => v.push((t.galley.text().to_string(), egui::Rect::from_min_size(t.pos, t.galley.size()))), + egui::Shape::Vec(s) => s.iter().for_each(|s| walk(s, v)), + _ => {} + } + } + let mut v = vec![]; + out.shapes.iter().for_each(|c| walk(&c.shape, &mut v)); + v + }; + frame(app, vec![]); + let texts = frame(app, vec![]); + let at = texts.iter().find(|(t, _)| t == label).map(|(_, r)| r.center()).unwrap_or_else(|| panic!("no `{label}` in {texts:?}")); + let press = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + frame(app, vec![egui::Event::PointerMoved(at)]); + frame(app, vec![press(true)]); + frame(app, vec![press(false)]); +} + +/// A Custom table whose preview fails (only a color mapped to transparent left) still offers +/// Restore Generated Table, which brings the preview back. +#[test] +fn restore_generated_table_shows_when_the_preview_fails() { + let dir = vectorcraft_testkit::temp_dir("sfw-restore-table"); + let (mut app, _) = app(&dir, false); + app.run("shape.rectangle", json!({"x": 40, "y": 0, "width": 20, "height": 40})).unwrap(); + app.run("paint.setFill", json!({"color": "#0000ff"})).unwrap(); + app.run("file.saveForWeb", json!({})).unwrap(); + let table = json!({"deleted": ["#cc3300"], "customPalette": ["#cc3300", "#0000ff"], "transparent": ["#0000ff"]}); + for (k, v) in [("format", json!("gif")), ("antiAlias", json!("none")), ("dither", json!("none")), ("colorTable", table)] { + set(&mut app, k, v); + } + let p = json!({"format": "gif", "antiAlias": "none", "colorTable": app.ui.dialog.as_ref().unwrap().fields["colorTable"].clone()}); + assert!(app.session.execute("document.exportForWeb.preview", &p).is_err(), "the preview fails"); + click_text(&mut app, "Restore Generated Table"); + let t = &app.ui.dialog.as_ref().unwrap().fields["colorTable"]; + assert_eq!((&t["deleted"], &t["customPalette"]), (&json!([]), &json!([]))); +} + +/// The saved file lacks the deleted color, whose pixels take the color left; the edit is +/// remembered, reopens with the dialog and stays through a format change. +#[test] +fn delete_color_reaches_the_saved_file_and_is_remembered() { + let dir = vectorcraft_testkit::temp_dir("sfw-delete-color"); + let (mut app, _) = app(&dir, false); + app.run("shape.rectangle", json!({"x": 40, "y": 0, "width": 20, "height": 40})).unwrap(); + app.run("paint.setFill", json!({"color": "#0000ff"})).unwrap(); + app.run("file.saveForWeb", json!({})).unwrap(); + for (k, v) in [("format", json!("gif")), ("antiAlias", json!("none")), ("dither", json!("none"))] { + set(&mut app, k, v); + } + frame(&mut app); + set(&mut app, "__colors", json!(["#cc3300"])); + save_for_web::delete_colors(app.ui.dialog.as_mut().unwrap(), &["#cc3300".into(), "#0000ff".into()]).unwrap(); + frame(&mut app); + for format in ["jpg", "gif"] { + set(&mut app, "format", json!(format)); + frame(&mut app); + } + let r = confirm(&mut app).unwrap(); + let image = image::open(r["path"].as_str().unwrap()).unwrap().to_rgba8(); + assert_eq!((image.get_pixel(20, 14).0, image.get_pixel(50, 20).0), ([0, 0, 255, 255], [0, 0, 255, 255])); + assert_eq!(app.session.last_web_settings().color_table.deleted, ["#cc3300"]); + app.run("file.saveForWeb", json!({})).unwrap(); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields["colorTable"]["deleted"], json!(["#cc3300"])); + frame(&mut app); +} + #[test] fn optimize_to_file_size_takes_the_settings_that_fit() { let dir = vectorcraft_testkit::temp_dir("sfw-optimize"); diff --git a/crates/ui-egui/src/dialogs/tests_scroll.rs b/crates/ui-egui/src/dialogs/tests_scroll.rs new file mode 100644 index 0000000000..bb013802ed --- /dev/null +++ b/crates/ui-egui/src/dialogs/tests_scroll.rs @@ -0,0 +1,449 @@ +//! Dialogs in a short or narrow window: a dialog too large for the window scrolls instead of +//! running off the screen. Every scroll bar here is drawn at rest (a solid bar style), so the tests +//! can find it. + +use egui::{Pos2, Rect, Shape, vec2}; +use serde_json::json; +use vectorcraft_engine::Session; + +use super::*; + +type Open = fn(&mut VectorcraftApp); + +/// What a dialog drew: the shapes, the dialog window's rectangle, and how it scrolls +/// ([`modal::scrolling`]). +struct Shown { + shapes: Vec, + window: Rect, + body: Option, + whole: [bool; 2], +} + +/// Open a dialog with `open` in a `size` window, with the pointer in the window's corner (away +/// from the dialog), and draw it until it settles. With `scroll`, then scroll far down and right +/// near the dialog's right edge (on the bar of a window that scrolls as a whole, beside the lists +/// inside it) and draw it until it settles again. +fn show_in(open: Open, size: egui::Vec2, scroll: bool) -> Shown { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 80, "height": 60})).unwrap(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + crate::theme::apply(&ctx, Default::default()); + ctx.global_style_mut(|s| s.spacing.scroll = egui::style::ScrollStyle::solid()); + open(&mut app); + let screen = Rect::from_min_size(Pos2::ZERO, size); + let window = |ctx: &egui::Context| { + ctx.memory(|m| { + m.areas() + .visible_layer_ids() + .into_iter() + .filter(|l| l.order == egui::Order::Foreground) + .filter_map(|l| Some((l.id, m.area_rect(l.id)?))) + .max_by(|a, b| a.1.area().total_cmp(&b.1.area())) + }) + .unwrap_or((egui::Id::NULL, Rect::NOTHING)) + }; + let mut time = 0.0; + let mut frames = |app: &mut VectorcraftApp, first: Vec| { + let mut first = Some(first); + let mut shapes = vec![]; + for _ in 0..12 { + time += 1.0; + let input = + egui::RawInput { screen_rect: Some(screen), events: first.take().unwrap_or_default(), time: Some(time), ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| show(app, ui.ctx())); + out.textures_delta.clear(); + shapes = std::mem::take(&mut out.shapes); + } + shapes + }; + let mut shapes = frames(&mut app, vec![egui::Event::PointerMoved(screen.max - vec2(2.0, 2.0))]); + if scroll { + let wheel = egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: vec2(-5000.0, -5000.0), + phase: egui::TouchPhase::Move, + source: egui::MouseWheelSource::Unknown, + modifiers: egui::Modifiers::NONE, + }; + let (id, w) = window(&ctx); + let (body, whole) = modal::scrolling(&ctx, id); + let before = Shown { shapes: std::mem::take(&mut shapes), window: w, body, whole }; + // On the window's upright bar, else on its body's bar, else on its sideways bar, else at + // its right edge. + let sideways = bars(&before, true, true).into_iter().find(|r| r.width() >= 0.5 * w.width()); + let at = whole_bar(&before).or(body_bar(&before)).or(sideways).map_or(egui::pos2(w.right() - 23.0, w.center().y), |r| r.center()); + shapes = frames(&mut app, vec![egui::Event::PointerMoved(at), wheel]); + } + let (id, window) = window(&ctx); + let (body, whole) = modal::scrolling(&ctx, id); + Shown { shapes, window, body, whole } +} + +/// Filled bars 4 to 10 pt across and longer than 12 pt (scroll bars and their handles), upright or +/// (`sideways`) flat, inside the dialog window; with `seen`, only those inside their clip. +fn bars(shown: &Shown, sideways: bool, seen: bool) -> Vec { + fn walk(s: &Shape, clip: Rect, sideways: bool, seen: bool, out: &mut Vec) { + match s { + Shape::Rect(r) if r.fill != egui::Color32::TRANSPARENT => { + let (across, along) = if sideways { (r.rect.height(), r.rect.width()) } else { (r.rect.width(), r.rect.height()) }; + if (4.0..=10.0).contains(&across) && along > 12.0 && (!seen || clip.contains_rect(r.rect)) { + out.push(r.rect); + } + } + Shape::Vec(v) => v.iter().for_each(|s| walk(s, clip, sideways, seen, out)), + _ => {} + } + } + let mut out = vec![]; + shown.shapes.iter().for_each(|c| walk(&c.shape, c.clip_rect, sideways, seen, &mut out)); + out.retain(|r| shown.window.expand(0.5).contains_rect(*r)); + out +} + +/// The bar of a shared dialog's scrolling body: the rightmost upright bar as tall as the body is +/// drawn (a list inside the body draws its bar further left). +fn body_bar(shown: &Shown) -> Option { + let view = shown.body?; + bars(shown, false, true).into_iter().filter(|r| (r.height() - view).abs() <= 1.0).max_by(|a, b| a.right().total_cmp(&b.right())) +} + +/// The bar of a window that scrolls as a whole: an upright bar at the window's right edge that +/// runs most of the window's height (lists inside it are shorter). +fn whole_bar(shown: &Shown) -> Option { + let w = shown.window; + bars(shown, false, true) + .into_iter() + .filter(|r| r.right() >= w.right() - 24.0 && r.height() >= 0.8 * w.height()) + .max_by(|a, b| a.height().total_cmp(&b.height())) +} + +/// The texts `labels` the dialog drew, each with whether it can be seen (inside the screen and +/// its clip). +fn buttons(shown: &Shown, screen: Rect, labels: &[&str]) -> Vec<(String, bool)> { + texts(shown) + .into_iter() + .filter(|(s, ..)| labels.contains(&s.as_str())) + .map(|(s, r, clip)| (s, screen.contains_rect(r) && clip.contains_rect(r))) + .collect() +} + +#[test] +fn a_dialog_taller_than_the_window_scrolls_its_body_and_keeps_its_buttons_in_view() { + let opens: [(&str, Open, &[&str]); 7] = [ + ("SVG Options", |app| svg_options::open(app, svg_options::Mode::Export, Some("/tmp/x.svg")), &["OK", "Cancel"]), + ("EPS Options", |app| eps_options::open(app, &json!({"format": "eps", "path": "/tmp/x.eps"})), &["Export", "Cancel"]), + ("DXF Options", |app| dxf_options::open(app, &json!({"format": "dxf", "path": "/tmp/x.dxf"})), &["Export", "Cancel"]), + ( + "Save PDF", + |app| { + save_pdf::open(app, &json!({"path": "/tmp/x.pdf"})).unwrap(); + }, + &["Cancel"], + ), + ( + "Save for Web", + |app| { + save_for_web::open(app).unwrap(); + }, + &["Cancel", "Done"], + ), + ("Export for Screens", export_for_screens::open, &["Cancel"]), + ( + "Print", + |app| { + print::open(app).unwrap(); + }, + &["Cancel", "Done"], + ), + ]; + let screen = Rect::from_min_size(Pos2::ZERO, vec2(1024.0, 480.0)); + for (name, open, labels) in opens { + let tall = show_in(open, vec2(1280.0, 900.0), false); + assert!(tall.window.height() > screen.height(), "{name}: the dialog is taller than the short window ({:?})", tall.window); + assert_eq!((tall.body, tall.whole), (None, [false; 2]), "{name}: in a tall window nothing scrolls"); + let shown = show_in(open, screen.size(), false); + assert!(screen.contains_rect(shown.window), "{name}: the dialog stays on the screen: {:?}", shown.window); + let found = buttons(&shown, screen, labels); + assert_eq!(found.len(), labels.len(), "{name}: {found:?}"); + assert!(found.iter().all(|(_, seen)| *seen), "{name}: the buttons stay in view: {found:?}"); + assert_eq!(shown.whole, [false; 2], "{name}: the window does not scroll as a whole"); + let bar = body_bar(&shown); + assert!(bar.is_some(), "{name}: the body scrolls ({:?}) and its bar is drawn: {:?}", shown.body, bars(&shown, false, true)); + } +} + +#[test] +fn a_list_in_a_scrolling_body_is_no_taller_than_the_body() { + // The settings of Save for Web and the sections of Print and Save PDF scroll in lists of their + // own; in a short window those lists are no taller than the body shows, so each list and its + // bar can be scrolled into view whole. + let opens: [(&str, Open); 3] = [ + ("Save for Web", |app| { + save_for_web::open(app).unwrap(); + }), + ("Print", |app| { + print::open(app).unwrap(); + if let Some(d) = app.ui.dialog.as_mut() { + d.fields.insert("__section".into(), json!("Marks and Bleed")); + } + }), + ("Save PDF", |app| { + save_pdf::open(app, &json!({"path": "/tmp/x.pdf"})).unwrap(); + if let Some(d) = app.ui.dialog.as_mut() { + d.fields.insert("__section".into(), json!("Marks and Bleeds")); + } + }), + ]; + let screen = Rect::from_min_size(Pos2::ZERO, vec2(1024.0, 400.0)); + let mut wrong = vec![]; + for (name, open) in opens { + let shown = show_in(open, screen.size(), false); + let Some(body) = body_bar(&shown) else { + wrong.push(format!("{name}: the body does not scroll ({:?}): {:?}", shown.body, bars(&shown, false, false))); + continue; + }; + // The tracks of the lists' bars, seen or not: left of the body's bar and inside the window + // (a list taller than the body runs past the window's bottom). + let lists: Vec = bars(&shown, false, false).into_iter().filter(|r| r.right() < body.left()).collect(); + let tallest = lists.iter().map(|r| r.height()).fold(0.0, f32::max); + if tallest == 0.0 || tallest > body.height() + 0.5 { + wrong.push(format!("{name}: no list bar no taller than the body ({}): {:?}", body.height(), bars(&shown, false, false))); + } + } + assert!(wrong.is_empty(), "{wrong:#?}"); +} + +#[test] +fn save_for_web_in_the_smallest_window_keeps_its_settings_and_buttons_in_view() { + let open: Open = |app| { + save_for_web::open(app).unwrap(); + }; + // The app window's smallest size, 800 by 500 pixels, at a UI scale of 100%, 110% and 125%. + let mut wrong = vec![]; + for size in [vec2(800.0, 500.0), vec2(727.0, 454.0), vec2(640.0, 400.0)] { + let screen = Rect::from_min_size(Pos2::ZERO, size); + let shown = show_in(open, size, false); + let labels = ["Format:", "Optimize to File Size…", "Cancel", "Done"]; + let found = buttons(&shown, screen, &labels); + if !screen.contains_rect(shown.window) || found.len() != labels.len() || !found.iter().all(|(_, seen)| *seen) { + wrong.push(format!("{size:?}: the dialog ({:?}) leaves its settings and buttons in view: {found:?}", shown.window)); + } + if body_bar(&shown).is_none() || shown.whole != [false; 2] { + wrong.push(format!("{size:?}: only the body scrolls ({:?}, {:?})", shown.body, shown.whole)); + } + // The controls under the narrower panes stay in their column, left of the settings. + let controls = text_rects(&shown, "Preview in Browser").first().map(|r| r.right()); + let settings = text_rects(&shown, "Format:").first().map(|r| r.left()); + if !matches!((controls, settings), (Some(c), Some(s)) if c < s) { + wrong.push(format!("{size:?}: Preview in Browser ({controls:?}) is left of the settings ({settings:?})")); + } + // Preview in Browser is right of the download speed list or on a row below it, not over it. + let button = text_rects(&shown, "Preview in Browser").first().copied(); + let speed = text_rects(&shown, "56.6 Kbps").first().copied(); + if !matches!((button, speed), (Some(b), Some(s)) if b.left() > s.right() + 16.0 || b.top() > s.bottom() + 8.0) { + wrong.push(format!("{size:?}: Preview in Browser ({button:?}) clears the download speed list ({speed:?})")); + } + } + assert!(wrong.is_empty(), "{wrong:#?}"); +} + +/// The rectangles of the texts `label` the dialog drew. +fn text_rects(shown: &Shown, label: &str) -> Vec { + fn walk(s: &Shape, label: &str, out: &mut Vec) { + match s { + Shape::Text(t) if t.galley.text() == label => out.push(t.visual_bounding_rect()), + Shape::Vec(v) => v.iter().for_each(|s| walk(s, label, out)), + _ => {} + } + } + let mut out = vec![]; + shown.shapes.iter().for_each(|c| walk(&c.shape, label, &mut out)); + out +} + +#[test] +fn a_window_too_large_for_the_screen_scrolls_as_a_whole() { + let opens: [(&str, Open, &[&str]); 4] = [ + ("Preferences", |app| crate::prefs_dialog::open(app, None), &["OK", "Cancel"]), + ("Keyboard Shortcuts", crate::shortcut_editor::open, &["OK", "Cancel"]), + ("New Document", new_document::open, &["Create", "Close"]), + ("Find Font", crate::find_font::open, &["Done"]), + ]; + // The app window's smallest size. + let screen = Rect::from_min_size(Pos2::ZERO, vec2(800.0, 500.0)); + for (name, open, labels) in opens { + let tall = show_in(open, vec2(1280.0, 900.0), false); + assert!( + tall.window.height() > screen.height() || tall.window.width() > screen.width(), + "{name}: the dialog is larger than the small window ({:?})", + tall.window + ); + assert_eq!(tall.whole, [false; 2], "{name}: in a large window the dialog does not scroll as a whole"); + let shown = show_in(open, screen.size(), false); + assert!(screen.contains_rect(shown.window), "{name}: the dialog stays on the screen: {:?}", shown.window); + assert!(shown.whole[1], "{name}: the dialog scrolls as a whole"); + assert!(whole_bar(&shown).is_some(), "{name}: the window's bar is drawn: {:?}", bars(&shown, false, true)); + // The buttons can sit outside the part in view; each is in view at the top or scrolled to + // the end. + let scrolled = show_in(open, screen.size(), true); + let (top, end) = (buttons(&shown, screen, labels), buttons(&scrolled, screen, labels)); + for label in labels { + let seen = |found: &[(String, bool)]| found.iter().any(|(s, seen)| s == label && *seen); + assert!(seen(&top) || seen(&end), "{name}: {label} can be scrolled into view: {top:?} {end:?}"); + } + } +} + +#[test] +fn keyboard_shortcuts_keeps_its_scroll_under_import_shortcut_set() { + // Scrolled down in the smallest window, Keyboard Shortcuts is where it was left when Import + // Shortcut Set, opened over it, is canceled; closed and opened again, it starts at its top. + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + crate::theme::apply(&ctx, Default::default()); + let screen = Rect::from_min_size(Pos2::ZERO, vec2(800.0, 500.0)); + let mut time = 0.0; + // Draws 12 frames, the first with `events`; returns whether the heading can be seen. + let mut heading_seen = |app: &mut VectorcraftApp, events: Vec| { + let mut events = Some(events); + let mut seen = false; + for _ in 0..12 { + time += 1.0; + let input = + egui::RawInput { screen_rect: Some(screen), events: events.take().unwrap_or_default(), time: Some(time), ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| show(app, ui.ctx())); + out.textures_delta.clear(); + let shown = Shown { shapes: out.shapes, window: screen, body: None, whole: [false; 2] }; + seen = buttons(&shown, screen, &["Keyboard Shortcuts"]).iter().any(|(_, seen)| *seen); + } + seen + }; + let wheel = |at: Pos2| { + let wheel = egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: vec2(0.0, -5000.0), + phase: egui::TouchPhase::Move, + source: egui::MouseWheelSource::Unknown, + modifiers: egui::Modifiers::NONE, + }; + vec![egui::Event::PointerMoved(at), wheel] + }; + crate::shortcut_editor::open(&mut app); + assert!(heading_seen(&mut app, vec![]), "Keyboard Shortcuts opens at its top"); + // On the window's bar, inside its 20 pt margin. + let window = ctx.memory(|m| m.area_rect(egui::Id::unique("dialog-shortcuts"))).unwrap_or(screen); + assert!(!heading_seen(&mut app, wheel(egui::pos2(window.right() - 23.0, window.center().y))), "the wheel scrolls the heading away"); + let kys = "/Menus {\n /Acme\\ Copy { /Modifiers 11 /Key 902 }\n}\n"; + crate::io::open_bytes(&mut app, "Keys.kys", kys.as_bytes(), None).unwrap(); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(shortcut_import::KIND)); + heading_seen(&mut app, vec![]); + cancel(&mut app); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some("shortcuts"), "Cancel shows Keyboard Shortcuts again"); + assert!(!heading_seen(&mut app, vec![]), "shown again, Keyboard Shortcuts is where it was scrolled to"); + cancel(&mut app); + heading_seen(&mut app, vec![]); + crate::shortcut_editor::open(&mut app); + assert!(heading_seen(&mut app, vec![]), "opened again, Keyboard Shortcuts starts at its top"); +} + +/// Open Import Shortcut Set on a set of two shortcuts. +fn open_shortcut_import(app: &mut VectorcraftApp) { + let kys = "/Menus {\n /Acme\\ Copy { /Modifiers 11 /Key 902 }\n /Acme\\ Paste { /Modifiers 11 /Key 903 }\n}\n"; + crate::io::open_bytes(app, "Keys.kys", kys.as_bytes(), None).unwrap(); +} + +#[test] +fn a_window_that_fits_itself_but_is_too_wide_scrolls_sideways() { + // Import Shortcut Set sizes its lists from the window's height and is about 780 pt wide. An + // 800 by 600 pixel window at a UI scale of 125% is 640 by 480 pt. + let wide = show_in(open_shortcut_import, vec2(1280.0, 900.0), false); + let screen = Rect::from_min_size(Pos2::ZERO, vec2(640.0, 480.0)); + assert!(wide.window.width() > screen.width(), "Import Shortcut Set is wider than the window: {:?}", wide.window); + assert_eq!(wide.whole, [false; 2], "in a large window it does not scroll"); + let shown = show_in(open_shortcut_import, screen.size(), false); + assert!(screen.contains_rect(shown.window), "the dialog stays on the screen: {:?}", shown.window); + assert_eq!(shown.whole, [true, false], "it scrolls sideways only"); + let sideways: Vec = bars(&shown, true, true).into_iter().filter(|r| r.width() >= 0.5 * shown.window.width()).collect(); + assert!(!sideways.is_empty(), "its sideways bar is drawn: {:?}", bars(&shown, true, false)); +} + +#[test] +fn a_window_wider_than_the_screen_scrolls_sideways_to_its_right_edge() { + // In a window 70% as wide as the dialog, the dialog scrolls sideways, and scrolled to its right + // edge, the text drawn furthest right in a large window can be seen. + let opens: [(&str, Open); 3] = [ + ("Import Shortcut Set", open_shortcut_import), + ("Keyboard Shortcuts", crate::shortcut_editor::open), + ("Preferences", |app| crate::prefs_dialog::open(app, None)), + ]; + let mut wrong = vec![]; + for (name, open) in opens { + let wide = show_in(open, vec2(1600.0, 1000.0), false); + let Some((right, _)) = texts(&wide) + .into_iter() + .filter(|(_, r, _)| wide.window.contains_rect(*r)) + .map(|(s, r, _)| (s, r.right())) + .max_by(|a, b| a.1.total_cmp(&b.1)) + else { + wrong.push(format!("{name}: no text in the large window")); + continue; + }; + let screen = Rect::from_min_size(Pos2::ZERO, vec2((0.7 * wide.window.width()).round(), 1000.0)); + let shown = show_in(open, screen.size(), false); + let scrolled = show_in(open, screen.size(), true); + // Within 1 pt: a text's drawn box can reach a fraction of a point past the content's edge. + let seen = + |shown: &Shown| texts(shown).iter().any(|(s, r, clip)| *s == right && screen.contains_rect(*r) && clip.expand(1.0).contains_rect(*r)); + let sideways = bars(&shown, true, true).into_iter().any(|r| r.width() >= 0.5 * shown.window.width()); + if !screen.contains_rect(shown.window) || !shown.whole[0] || !sideways || seen(&shown) || !seen(&scrolled) { + let at = |shown: &Shown| texts(shown).into_iter().filter(|(s, ..)| *s == right).collect::>(); + wrong.push(format!( + "{name} in {:?}: window {:?}, scrolls {:?}, sideways bar {sideways}, {right:?} seen at first {} {:?}, scrolled {} {:?}, bars {:?}", + screen.size(), + shown.window, + shown.whole, + seen(&shown), + at(&shown), + seen(&scrolled), + at(&scrolled), + bars(&shown, true, true) + )); + } + } + assert!(wrong.is_empty(), "{wrong:#?}"); +} + +/// Every text the dialog drew, with its rectangle and its clip. +fn texts(shown: &Shown) -> Vec<(String, Rect, Rect)> { + fn walk(s: &Shape, clip: Rect, out: &mut Vec<(String, Rect, Rect)>) { + match s { + Shape::Text(t) => out.push((t.galley.text().to_string(), t.visual_bounding_rect(), clip)), + Shape::Vec(v) => v.iter().for_each(|s| walk(s, clip, out)), + _ => {} + } + } + let mut out = vec![]; + shown.shapes.iter().for_each(|c| walk(&c.shape, c.clip_rect, &mut out)); + out +} + +#[test] +fn a_dialog_with_buttons_in_its_body_scrolls_them_with_the_body() { + // Check Spelling draws its buttons inside its body: in a window too short for it, the heading + // stays in view and the buttons scroll with the body. + let open: Open = |app| { + check_spelling::open(app).unwrap(); + }; + let tall = show_in(open, vec2(1280.0, 900.0), false); + let screen = Rect::from_min_size(Pos2::ZERO, vec2(1024.0, (0.6 * tall.window.height()).round())); + let shown = show_in(open, screen.size(), false); + let scrolled = show_in(open, screen.size(), true); + let seen = |shown: &Shown, label: &str| buttons(shown, screen, &[label]).iter().any(|(_, seen)| *seen); + assert!(screen.contains_rect(shown.window), "the dialog stays on the screen: {:?}", shown.window); + assert!(body_bar(&shown).is_some() && shown.whole == [false; 2], "only the body scrolls ({:?}, {:?})", shown.body, shown.whole); + assert!(seen(&shown, "Check Spelling") && seen(&scrolled, "Check Spelling"), "the heading stays in view"); + assert!(!seen(&shown, "Cancel") && seen(&scrolled, "Cancel"), "Cancel is out of view until the body is scrolled down"); +} diff --git a/crates/ui-egui/src/dialogs/three_d_materials.rs b/crates/ui-egui/src/dialogs/three_d_materials.rs index e0af93a825..659283f099 100644 --- a/crates/ui-egui/src/dialogs/three_d_materials.rs +++ b/crates/ui-egui/src/dialogs/three_d_materials.rs @@ -1,13 +1,14 @@ //! The 3D and Materials panel's Materials tab: the document's Graphics (its symbols) as thumbnails, //! Add as Single Graphic, and the graphics mapped onto the selected 3D object (its planar faces, -//! Revolve's side, or Inflate's puffed faces) with their face, position, size and turn. Picking a thumbnail maps that graphic +//! Extrude & Bevel's side, Revolve's side, or Inflate's puffed faces) with their face, position, size and turn. Picking a +//! thumbnail maps that graphic //! onto the selected objects (`threeD.mapGraphic`); art dropped on the thumbnails becomes a graphic //! (`threeD.addGraphic`). Editing a mapped graphic changes the effect's `graphics` parameter, which //! the panel sends as it sends every other setting. use egui::{Sense, Stroke, StrokeKind, vec2}; use serde_json::{Value, json}; -use vectorcraft_effects::{GRAPHICS, MappedGraphic, PlanarFace, REVOLVE, ROTATE}; +use vectorcraft_effects::{GRAPHICS, INFLATE, MappedGraphic, PlanarFace, REVOLVE, ROTATE}; use super::revolve::{heading, label, number}; use crate::VectorcraftApp; @@ -85,6 +86,15 @@ pub(crate) fn library(app: &VectorcraftApp, ui: &mut egui::Ui, apply: bool) -> O action } +/// The name of `face` in the interface. +fn face_label(face: PlanarFace) -> &'static str { + match face { + PlanarFace::Front => tl!("Front"), + PlanarFace::Back => tl!("Back"), + PlanarFace::Side => tl!("Side"), + } +} + /// The Materials tab of the 3D effect in `d.fields["__effect"]`: the Graphics list, then the /// graphics mapped onto the object, the selected one with its settings. Edits `d.fields`; a click /// in the list is left in [`ACTION`]. @@ -112,7 +122,7 @@ pub(crate) fn controls(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) } let mut index = d.fields.get(SELECTED).and_then(Value::as_u64).map_or(0, |i| i as usize).min(list.len() - 1); for (i, g) in list.iter().enumerate() { - let face = if g.face == PlanarFace::Back { tl!("Back") } else { tl!("Front") }; + let face = face_label(g.face); if ui.selectable_label(i == index, format!("{} · {face}", g.symbol)).clicked() { index = i; } @@ -121,15 +131,21 @@ pub(crate) fn controls(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) ui.add_space(6.0); let Some(g) = list.get(index).cloned() else { return }; let mut edited = g.clone(); - // A plane has one face, and Revolve's graphics go on its side. + // A plane has one face, and Revolve's graphics go on its side. Extrude & Bevel's graphics go on + // its front or back cap, or on its side (its walls and bevels). Inflate's go on its puffed front + // or back. if effect != ROTATE && effect != REVOLVE { + let faces: &[PlanarFace] = if effect == INFLATE { &[PlanarFace::Front, PlanarFace::Back] } else { &PlanarFace::ALL }; ui.horizontal(|ui| { ui.spacing_mut().item_spacing.x = 6.0; label(ui, tl!("Face")); - let labels = [tl!("Front"), tl!("Back")]; - let at = usize::from(g.face == PlanarFace::Back); - if let Some(k) = widgets::dropdown(ui, "three-d-graphic-face", labels[at], &labels, 120.0) { - edited.face = PlanarFace::ALL[k.min(1)]; + let labels: Vec<&str> = faces.iter().map(|f| face_label(*f)).collect(); + let at = faces.iter().position(|f| *f == g.face).unwrap_or(0); + let current = labels.get(at).copied().unwrap_or_default(); + if let Some(k) = widgets::dropdown(ui, "three-d-graphic-face", current, &labels, 120.0) + && let Some(face) = faces.get(k) + { + edited.face = *face; } }); } diff --git a/crates/ui-egui/src/dialogs/tools.rs b/crates/ui-egui/src/dialogs/tools.rs index 6dbcfe28ce..5e7b0d4092 100644 --- a/crates/ui-egui/src/dialogs/tools.rs +++ b/crates/ui-egui/src/dialogs/tools.rs @@ -112,7 +112,7 @@ pub fn open_tool_dialog(app: &mut VectorcraftApp, kind: &str, p: Value) { "rotate" => json!({"angle": 0}), "reflect" => json!({"axis": "vertical", "angle": 90}), "scale" => json!({"sx": 100, "sy": 100, "uniform": true}), - "shear" => json!({"angle": 0, "axis": "horizontal"}), + "shear" => json!({"angle": 0, "axis": "horizontal", "axisAngle": 0}), _ => json!({}), }; if let (Some(b), Some(o)) = (base.as_object_mut(), p.as_object()) { diff --git a/crates/ui-egui/src/dialogs/transform.rs b/crates/ui-egui/src/dialogs/transform.rs index 4f576b561a..cf8c2e6b44 100644 --- a/crates/ui-egui/src/dialogs/transform.rs +++ b/crates/ui-egui/src/dialogs/transform.rs @@ -220,6 +220,7 @@ fn command(app: &VectorcraftApp, d: &Dialog) -> (&'static str, Value) { // The axis by name, or the angle it is at. "reflect" if d.str("axis") == "angle" => ("object.reflect", json!({"axis": d.f64("angle", 90.0)})), "reflect" => ("object.reflect", json!({"axis": d.fields.get("axis").cloned().unwrap_or(json!("vertical"))})), + "shear" if d.str("axis") == "angle" => ("object.shear", json!({"angle": d.f64("angle", 0.0), "axis": d.f64("axisAngle", 0.0)})), _ => ("object.shear", json!({"angle": d.f64("angle", 0.0), "axis": d.str("axis")})), }; params["copy"] = json!(d.bool("copy")); @@ -377,6 +378,54 @@ mod tests { } } + /// Shear's axis is Horizontal, Vertical or an angle: the Axis Angle field takes input only with + /// the Angle axis and keeps its value with the others, and OK sends that angle as the axis, + /// apart from the Shear Angle. + #[test] + fn shear_takes_an_axis_angle() { + use egui::accesskit::Role; + use egui_kittest::kittest::{NodeT, Queryable}; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 60, "height": 20})).unwrap(); + crate::menus::invoke(&mut app, "object.shear", json!({})); + let mut fonts = false; + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1100.0, 900.0)).build_ui_state( + move |ui, app: &mut VectorcraftApp| { + if !std::mem::replace(&mut fonts, true) { + crate::theme::install_fonts(ui.ctx()); + return; + } + crate::dialogs::show(app, ui.ctx()); + }, + app, + ); + h.run_steps(5); + let dimmed = + |h: &egui_kittest::Harness<'_, VectorcraftApp>| h.get_by_role_and_label(Role::TextInput, "Axis Angle").accesskit_node().is_disabled(); + assert!(dimmed(&h), "Horizontal leaves the Axis Angle off"); + // Along an axis at 90° the left and right sides slide, 45° moving the right one by the width; + // at 0° the top and bottom slide by the height. Each case is undone before the next. + for (axis, axis_angle, sent, size) in + [("angle", 90, json!(90.0), (60.0, 80.0)), ("angle", 0, json!(0.0), (80.0, 20.0)), ("vertical", 30, json!("vertical"), (60.0, 80.0))] + { + let d = h.state_mut().ui.dialog.as_mut().unwrap(); + d.fields.extend([("axis".to_string(), json!(axis)), ("axisAngle".to_string(), json!(axis_angle)), ("angle".to_string(), json!(45))]); + h.run_steps(2); + assert_eq!(dimmed(&h), axis != "angle", "{axis}"); + assert_eq!(h.state().ui.dialog.as_ref().unwrap().fields["axisAngle"], json!(axis_angle), "the field keeps its value"); + crate::dialogs::confirm(h.state_mut()).unwrap(); + let app = h.state(); + let (cmd, p) = app.session.journal.last().unwrap(); + assert_eq!((cmd.as_str(), &p["axis"], &p["angle"]), ("object.shear", &sent, &json!(45.0)), "{axis} {axis_angle}"); + let b = app.session.doc().unwrap().doc.layers[0].children().unwrap()[0].geometric_bounds().unwrap(); + assert_eq!((b.width().round(), b.height().round()), size, "{axis} {axis_angle}"); + h.state_mut().run("edit.undo", json!({})).unwrap(); + crate::menus::invoke(h.state_mut(), "object.shear", json!({})); + h.run_steps(2); + } + } + /// #1915: Move's Distance and Angle follow Horizontal and Vertical, and they follow them back. /// The angle is counter-clockwise on the page and Vertical is down = +, so 90° moves up. #[test] diff --git a/crates/ui-egui/src/display_profile.rs b/crates/ui-egui/src/display_profile.rs index b3f10ab27e..a1acf8ebbe 100644 --- a/crates/ui-egui/src/display_profile.rs +++ b/crates/ui-egui/src/display_profile.rs @@ -78,6 +78,10 @@ struct State { transform: Option>, /// The bytes last reported, so a reading of the same profile builds nothing. reported: Option<(Option, Vec)>, + /// The desktop app reads the display's profile ([`DisplayProfile::attach_reader`]). + reader: bool, + /// Refresh Monitor Profile asked for a reading that hasn't started yet. + requested: bool, } impl Default for State { @@ -90,6 +94,8 @@ impl Default for State { reason: Some("this build doesn't read display profiles".into()), transform: None, reported: None, + reader: false, + requested: false, } } } @@ -116,6 +122,42 @@ impl DisplayProfile { } } + /// The desktop app reads the display's profile, so [`Self::request_read`] can ask it to. + pub fn attach_reader(&self) { + self.write().reader = true; + } + + /// Whether something reads the display's profile ([`Self::attach_reader`]). + pub(crate) fn has_reader(&self) -> bool { + self.read().reader + } + + /// Edit › Refresh Monitor Profile: asks the desktop app to read the display's profile again on + /// its next frame, without waiting for its intervals; while a reading runs, the request waits + /// for it to end. Refused while `enabled` (the preference) is off, and when nothing reads the + /// profile. Nothing is queued when it is refused. + pub fn request_read(&self, enabled: bool) -> Result<(), String> { + if !enabled { + return Err("turn on Use Monitor Profile for Canvas first".into()); + } + let mut s = self.write(); + if !s.reader { + return Err("this build doesn't read display profiles".into()); + } + s.requested = true; + Ok(()) + } + + /// Whether [`Self::request_read`] asked for a reading that hasn't started. + pub fn read_requested(&self) -> bool { + self.read().requested + } + + /// Takes the request [`Self::request_read`] made: whether there was one. + pub fn take_request(&self) -> bool { + self.read_requested() && std::mem::take(&mut self.write().requested) + } + /// Takes `reading` in. A profile is checked, and its conversion built, on the calling thread; /// a profile that can't be used leaves the canvas sRGB, with the reason in [`Self::status`]. /// The same profile reported again for the same display changes nothing. Returns whether the @@ -170,8 +212,9 @@ impl DisplayProfile { /// The status `ui.inspect` reports as `displayProfile`: the display, what was found /// (`profile`, `srgbProfile`, `system`, `none`, `pending` or `unsupported`), the profile's - /// description and where it was read from, whether the canvas is converted, why not, and - /// whether the system converts the window. + /// description and where it was read from, whether the canvas is converted, why not, whether + /// the system converts the window, and whether a reading [`Self::request_read`] asked for + /// hasn't started. pub fn status(&self, enabled: bool) -> Value { let s = self.read(); json!({ @@ -183,6 +226,7 @@ impl DisplayProfile { "applied": enabled && s.transform.is_some(), "reason": s.reason, "osManaged": s.kind == Kind::System, + "readRequested": s.requested, }) } @@ -535,6 +579,22 @@ pub(crate) mod tests { assert!(d.key(true) > key); } + #[test] + fn a_reading_is_requested_only_with_the_preference_on_and_a_reader() { + let d = DisplayProfile::default(); + assert_eq!(d.request_read(true).unwrap_err(), "this build doesn't read display profiles"); + d.attach_reader(); + assert_eq!(d.request_read(false).unwrap_err(), "turn on Use Monitor Profile for Canvas first"); + assert!(!d.read_requested() && !d.take_request(), "a refused request is not queued"); + d.request_read(true).unwrap(); + d.request_read(true).unwrap(); + assert_eq!(d.status(true)["readRequested"].as_bool(), Some(true)); + // Two requests before the reading starts make one reading. + assert!(d.take_request()); + assert!(!d.take_request()); + assert_eq!(d.status(true)["readRequested"].as_bool(), Some(false)); + } + #[test] fn a_profile_that_can_t_be_used_leaves_the_canvas_srgb_and_says_why() { let d = DisplayProfile::default(); diff --git a/crates/ui-egui/src/find_font.rs b/crates/ui-egui/src/find_font.rs index 6cffc344d1..0ee21574fb 100644 --- a/crates/ui-egui/src/find_font.rs +++ b/crates/ui-egui/src/find_font.rs @@ -4,10 +4,13 @@ //! missing fonts' files, in the Missing Fonts dialog: `ui.findFontsInFolder`). Find In limits Find //! to the active artboard or the selected layers. +use std::sync::Arc; + use egui::Ui; use serde_json::{Value, json}; use crate::VectorcraftApp; +use crate::caches::{FindFontCache, FontsKey}; use crate::state::Dialog; use crate::theme::Tokens; use crate::widgets; @@ -20,7 +23,7 @@ pub fn open(app: &mut VectorcraftApp) { /// Open the dialog on the first font the document misses, to replace it (Missing Fonts' Find /// Fonts). pub fn open_on_missing(app: &mut VectorcraftApp) { - let first = fonts(app).iter().position(|f| matches!(f["status"].as_str(), Some("missing" | "substitute"))); + let first = document_fonts(app, false).0.iter().position(|f| matches!(f["status"].as_str(), Some("missing" | "substitute"))); open_at(app, first.unwrap_or(0)); } @@ -28,7 +31,7 @@ pub fn open_on_missing(app: &mut VectorcraftApp) { /// System's font ([`system_family`]) to change to, and the last Find In choice (Document at first). fn open_at(app: &mut VectorcraftApp, selected: usize) { let find_in = FIND_IN.iter().find(|f| **f == app.ui.find_font_in).copied().unwrap_or("document"); - let used = fonts(app); + let (used, _) = document_fonts(app, false); let source = "system"; let rows = replacement_rows(app, source, &used); let family = system_family(); @@ -252,6 +255,30 @@ fn fonts(app: &mut VectorcraftApp) -> Vec { app.session.execute("text.fonts", &json!({})).ok().and_then(|v| v.as_array().cloned()).unwrap_or_default() } +/// The active document's fonts ([`fonts`]) and, when `missing` is asked for, whether it misses a +/// font ([`vectorcraft_engine::cmd::fontfiles::missing_fonts`]; `false` when it is not asked +/// for). Both are kept in [`crate::CanvasCache::find_font`] and worked out again only for another +/// document, another version of its content or another font generation. No document: no fonts. +fn document_fonts(app: &mut VectorcraftApp, missing: bool) -> (Arc>, bool) { + let Some(st) = app.session.active() else { return (Arc::default(), false) }; + // The generation is read first: fonts loaded while the answers are worked out leave the entry + // under the older generation, so the next frame works them out again. + let key = FontsKey { uid: st.uid, doc: Arc::downgrade(&st.doc), generation: vectorcraft_text::FontDb::global().generation() }; + if app.canvas.find_font.as_ref().is_none_or(|c| c.key != key) { + let fonts = Arc::new(fonts(app)); + app.canvas.find_font = Some(FindFontCache { key, fonts, missing: None }); + } + if missing + && let Some(c) = app.canvas.find_font.as_mut() + && c.missing.is_none() + && let Some(st) = app.session.active() + { + c.missing = Some(!vectorcraft_engine::cmd::fontfiles::missing_fonts(&st.doc).is_empty()); + } + let c = app.canvas.find_font.as_ref(); + (c.map(|c| c.fonts.clone()).unwrap_or_default(), missing && c.and_then(|c| c.missing).unwrap_or(false)) +} + pub fn confirm(app: &mut VectorcraftApp) -> Result { if let Some(ctx) = app.ui_ctx.clone() { clear_search(&ctx); @@ -279,10 +306,9 @@ fn change(app: &mut VectorcraftApp, d: &Dialog, from: &Value, all: bool) -> Resu pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { let Some(mut d) = app.ui.dialog.clone() else { return }; let t = Tokens::get(ctx); - let list = fonts(app); // Find in Folder… shows when the document misses fonts, fonts used only in its symbols included. - let offer_folder = crate::picks::can(app, &crate::picks::PickRequest::Folder) - && app.session.active().is_some_and(|st| !vectorcraft_engine::cmd::fontfiles::missing_fonts(&st.doc).is_empty()); + let can_pick = crate::picks::can(app, &crate::picks::PickRequest::Folder); + let (list, offer_folder) = document_fonts(app, can_pick); let mut close = false; let mut find_in_folder = false; let mut act: Option<&str> = None; @@ -416,7 +442,7 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { match run_button(app, &d, a, from) { // The rows are a snapshot: the document's fonts and the recent fonts have moved on. Ok(_) if a != "find" => { - let used = fonts(app); + let (used, _) = document_fonts(app, false); d.fields.insert("rows".into(), rows_json(&replacement_rows(app, &d.str("replaceFrom"), &used))); } Ok(_) => {} @@ -1421,4 +1447,231 @@ mod tests { let (note, color) = font_note(&row("exact", 2)); assert!(note.contains("2 characters") && color.is_some()); } + + /// The font list the dialog keeps for the active document. + fn kept_list(app: &VectorcraftApp) -> Arc> { + app.canvas.find_font.as_ref().expect("the dialog kept the document's fonts").fonts.clone() + } + + /// The kept list and Find in Folder… are what `text.fonts` and `missing_fonts` give now. + fn assert_current(app: &mut VectorcraftApp, shown: &str, why: &str) { + let listed = fonts(app); + assert_eq!(*kept_list(app), listed, "{why}: the list"); + let missing = app.session.active().is_some_and(|st| !vectorcraft_engine::cmd::fontfiles::missing_fonts(&st.doc).is_empty()); + let picks = crate::picks::can(app, &crate::picks::PickRequest::Folder); + assert_eq!(shown.contains("Find in Folder…"), picks && missing, "{why}: Find in Folder… {shown}"); + } + + /// A document set in a missing family and in Inter, with a folder picker. + fn missing_font_document() -> VectorcraftApp { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + for (y, font) in [(20, "Missing Family"), (40, "Inter")] { + app.session.execute("text.create", &json!({"x": 10, "y": y, "text": "Hi", "font": font})).unwrap(); + } + app.services.pick_folder = Some(Box::new(|| None)); + app + } + + /// Frames that change nothing in the document, a new selection included, keep the font list + /// and the missing-font answer worked out on the first; the answer is worked out only once a + /// folder picker is there. + #[test] + fn the_font_list_is_worked_out_once_per_document_version() { + let mut app = missing_font_document(); + let picker = app.services.pick_folder.take(); + open(&mut app); + assert!(kept_over_frames(&mut app, "no folder picker"), "frames of one document version keep its list"); + assert_eq!(app.canvas.find_font.as_ref().and_then(|c| c.missing), None, "no picker: the document is not searched for missing fonts"); + app.services.pick_folder = picker; + assert!(kept_over_frames(&mut app, "a folder picker"), "a picker alone keeps the list"); + assert_eq!(app.canvas.find_font.as_ref().and_then(|c| c.missing), Some(true)); + app.run("select.all", json!({})).unwrap(); + assert!(kept_over_frames(&mut app, "a new selection"), "a new selection keeps the list"); + } + + /// Draws frames of the dialog and tells whether they kept the list kept before them. Another + /// test thread that changes the available fonts meanwhile makes the dialog work the list out + /// again, so the frames are drawn again until the fonts stay as they are. + fn kept_over_frames(app: &mut VectorcraftApp, why: &str) -> bool { + for _ in 0..20 { + // The generation the kept list was worked out under: the database's generation only + // counts up, so the same one after the frames means no fonts changed in between. + let before = kept_list(app); + let generation = app.canvas.find_font.as_ref().map(|c| c.key.generation); + let shown = crate::tests_labels::painted_text(app, |app, ui| show(app, ui.ctx())); + assert_current(app, &shown, why); + if Some(vectorcraft_text::FontDb::global().generation()) == generation { + return Arc::ptr_eq(&before, &kept_list(app)); + } + } + panic!("{why}: the available fonts kept changing") + } + + /// An edit, its undo and a Change All each give the list of the document as it is then. + #[test] + fn an_edit_works_the_font_list_out_again() { + let mut app = missing_font_document(); + open(&mut app); + crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx())); + let first = kept_list(&app); + app.run("text.replaceFont", json!({"from": {"family": "Missing Family"}, "to": {"family": "Inter"}})).unwrap(); + let shown = crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx())); + assert_current(&mut app, &shown, "after the replacement"); + assert!(!shown.contains("Find in Folder…"), "nothing is missing: {shown}"); + assert_eq!(kept_list(&app).len(), 1, "{:?}", kept_list(&app)); + app.run("edit.undo", json!({})).unwrap(); + let shown = crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx())); + assert_current(&mut app, &shown, "after the undo"); + assert_eq!(*kept_list(&app), *first, "the undo brings back the first list"); + let mut d = app.ui.dialog.clone().unwrap(); + d.fields.insert("family".into(), json!("Source Serif 4")); + d.fields.insert("style".into(), json!("")); + let from = first.iter().find(|f| f["family"] == "Inter").unwrap().clone(); + change(&mut app, &d, &from, true).unwrap(); + let shown = crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx())); + assert_current(&mut app, &shown, "after Change All"); + assert!(kept_list(&app).iter().any(|f| f["family"] == "Source Serif 4"), "{:?}", kept_list(&app)); + } + + /// Fonts that become available, a composite font defined among them, give the list and the + /// missing-font answer as they are with those fonts. + #[test] + fn other_available_fonts_work_the_font_list_out_again() { + const FAMILY: &str = "Find Font Kept List CF"; + let mut app = missing_font_document(); + app.session.execute("text.create", &json!({"x": 10, "y": 60, "text": "Ab12", "font": FAMILY})).unwrap(); + open(&mut app); + crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx())); + // The same document under another generation of the font database: what is kept for it no + // longer counts. + let entry = app.canvas.find_font.as_mut().unwrap(); + entry.key.generation = u64::MAX; + entry.fonts = Arc::default(); + entry.missing = Some(false); + let shown = crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx())); + assert_current(&mut app, &shown, "another font generation"); + let row = |app: &VectorcraftApp| kept_list(app).iter().find(|f| f["family"] == FAMILY).cloned().unwrap(); + assert_eq!(row(&app)["status"], "missing"); + let generation = vectorcraft_text::FontDb::global().generation(); + let parts = json!({"name": FAMILY, "parts": {"kanji": {"font": "Source Sans 3"}, "roman": {"font": "JetBrains Mono"}, "numerals": {"font": "Inter"}}}); + app.run("type.compositeFonts.set", json!({"fonts": [parts]})).unwrap(); + assert_ne!(vectorcraft_text::FontDb::global().generation(), generation, "defining a composite font is a new generation"); + let shown = crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx())); + assert_current(&mut app, &shown, "the composite font defined"); + assert_eq!(row(&app)["status"], "exact"); + app.run("type.compositeFonts.set", json!({"fonts": []})).unwrap(); + let shown = crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx())); + assert_current(&mut app, &shown, "the composite font taken out"); + assert_eq!(row(&app)["status"], "missing"); + } + + /// Another document in front, and pattern editing entered and canceled, each give the list of + /// the document in front as it is then. + #[test] + fn the_font_list_follows_the_document_in_front() { + let mut app = missing_font_document(); + app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + let id = app.session.execute("text.create", &json!({"x": 10, "y": 40, "text": "Hi", "font": "Source Serif 4"})).unwrap()["id"].clone(); + app.services.pick_folder = Some(Box::new(|| None)); + open(&mut app); + let shown = crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx())); + assert_current(&mut app, &shown, "the second document"); + app.session.set_active(0); + let shown = crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx())); + assert_current(&mut app, &shown, "the first document"); + assert!(shown.contains("Find in Folder…"), "{shown}"); + app.session.set_active(1); + app.run("select.set", json!({"ids": [id]})).unwrap(); + app.run("object.pattern.make", json!({"name": "Kept List"})).unwrap(); + assert!(app.session.active().unwrap().doc.pattern_edit.is_some(), "pattern editing"); + let shown = crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx())); + assert_current(&mut app, &shown, "pattern editing"); + app.run("object.pattern.cancel", json!({})).unwrap(); + let shown = crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx())); + assert_current(&mut app, &shown, "pattern editing canceled"); + } + + /// CPU time of this thread in nanoseconds where the system reports it (Linux), else `None`. + fn thread_cpu_ns() -> Option { + std::fs::read_to_string("/proc/thread-self/schedstat").ok()?.split_whitespace().next()?.parse().ok() + } + + /// Time the font list and the missing-font answer a Find Font frame reads, for a document of + /// 2,000 point-type objects of 50 characters each and one of 20, set in five installed faces + /// and a missing family, with a folder picker: worked out on every frame as `text.fonts` and + /// `missing_fonts` (each frame before they were kept), on the first frame of a document version + /// ([`document_fonts`] with nothing kept) and on later frames. Per run, the large document + /// draws 120 frames and the small one 12,000 (so the thread's CPU clock, which advances in + /// steps of a few milliseconds, sees them), and later frames number 1,000,000; the sides + /// alternate, and the median time per frame of 7 runs is printed. + /// Run with `cargo test --release -p vectorcraft-ui-egui --lib find_font_list_timing -- --ignored --nocapture`. + #[test] + #[ignore = "manual timing probe; performance depends on machine load"] + fn find_font_list_timing() { + const KEPT: u32 = 1_000_000; + const FACES: [(&str, &str); 6] = [ + ("Inter", "Regular"), + ("Inter", "Medium"), + ("Source Sans 3", "Bold"), + ("Source Serif 4", "Regular"), + ("JetBrains Mono", "Regular"), + ("Missing Family", "Regular"), + ]; + for (objects, frames) in [(2_000, 120), (20, 12_000)] { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 2000, "height": 2000})).unwrap(); + for i in 0..objects { + let (family, style) = FACES[i % FACES.len()]; + let text: String = (0..50).map(|c| char::from(b'a' + ((i + c) % 26) as u8)).collect(); + let (x, y) = ((i % 20 * 90) as f64, (i / 20 * 18) as f64 + 20.0); + app.session.execute("text.create", &json!({"x": x, "y": y, "text": text, "font": family, "style": style})).unwrap(); + } + app.services.pick_folder = Some(Box::new(|| None)); + let every_frame = |app: &mut VectorcraftApp| { + let list = fonts(app); + let offer = crate::picks::can(app, &crate::picks::PickRequest::Folder) + && app.session.active().is_some_and(|st| !vectorcraft_engine::cmd::fontfiles::missing_fonts(&st.doc).is_empty()); + (list, offer) + }; + let expected = every_frame(&mut app); + assert!(expected.1 && expected.0.len() == FACES.len(), "{expected:?}"); + let kept = document_fonts(&mut app, true); + assert_eq!((kept.0.to_vec(), kept.1), expected, "the kept answers are the ones worked out every frame"); + // Each side's answers for one frame: the number of fonts listed and Find in Folder…. + let time = |app: &mut VectorcraftApp, frames: u32, f: &mut dyn FnMut(&mut VectorcraftApp) -> (usize, bool)| { + let (cpu, wall) = (thread_cpu_ns(), std::time::Instant::now()); + for _ in 0..frames { + assert_eq!(f(app), (FACES.len(), true)); + } + let ns = thread_cpu_ns().zip(cpu).map_or_else(|| wall.elapsed().as_nanos(), |(b, a)| b - a); + ns as f64 / f64::from(frames) / 1000.0 + }; + let (mut full, mut first, mut later) = (vec![], vec![], vec![]); + for _ in 0..7 { + full.push(time(&mut app, frames, &mut |app| { + let (list, offer) = every_frame(app); + (list.len(), offer) + })); + first.push(time(&mut app, frames, &mut |app| { + app.canvas.find_font = None; + let (list, offer) = document_fonts(app, true); + (list.len(), offer) + })); + later.push(time(&mut app, KEPT, &mut |app| { + let (list, offer) = document_fonts(app, true); + (list.len(), offer) + })); + } + let median = |v: &mut Vec| { + v.sort_by(f64::total_cmp); + v[v.len() / 2] + }; + let clock = if thread_cpu_ns().is_some() { "thread CPU time" } else { "wall-clock time" }; + eprintln!("{objects} text objects of 50 characters; {clock} per frame, median of 7 runs"); + eprintln!("worked out every frame ({frames} frames a run): {:>12.3} us {full:.3?}", median(&mut full)); + eprintln!("first frame of a version ({frames} a run): {:>12.3} us {first:.3?}", median(&mut first)); + eprintln!("later frames of the version ({KEPT} a run): {:>12.4} us {later:.4?}", median(&mut later)); + } + } } diff --git a/crates/ui-egui/src/font_menu.rs b/crates/ui-egui/src/font_menu.rs index d6c5e0d071..855bc3a3f4 100644 --- a/crates/ui-egui/src/font_menu.rs +++ b/crates/ui-egui/src/font_menu.rs @@ -518,10 +518,10 @@ impl Filters { /// The families the type in `doc` is set in, lowercase and by the name the menu lists them under /// ([`vectorcraft_text::FontDb::canonical`]): the runs of every text object in the layers, symbols, -/// patterns and graph designs, hidden, locked and masked ones included, with a composite font named -/// as such. A pattern being edited is read from its editing layer only. Each run's family is looked -/// up with its style, so a family and style split from a PostScript name (`Honoka`, `Mincho`) find -/// the installed font of that name. Styles no type uses are left out. +/// patterns, graph designs and stored scatter brushes, hidden, locked and masked ones included, with +/// a composite font named as such. A pattern being edited is read from its editing layer only. Each +/// run's family is looked up with its style, so a family and style split from a PostScript name +/// (`Honoka`, `Mincho`) find the installed font of that name. Styles no type uses are left out. fn document_families(db: &vectorcraft_text::FontDb, doc: &vectorcraft_doc::Document) -> HashSet { // Each family and style once, so a document with many runs in a few fonts looks each one up // once. @@ -549,6 +549,14 @@ fn document_families(db: &vectorcraft_text::FontDb, doc: &vectorcraft_doc::Docum for n in doc.layers.iter().map(|l| &**l).chain(doc.symbols.iter().map(|s| &*s.art)).chain(patterns).chain(designs) { vectorcraft_doc::swatches::walk_with_masks(n, &mut add); } + // A scatter brush draws copies of its art's type along a stroke; art and pattern brushes drop + // type when they bend their art. Malformed library entries are skipped. + let brushes = doc.unknown.get(vectorcraft_brush::DOC_KEY).map(vectorcraft_brush::parse_library).unwrap_or_default(); + for b in &brushes { + if let vectorcraft_brush::BrushKind::Scatter(s) = &b.kind { + vectorcraft_doc::swatches::walk_with_masks(&s.art, &mut add); + } + } named.iter().flat_map(|(f, styles)| styles.iter().map(move |s| db.canonical(f, s).0.to_lowercase())).collect() } diff --git a/crates/ui-egui/src/font_menu/tests.rs b/crates/ui-egui/src/font_menu/tests.rs index 7cf20d4210..7d930b7af5 100644 --- a/crates/ui-egui/src/font_menu/tests.rs +++ b/crates/ui-egui/src/font_menu/tests.rs @@ -1221,6 +1221,58 @@ fn the_document_filter_counts_type_in_graph_designs() { assert_eq!(names, ["inter", "jetbrains mono"]); } +/// Type in the art of a stored scatter brush counts as the document's type, as a scatter stroke +/// draws it, after a malformed library entry too. Type in an art or pattern brush's art does not, +/// as those brushes leave type out when they bend their art. +#[test] +fn the_document_filter_counts_type_in_scatter_brushes() { + let mut app = app_with_type(&["Inter"]); + let mut art = |font: &str| { + let id = app.run("text.create", serde_json::json!({"x": 20, "y": 90, "text": "Dot", "font": font})).unwrap()["id"].as_u64().unwrap(); + let node = app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).cloned().expect("the new type"); + app.run("edit.undo", serde_json::json!({})).unwrap(); + node + }; + let (scatter, bent, tiled) = (art("JetBrains Mono"), art("Source Serif 4"), art("Source Sans 3")); + let brush = |name: &str, kind| serde_json::to_value(vectorcraft_brush::Brush { name: name.into(), kind }).unwrap(); + let library = serde_json::json!([ + {"name": "Broken", "type": "scatter", "art": 7}, + brush("Art", vectorcraft_brush::BrushKind::Art(vectorcraft_brush::ArtBrush { art: bent, ..Default::default() })), + brush("Pattern", vectorcraft_brush::BrushKind::Pattern(vectorcraft_brush::PatternBrush { side: tiled, ..Default::default() })), + brush("Dots", vectorcraft_brush::BrushKind::Scatter(vectorcraft_brush::Scatter { art: scatter, ..Default::default() })), + ]); + let mut doc = (*app.session.active().unwrap().doc).clone(); + doc.unknown.insert(vectorcraft_brush::DOC_KEY.into(), library); + let db = vectorcraft_text::FontDb::global(); + let mut names: Vec<_> = super::document_families(db, &doc).into_iter().collect(); + names.sort(); + assert_eq!(names, ["inter", "jetbrains mono"]); +} + +/// A scatter brush made of type keeps its family in the Document filter after the type is deleted; +/// deleting the brush takes the family out, and undoing the deletion brings it back. +#[test] +fn the_document_filter_follows_a_scatter_brushs_edits_and_undo() { + let mut app = app_with_type(&["Inter"]); + let id = app.run("text.create", serde_json::json!({"x": 20, "y": 90, "text": "Dot", "font": "JetBrains Mono"})).unwrap()["id"].clone(); + let name = app.run("brush.new", serde_json::json!({"type": "scatter", "name": "Type Dots"})).unwrap()["name"].clone(); + app.run("edit.clear", serde_json::json!({"ids": [id]})).unwrap(); + let db = vectorcraft_text::FontDb::global(); + // One menu state throughout, so each edit has to get past the families it keeps. + let mut st = super::MenuState { document_only: true, ..Default::default() }; + let mut families = |app: &crate::VectorcraftApp| { + let used = super::used_families(db, &mut st, super::MenuLook::of(app)).expect("a document is open"); + let mut names: Vec<_> = used.iter().cloned().collect(); + names.sort(); + names + }; + assert_eq!(families(&app), ["inter", "jetbrains mono"], "the brush's type"); + app.run("brush.delete", serde_json::json!({"name": name})).unwrap(); + assert_eq!(families(&app), ["inter"], "the brush deleted"); + app.run("edit.undo", serde_json::json!({})).unwrap(); + assert_eq!(families(&app), ["inter", "jetbrains mono"], "the deletion undone"); +} + /// A run whose family and style were split from a PostScript name (as an importer without the font /// splits one) counts under the family of the installed font of that name, found with its style. #[test] diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index df5d05fc95..e43e4bf0f4 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -640,6 +640,11 @@ pub fn tr_ctx<'a>(lang: Lang, context: &str, s: &'a str) -> &'a str { lang.catalog().contextual(context, s).unwrap_or_else(|| tr(lang, s)) } +/// The translation of `s` in `lang`'s `context` rows alone, or `None` when it has no such row. +pub fn tr_ctx_row(lang: Lang, context: &str, s: &str) -> Option<&'static str> { + lang.catalog().contextual(context, s) +} + /// A name the app gives something (a default swatch's), translated where the current language has /// a `context` row for it; any other name (one the user gave) comes back as it is. pub fn t_name<'a>(context: &str, name: &'a str) -> &'a str { diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index d98672665c..59dc587ee7 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -127,6 +127,7 @@ Add to Swatches Добавяне към образци Add Used Colors Добавяне на използваните цветове Additional Plug-ins Folder Допълнителна папка за плъгини + Plug-in Instruction Budget Бюджет на инструкции за плъгини Additional Fonts Folder Допълнителна папка за шрифтове Adjust Adjoining Width Points Регулиране на прилежащите точки за ширина Incoming Входяща @@ -790,6 +791,8 @@ font-technology Variable Променливи Delete Artboard Изтриване на работна област Delete Artboards Изтриване на работни области Delete Brush Изтриване на четка + Delete Color Изтриване на цвят + Restore Generated Table Възстановяване на генерираната таблица Delete Character Style Изтриване на стил за знаци Delete Empty Artboards Изтриване на празни работни области Delete Freeform Point Изтриване на свободна точка @@ -858,6 +861,7 @@ font-technology Variable Променливи Direct Selection Tool Инструмент „Директен избор“ Direction Handles Маркери за посока Disable Auto Add/Delete Изключване на автоматично добавяне/изтриване + Interpolate Control Points When Moving Anchors Интерполиране на маркерите за посока при преместване на опорни точки Disable Opacity Mask Изключване на маска за непрозрачност Discard Отхвърляне Discard Empty Type Отхвърляне на празен текст @@ -2169,6 +2173,7 @@ font-technology Variable Променливи Scatter: Разпръскване: Rotation: Завъртане: Rotation relative to: Завъртане спрямо: + Hue Jitter: Вариация на оттенъка: Brush Scale Options Опции за мащабиране на четката Scale Proportionately Мащабиране пропорционално Stretch to Fit Stroke Length Разтягане за запълване дължината на щриха @@ -2205,6 +2210,7 @@ font-technology Variable Променливи Black becomes the stroke color and white stays white. Other colors become tints of the stroke color by their lightness. Черното става цвят на щриха, а бялото остава бяло. Другите цветове стават оттенъци на цвета на щриха и колкото по-светъл е един цвят, толкова по-светъл е оттенъкът му. Black and white stay as they are. Dark colors become shades of the stroke color and light colors become tints of it. Черното остава черно, а бялото остава бяло. Другите цветове стават тъмни нюанси на цвета на щриха, когато са тъмни, и негови оттенъци, когато са светли. The key color becomes the stroke color. The other colors shift their hue by the same amount and keep their saturation and brightness. Основният цвят става цвят на щриха. Другите цветове се завъртат по цветовото колело толкова, колкото и основният цвят, и запазват насищането и яркостта си. + Roundness Закръгленост Roundness: Закръгленост: Fixed Фиксирано Pressure Натиск @@ -2634,6 +2640,7 @@ font-technology Variable Променливи Line Properties: Свойства на линията: Line Length: Дължина на линията: Line Angle: Ъгъл на линията: + Constrain Pie Angle Запазване на ъгъла на сектора Polygon Tool Инструмент „Многоъгълник“ Portrait Портретна Power Saving (integrated) Пестене на енергия (интегрирано) @@ -2793,6 +2800,7 @@ digits Malayalam Малаялам Real World: Реален свят: Real-time Drawing and Editing Чертане и редактиране в реално време Use Monitor Profile for Canvas Използване на профила на монитора за платното + Refresh Monitor Profile Обновяване на профила на монитора The canvas is drawn in sRGB. Платното се изобразява в sRGB. Canvas display profile: Профил на дисплея за платното: The system matches the window to the display's colors. Системата съгласува цветовете на прозореца с дисплея. @@ -3053,6 +3061,7 @@ digits Malayalam Малаялам The mouse wheel with Cmd/Ctrl held scrolls the canvas sideways. Колелцето на мишката с натиснат Cmd/Ctrl превърта платното настрани. Dragging sideways on a numeric field's label changes the field's value. Влаченето настрани върху етикета на числово поле променя стойността на полето. A two-finger rotate gesture on a trackpad rotates the canvas view. Жест за завъртане с два пръста върху тъчпад завърта изгледа на платното. + When you move anchor points, each curve with one moved end keeps its shape relative to its ends. Когато премествате котвени точки, всяка крива с една преместена крайна точка запазва формата си спрямо краищата си. Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Задържането на клавишната комбинация на инструмент го избира, докато я пуснете, а след това отново се избира предишният инструмент. Shows the bounding box while you move the selection or draw a shape. Показва ограничителната рамка, докато премествате селекцията или рисувате форма. Create Trim Marks draws Japanese-style marks instead of Roman ones. „Създаване на режещи знаци“ рисува знаци в японски стил вместо в римски. @@ -3350,6 +3359,9 @@ digits Malayalam Малаялам Search commands, tools, panels and effects… Търсене на команди, инструменти, панели и ефекти… No commands match Няма съвпадащи команди {pos} of {total}: {name} {pos} от {total}: {name} + No menu item Няма елемент в менюто + Toolbar Лента с инструменти + {toolbar}, in the {tool} group {toolbar}, в групата на {tool} @plural {n} result|{n} results {n} резултат|{n} резултата @plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} от {n} резултат. Продължете да пишете, за да ги стесните.|{shown} от {n} резултата. Продължете да пишете, за да ги стесните. Recent Commands Последни команди @@ -4395,6 +4407,7 @@ imageTrace Outline Контур Bevel Фаска Offset Отстъп Axis Ос + Axis Angle Ъгъл на оста axis Horizontal Хоризонтално axis Vertical Вертикално axis Both И двете @@ -4667,6 +4680,7 @@ axis Both И двете @msg choose a folder to export to изберете папка за експортиране @msg choose a location for the package изберете местоположение за пакета @msg clipboard is empty клипбордът е празен +@msg colorTable.deleted: at least one color has to stay in the color table colorTable.deleted: поне един цвят трябва да остане в цветовата таблица @msg colorTable.{what}: `{h}` is not a colour such as "#ff8800" colorTable.{what}: `{h}` не е цвят като "#ff8800" @msg colorTable.{what}: at most {MAX_TABLE} colours colorTable.{what}: най-много {MAX_TABLE} цвята @msg command `{0}` is not available right now: {1} команда `{0}` не е налична в момента: {1} @@ -5526,6 +5540,7 @@ lighting Light Светлина Cove Извивка Depth Дълбочина Front Отпред + Side Страна Isometric Bottom Изометрично отдолу Isometric Left Изометрично отляво Isometric Right Изометрично отдясно @@ -6989,6 +7004,14 @@ breakText Glyphs Глифи Remove Gaps Премахване на разстоянията @msg that makes too many pieces (at most 100000): make the dashes longer така се получават твърде много части (най-много 100000): удължете тиретата @msg select paths, or segments, to divide изберете пътища или сегменти за разделяне +# Path Precision Tools add-on: Smooth Bridge. + Smooth Bridge… Плавен мост… + Smooth Bridge Плавен мост + Keep Originals Запазване на оригиналите +@msg select two circles to bridge изберете два кръга за свързване +@msg one circle is inside the other единият кръг е вътре в другия +@msg the circles are too far apart for this radius: raise the radius кръговете са твърде далеч един от друг за този радиус: увеличете радиуса +@msg the circles are too far apart for this radius кръговете са твърде далеч един от друг за този радиус # Path Precision Tools add-on: Common Tangents. Common Tangents… Общи допирателни… Common Tangents Общи допирателни diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 1de5a3a44f..8c1e89f56c 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -1710,6 +1710,7 @@ digits Malayalam Malajalam Underline Podvučeno Vertical Scale % Okomita skala % Axis Osa + Axis Angle Ugao ose ICF Top/Right ICF vrh/desno ICF Bottom/Left ICF dno/lijevo Show Font Height Options Prikaži opcije visine fonta @@ -2369,6 +2370,7 @@ digits Malayalam Malajalam Line Properties: Svojstva linije: Line Length: Dužina linije: Line Angle: Ugao linije: + Constrain Pie Angle Zadrži ugao pite Rectangle Properties: Svojstva pravougaonika: Shape Properties: Svojstva oblika: Shape Properties Svojstva oblika @@ -2410,6 +2412,7 @@ digits Malayalam Malajalam Scatter: Raspršenost: Rotation: Rotacija: Rotation relative to: Rotacija u odnosu na: + Hue Jitter: Variranje nijanse: Brush Scale Options Opcije skale četkice Scale Proportionately Skaliraj proporcionalno Stretch to Fit Stroke Length Razvuci da stane u dužinu poteza @@ -2448,6 +2451,7 @@ digits Malayalam Malajalam Size: Veličina: Calligraphic Brush Options Opcije kaligrafske četkice Bristle Brush Options Opcije četkice s čekinjama + Roundness Zaobljenost Roundness: Zaobljenost: Shape: Oblik: Bristle Length: Dužina čekinja: @@ -3482,6 +3486,8 @@ theme Appearance Izgled Current Brush Trenutna četkica Current Symbol Trenutni simbol Delete Brush Izbriši četkicu + Delete Color Izbriši boju + Restore Generated Table Vrati generisanu tabelu Delete Symbol Izbriši simbol Delete the selected symbol? Izbrisati odabrani simbol? Delete the selected symbols? Izbrisati odabrane simbole? @@ -3938,6 +3944,7 @@ theme Appearance Izgled 90° & 45° Angles Uglovi od 90° i 45° 90° Angles Uglovi od 90° Additional Plug-ins Folder Dodatni folder dodataka + Plug-in Instruction Budget Budžet instrukcija za dodatke Additional Fonts Folder Dodatni folder fontova Alignment Guides Vodilice za poravnanje Anchor Points, Handle, and Bounding Box Display Prikaz sidrenih tačaka, ručki i graničnog okvira @@ -3964,6 +3971,7 @@ theme Appearance Izgled Data Recovery Oporavak podataka Default Language Zadani jezik Disable Auto Add/Delete Onemogući automatsko dodavanje/brisanje + Interpolate Control Points When Moving Anchors Interpoliraj ručke smjera pri pomjeranju sidrenih tačaka Display All Blacks Accurately Prikaži sve crne tačno Display All Blacks as Rich Black Prikaži sve crne kao bogatu crnu Display Bitmaps as Anti-aliased Images in Pixel Preview Prikaži bitmape kao slike sa zaglađenim ivicama u pregledu piksela @@ -4064,6 +4072,7 @@ theme Appearance Izgled Printing / Exporting Štampanje / izvoz Real-time Drawing and Editing Crtanje i uređivanje u stvarnom vremenu Use Monitor Profile for Canvas Koristi profil monitora za platno + Refresh Monitor Profile Osvježi profil monitora The canvas is drawn in sRGB. Platno se iscrtava u sRGB-u. Canvas display profile: Profil ekrana za platno: The system matches the window to the display's colors. Sistem prilagođava boje prozora ekranu. @@ -4471,6 +4480,9 @@ font-technology Variable Varijabilni Search commands, tools, panels and effects… Pretraži naredbe, alate, panele i efekte… No commands match Nijedna naredba se ne podudara {pos} of {total}: {name} {pos} od {total}: {name} + No menu item Nema stavke menija + Toolbar Traka s alatima + {toolbar}, in the {tool} group {toolbar}, u grupi {tool} @plural {n} result|{n} results {n} rezultat|{n} rezultata|{n} rezultata @plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} od {n} rezultata. Nastavite kucati da ih suzite.|{shown} od {n} rezultata. Nastavite kucati da ih suzite.|{shown} od {n} rezultata. Nastavite kucati da ih suzite. Recent Commands Nedavne naredbe @@ -4507,6 +4519,7 @@ font-technology Variable Varijabilni The mouse wheel with Cmd/Ctrl held scrolls the canvas sideways. Točkić miša uz pritisnut Cmd/Ctrl pomjera platno u stranu. Dragging sideways on a numeric field's label changes the field's value. Prevlačenje u stranu po oznaci brojčanog polja mijenja vrijednost polja. A two-finger rotate gesture on a trackpad rotates the canvas view. Pokret rotacije s dva prsta na dodirnoj podlozi rotira prikaz platna. + When you move anchor points, each curve with one moved end keeps its shape relative to its ends. Kada pomjerate sidrene tačke, svaka kriva s jednim pomjerenim krajem zadržava svoj oblik u odnosu na svoje krajeve. Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Držanje prečice alata bira taj alat dok je ne pustite, a zatim se ponovo bira prethodni alat. Shows the bounding box while you move the selection or draw a shape. Prikazuje granični okvir dok pomjerate odabir ili crtate oblik. Create Trim Marks draws Japanese-style marks instead of Roman ones. Kreiraj oznake za obrezivanje crta oznake u japanskom stilu umjesto rimskih. @@ -5075,6 +5088,7 @@ imageTrace Outline Obris @msg choose a folder to export to odaberite folder za izvoz @msg choose a location for the package odaberite lokaciju za paket @msg clipboard is empty međuspremnik je prazan +@msg colorTable.deleted: at least one color has to stay in the color table colorTable.deleted: barem jedna boja mora ostati u tabeli boja @msg colorTable.{what}: `{h}` is not a colour such as "#ff8800" colorTable.{what}: `{h}` nije boja poput "#ff8800" @msg colorTable.{what}: at most {MAX_TABLE} colours colorTable.{what}: najviše {MAX_TABLE} boja @msg command `{0}` is not available right now: {1} naredba `{0}` trenutno nije dostupna: {1} @@ -6046,6 +6060,7 @@ mark-style Japanese Japanski Cove Udubina Depth Dubina Front Prednja strana + Side Bočna strana Isometric Bottom Izometrijsko dno Isometric Left Izometrijski lijevo Isometric Right Izometrijski desno @@ -7038,6 +7053,14 @@ shape Open Otvoren Remove Gaps Ukloni razmake @msg that makes too many pieces (at most 100000): make the dashes longer to daje previše dijelova (najviše 100000): produžite crtice @msg select paths, or segments, to divide odaberite putanje ili segmente za dijeljenje +# Path Precision Tools add-on: Smooth Bridge. + Smooth Bridge… Glatki most… + Smooth Bridge Glatki most + Keep Originals Zadrži originale +@msg select two circles to bridge odaberite dva kruga za premošćavanje +@msg one circle is inside the other jedan krug je unutar drugog +@msg the circles are too far apart for this radius: raise the radius krugovi su predaleko jedan od drugog za ovaj radijus: povećajte radijus +@msg the circles are too far apart for this radius krugovi su predaleko jedan od drugog za ovaj radijus # Path Precision Tools add-on: Common Tangents. Common Tangents… Zajedničke tangente… Common Tangents Zajedničke tangente diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 70ccfd1cb6..604bbb9028 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -223,6 +223,7 @@ Add Used Colors Afegeix els colors utilitzats Additional Fonts Folder Carpeta addicional de tipus de lletra Additional Plug-ins Folder Carpeta addicional de complements + Plug-in Instruction Budget Pressupost d’instruccions dels complements Adjust Adjoining Width Points Ajusta els punts d’amplada contigus Incoming Entrant Outgoing Sortint @@ -439,6 +440,7 @@ antiAlias Sharp Nítid Average… Mitjana… Away from the Line Allunyat de la línia Axis Eix + Axis Angle Angle de l’eix Axis side Costat de l’eix Axis: Eix: B4 B4 @@ -1152,6 +1154,8 @@ antiAlias Sharp Nítid Delete Artboard Suprimeix el tauler Delete Artboards Suprimeix els taulers Delete Brush Suprimeix el pinzell + Delete Color Suprimeix el color + Restore Generated Table Restaura la taula generada Delete Character Style Suprimeix l’estil de caràcter Delete Data Set Suprimeix el conjunt de dades Delete Data Sets Suprimeix els conjunts de dades @@ -1261,6 +1265,7 @@ antiAlias Sharp Nítid Direction: Direcció: Directives Directrius Disable Auto Add/Delete Desactiva l’addició i la supressió automàtiques + Interpolate Control Points When Moving Anchors Interpola les manetes de direcció en moure punts d’ancoratge Disable Opacity Mask Desactiva la màscara d’opacitat Discard Descarta Discard Empty Type Descarta el text buit @@ -1887,6 +1892,7 @@ digits Malayalam Malaiàlam from the format's public description de la descripció pública del format from your earlier imports de les importacions anteriors Front Davant + Side Lateral Frosted Glaçat Full Document Document complet Full Justify Justificació completa @@ -3410,6 +3416,7 @@ digits Malayalam Malaiàlam Line Properties: Propietats de la línia: Line Length: Longitud de la línia: Line Angle: Angle de la línia: + Constrain Pie Angle Restringeix l’angle del sector Polygon Tool Eina de polígon Portrait Vertical Portrait (flipped) Vertical (invertit) @@ -3608,6 +3615,9 @@ digits Malayalam Malaiàlam Real World: Món real: Real-time Drawing and Editing Dibuix i edició en temps real Use Monitor Profile for Canvas Utilitza el perfil del monitor per al llenç + Refresh Monitor Profile Actualitza el perfil del monitor +@msg turn on Use Monitor Profile for Canvas first activeu primer «Utilitza el perfil del monitor per al llenç» +@msg this build doesn't read display profiles aquesta versió no llegeix perfils de pantalla The canvas is drawn in sRGB. El llenç es dibuixa en sRGB. Canvas display profile: Perfil de pantalla del llenç: The system matches the window to the display's colors. El sistema ajusta la finestra als colors de la pantalla. @@ -3893,6 +3903,7 @@ digits Malayalam Malaiàlam The mouse wheel with Cmd/Ctrl held scrolls the canvas sideways. La roda del ratolí amb Cmd/Ctrl premut desplaça el llenç en horitzontal. Dragging sideways on a numeric field's label changes the field's value. Arrossegar en horitzontal sobre l’etiqueta d’un camp numèric canvia el valor del camp. A two-finger rotate gesture on a trackpad rotates the canvas view. Un gest de rotació amb dos dits al trackpad gira la vista del llenç. + When you move anchor points, each curve with one moved end keeps its shape relative to its ends. Quan moveu punts d’ancoratge, cada corba amb un extrem desplaçat conserva la forma respecte dels seus extrems. Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Mantenir premuda la drecera d’una eina la tria fins que la deixeu anar, i després es torna a triar l’eina anterior. Shows the bounding box while you move the selection or draw a shape. Mostra el quadre delimitador mentre moveu la selecció o dibuixeu una forma. Create Trim Marks draws Japanese-style marks instead of Roman ones. Crea marques de retall dibuixa marques d’estil japonès en lloc de romanes. @@ -4033,6 +4044,7 @@ digits Malayalam Malaiàlam Rotate… Gira… Rotation Rotació Rotation relative to: Rotació relativa a: + Hue Jitter: Variació del to: Rotation X Rotació X Rotation Y Rotació Y Rotation Z Rotació Z @@ -4053,6 +4065,7 @@ digits Malayalam Malaiàlam Rounded Rectangle Rectangle arrodonit Rounded Rectangle Tool Eina de rectangle arrodonit Rounded Rectangle… Rectangle arrodonit… + Roundness Arrodoniment Roundness: Arrodoniment: Row Size: Mida de la fila: Rows Files @@ -4289,6 +4302,9 @@ digits Malayalam Malaiàlam Search commands, tools, panels and effects… Cerca ordres, eines, panells i efectes… No commands match Cap ordre coincideix {pos} of {total}: {name} {pos} de {total}: {name} + No menu item Cap element de menú + Toolbar Barra d’eines + {toolbar}, in the {tool} group {toolbar}, al grup {tool} @plural {n} result|{n} results {n} resultat|{n} resultats @plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} de {n} resultat. Continueu escrivint per reduir-los.|{shown} de {n} resultats. Continueu escrivint per reduir-los. Recent Commands Ordres recents @@ -5792,6 +5808,7 @@ digits Malayalam Malaiàlam @msg a linked JavaScript file is outside the read roots un fitxer JavaScript enllaçat és fora de les arrels de lectura @msg a linked image file is outside the read roots un fitxer d’imatge enllaçat és fora de les arrels de lectura @msg a linked file's export folder is outside the read roots la carpeta d’exportació d’un fitxer enllaçat és fora de les arrels de lectura +@msg a linked file's editing data can't be read to check it against the read roots no es poden llegir les dades d’edició d’un fitxer enllaçat per comprovar-les amb les arrels de lectura @msg the library's file is outside the read roots el fitxer de la biblioteca és fora de les arrels de lectura @msg {file} names more than one linked JavaScript file {file} correspon a més d’un fitxer JavaScript enllaçat @msg automation path rejected: outside the write root {root}: {path} camí d’automatització rebutjat: fora de l’arrel d’escriptura {root}: {path} @@ -5845,6 +5862,7 @@ digits Malayalam Malaiàlam @msg Choose two nonzero angle arms Trieu dos braços d’angle no nuls @msg clipboard is empty el porta-retalls és buit @msg closing needs three anchors el tancament necessita tres punts d’ancoratge +@msg colorTable.deleted: at least one color has to stay in the color table colorTable.deleted: almenys un color ha de quedar a la taula de colors @msg colorTable.{what}: `{h}` is not a colour such as "#ff8800" colorTable.{what}: `{h}` no és un color com "#ff8800" @msg colorTable.{what}: at most {MAX_TABLE} colours colorTable.{what}: com a màxim {MAX_TABLE} colors @msg column docks a set as a dock column, with no anchor or icon column acobla un conjunt com a columna d’acoblament, sense àncora ni icona @@ -6038,6 +6056,14 @@ liquify-list-end {0}, {1} {0} i {1} @msg is a prompt's answer, whose `value` must be a string or null és la resposta d'un prompt, i el seu `value` ha de ser una cadena o null @msg must have `kind` alert, confirm or prompt ha de tenir `kind` alert, confirm o prompt @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` només és per a una execució sense ningú a qui preguntar: a l'aplicació, la persona respon cada quadre de diàleg +@msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` ha de ser un nombre enter d’1 a {_1} +@msg `args{place}` is nested more than 64 levels deep `args{place}` està imbricat en més de 64 nivells +@msg `args` must be an object `args` ha de ser un objecte +@msg `args` is larger than 1 MiB `args` ocupa més d'1 MiB +@msg `path` is empty `path` és buit +@msg `installed` takes a `path`, not a `source` `installed` admet un `path`, no un `source` +@msg `path` must name a .js or .jsx file `path` ha d’indicar un fitxer .js o .jsx +@msg give exactly one of `path` and `source` indiqueu exactament un de `path` i `source` @msg Running a script S'està executant un script @msg Copied the script report S’ha copiat l’informe de l’script @msg Script file access denied: {path} S’ha denegat l’accés de l’script als fitxers: {path} @@ -6267,6 +6293,12 @@ liquify-list-end {0}, {1} {0} i {1} @msg New Window isn't available yet: a document opens in one window Finestra nova encara no està disponible: un document s’obre en una sola finestra @msg no active document no hi ha cap document actiu @msg no active perspective plane no hi ha cap pla de perspectiva actiu +@msg the perspective grid is hidden la quadrícula de perspectiva està oculta +@msg Automatic Plane Positioning is off: turn on anchorPoint or gridlineIntersection (perspective.widget.options) El posicionament automàtic del pla està desactivat: activeu anchorPoint o gridlineIntersection (perspective.widget.options) +@msg anchorPoint must be true or false anchorPoint ha de ser true o false +@msg gridlineIntersection must be true or false gridlineIntersection ha de ser true o false +@msg tolerance must be 0 or more tolerance ha de ser 0 o més +@msg give `at` or `clear`, not both indiqueu `at` o `clear`, no tots dos @msg no anchor points selected no hi ha cap punt d’ancoratge seleccionat @msg `points` must be two or three [x, y] pairs of numbers `points` han de ser dos o tres parells de nombres [x, y] @msg direct-select two or three anchor points, or give `points` seleccioneu directament dos o tres punts d’ancoratge o indiqueu `points` @@ -6718,7 +6750,7 @@ liquify-list-end {0}, {1} {0} i {1} @msg each of `{GRAPHICS}` must be an object cada element de `{GRAPHICS}` ha de ser un objecte @msg `{GRAPHICS}` entries take symbol, face, x, y, scale and rotation, not `{k}` les entrades de `{GRAPHICS}` admeten symbol, face, x, y, scale i rotation, no `{k}` @msg each of `{GRAPHICS}` needs `symbol`, the name of a symbol cada element de `{GRAPHICS}` necessita `symbol`, el nom d’un símbol -@msg `{GRAPHICS}` face must be front or back face de `{GRAPHICS}` ha de ser front o back +@msg `{GRAPHICS}` face must be front, back or side face de `{GRAPHICS}` ha de ser front, back o side @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} {key} de `{GRAPHICS}` ha de ser un nombre de {lo} a {hi} @msg `{GRAPHICS}` must be an array `{GRAPHICS}` ha de ser una matriu @msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types Els gràfics s’apliquen als tipus d’objecte Pla, Extrusió, Revolució i Infla @@ -7042,6 +7074,8 @@ variable-list-end {0}, {1} {0} i {1} @msg {path}: {e} {path}: {e} @msg {status} ({e}) {status} ({e}) @msg {tool} isn't in a toolbar group of several tools {tool} no forma part d’un grup de diverses eines a la barra d’eines +@msg Presentation Mode hides the toolbars: change the screen mode to show them el Mode de presentació amaga les barres d’eines: canvieu el mode de pantalla per mostrar-les +@msg Tab has hidden the toolbars: press Tab to show them Tab ha amagat les barres d’eines: premeu Tab per mostrar-les @msg “{_1}” asks for a heavy budget (each run up to {minutes} minutes and {times} times the usual instructions): a person has to approve it in the desktop app, or pass `allowHeavy: true` in a session started with --allow-plugin-grants «{_1}» demana un pressupost elevat (cada execució fins a {minutes} minuts i {times} vegades les instruccions habituals): una persona l’ha d’aprovar a l’aplicació d’escriptori, o passa `allowHeavy: true` en una sessió iniciada amb --allow-plugin-grants # Plug-in host messages: manifests, modules, runs and plug-in output @msg `name` must be 1-64 printable characters `name` ha de tenir 1-64 caràcters imprimibles @@ -7760,6 +7794,14 @@ breakText Glyphs Glifs Remove Gaps Elimina les separacions @msg that makes too many pieces (at most 100000): make the dashes longer això fa massa trossos (com a màxim 100000): allargueu els guions @msg select paths, or segments, to divide seleccioneu camins o segments per dividir +# Path Precision Tools add-on: Smooth Bridge. + Smooth Bridge… Pont suau… + Smooth Bridge Pont suau + Keep Originals Conserva els originals +@msg select two circles to bridge seleccioneu dos cercles per unir-los +@msg one circle is inside the other un cercle és dins de l’altre +@msg the circles are too far apart for this radius: raise the radius els cercles estan massa separats per a aquest radi: augmenteu el radi +@msg the circles are too far apart for this radius els cercles estan massa separats per a aquest radi # Path Precision Tools add-on: Common Tangents. Common Tangents… Tangents comunes… Common Tangents Tangents comunes diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index bf9621834f..941b4da68a 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -1779,6 +1779,7 @@ digits Malayalam Malajálamské Underline Podtržení Vertical Scale % Svislá změna velikosti % Axis Osa + Axis Angle Úhel osy ICF Top/Right ICF horní/pravý ICF Bottom/Left ICF dolní/levý Show Font Height Options Zobrazit možnosti výšky písma @@ -2440,6 +2441,7 @@ digits Malayalam Malajálamské Line Properties: Vlastnosti čáry: Line Length: Délka čáry: Line Angle: Úhel čáry: + Constrain Pie Angle Zachovat úhel výseče Rectangle Properties: Vlastnosti obdélníku: Shape Properties: Vlastnosti tvaru: Shape Properties Vlastnosti tvaru @@ -2483,6 +2485,7 @@ digits Malayalam Malajálamské Scatter: Rozptyl: Rotation: Otočení: Rotation relative to: Otočení vzhledem k: + Hue Jitter: Kolísání odstínu: Brush Scale Options Možnosti velikosti štětce Scale Proportionately Měnit velikost proporcionálně Stretch to Fit Stroke Length Roztáhnout na délku tahu @@ -2521,6 +2524,7 @@ digits Malayalam Malajálamské Size: Velikost: Calligraphic Brush Options Možnosti kaligrafického štětce Bristle Brush Options Možnosti štětinového štětce + Roundness Zakulacení Roundness: Zakulacení: Shape: Tvar: Bristle Length: Délka štětin: @@ -3582,6 +3586,8 @@ theme Appearance Motiv Current Brush Aktuální štětec Current Symbol Aktuální symbol Delete Brush Odstranit štětec + Delete Color Odstranit barvu + Restore Generated Table Obnovit vygenerovanou tabulku Delete Symbol Odstranit symbol Delete the selected symbol? Odstranit vybraný symbol? Delete the selected symbols? Odstranit vybrané symboly? @@ -4042,6 +4048,7 @@ theme Appearance Motiv 90° & 45° Angles Úhly 90° a 45° 90° Angles Úhly 90° Additional Plug-ins Folder Další složka zásuvných modulů + Plug-in Instruction Budget Rozpočet instrukcí zásuvných modulů Additional Fonts Folder Další složka písem Alignment Guides Vodítka zarovnání Anchor Points, Handle, and Bounding Box Display Zobrazení kotevních bodů, úchytů a ohraničovacího rámečku @@ -4068,6 +4075,7 @@ theme Appearance Motiv Data Recovery Obnovení dat Default Language Výchozí jazyk Disable Auto Add/Delete Vypnout automatické přidávání/odstraňování + Interpolate Control Points When Moving Anchors Interpolovat směrové úchyty při přesouvání kotevních bodů Display All Blacks Accurately Zobrazovat všechny černé přesně Display All Blacks as Rich Black Zobrazovat všechny černé jako sytou černou Display Bitmaps as Anti-aliased Images in Pixel Preview Zobrazovat bitmapy v náhledu obrazových bodů vyhlazené @@ -4170,6 +4178,9 @@ theme Appearance Motiv Printing / Exporting Tisk / export Real-time Drawing and Editing Kreslení a úpravy v reálném čase Use Monitor Profile for Canvas Použít profil monitoru pro plátno + Refresh Monitor Profile Obnovit profil monitoru +@msg turn on Use Monitor Profile for Canvas first nejprve zapněte „Použít profil monitoru pro plátno“ +@msg this build doesn't read display profiles tato verze nečte profily displejů The canvas is drawn in sRGB. Plátno se vykresluje v sRGB. Canvas display profile: Profil displeje pro plátno: The system matches the window to the display's colors. Systém přizpůsobuje okno barvám displeje. @@ -4577,6 +4588,9 @@ font-technology Variable Variabilní Search commands, tools, panels and effects… Hledat příkazy, nástroje, panely a efekty… No commands match Žádný příkaz neodpovídá {pos} of {total}: {name} {pos} z {total}: {name} + No menu item Žádná položka nabídky + Toolbar Panel nástrojů + {toolbar}, in the {tool} group {toolbar}, ve skupině {tool} @plural {n} result|{n} results {n} výsledek|{n} výsledky|{n} výsledků @plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} z {n} výsledku. Pište dál a výsledky se zúží.|{shown} z {n} výsledků. Pište dál a výsledky se zúží.|{shown} z {n} výsledků. Pište dál a výsledky se zúží. Recent Commands Nedávné příkazy @@ -4613,6 +4627,7 @@ font-technology Variable Variabilní The mouse wheel with Cmd/Ctrl held scrolls the canvas sideways. Kolečko myši s podrženou klávesou Cmd/Ctrl posouvá plátno do stran. Dragging sideways on a numeric field's label changes the field's value. Tažení do stran po popisku číselného pole mění hodnotu pole. A two-finger rotate gesture on a trackpad rotates the canvas view. Gesto otočení dvěma prsty na trackpadu otáčí zobrazení plátna. + When you move anchor points, each curve with one moved end keeps its shape relative to its ends. Když přesouváte kotvové body, každá křivka s jedním přesunutým koncem si zachová tvar vůči svým koncům. Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Podržení zkratky nástroje vybere nástroj, dokud ji nepustíte, a pak se znovu vybere předchozí nástroj. Shows the bounding box while you move the selection or draw a shape. Zobrazí ohraničovací rámeček, když přesouváte výběr nebo kreslíte tvar. Create Trim Marks draws Japanese-style marks instead of Roman ones. Vytvořit značky ořezu nakreslí značky v japonském stylu místo římských. @@ -5097,6 +5112,14 @@ liquify-list-end {0}, {1} {0} a {1} @msg the main script engine is new for each run and is never kept, so it cannot be dropped hlavní skriptovací jádro je pro každý běh nové a nikdy se neuchovává, proto je nelze zahodit @msg there is no script engine named {name} skriptovací jádro s názvem {name} neexistuje @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` je jen pro běh, kde se nemá koho zeptat: v aplikaci odpovídá na každý dialog uživatel +@msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` musí být celé číslo od 1 do {_1} +@msg `args{place}` is nested more than 64 levels deep `args{place}` je vnořen hlouběji než 64 úrovní +@msg `args` must be an object `args` musí být objekt +@msg `args` is larger than 1 MiB `args` je větší než 1 MiB +@msg `path` is empty `path` je prázdný +@msg `installed` takes a `path`, not a `source` `installed` přijímá `path`, ne `source` +@msg `path` must name a .js or .jsx file `path` musí označovat soubor .js nebo .jsx +@msg give exactly one of `path` and `source` zadejte právě jedno z `path` a `source` @msg Running a script Běží skript @msg Copied the script report Zpráva o skriptu zkopírována @msg Script file access denied: {path} Přístup skriptu k souborům byl odepřen: {path} @@ -5360,6 +5383,7 @@ liquify-list-end {0}, {1} {0} a {1} @msg choose a folder to export to zvolte složku pro export @msg choose a location for the package zvolte umístění balíčku @msg clipboard is empty schránka je prázdná +@msg colorTable.deleted: at least one color has to stay in the color table colorTable.deleted: v tabulce barev musí zůstat alespoň jedna barva @msg colorTable.{what}: `{h}` is not a colour such as "#ff8800" colorTable.{what}: `{h}` není barva jako "#ff8800" @msg colorTable.{what}: at most {MAX_TABLE} colours colorTable.{what}: nejvýše {MAX_TABLE} barev @msg command `{0}` is not available right now: {1} příkaz `{0}` nyní není k dispozici: {1} @@ -5427,6 +5451,12 @@ liquify-list-end {0}, {1} {0} a {1} @msg no PNG encoder chybí kodér PNG @msg no active document žádný aktivní dokument @msg no active perspective plane žádná aktivní perspektivní rovina +@msg the perspective grid is hidden perspektivní mřížka je skrytá +@msg Automatic Plane Positioning is off: turn on anchorPoint or gridlineIntersection (perspective.widget.options) Automatické umístění roviny je vypnuté: zapněte anchorPoint nebo gridlineIntersection (perspective.widget.options) +@msg anchorPoint must be true or false anchorPoint musí být true nebo false +@msg gridlineIntersection must be true or false gridlineIntersection musí být true nebo false +@msg tolerance must be 0 or more tolerance musí být 0 nebo více +@msg give `at` or `clear`, not both zadejte `at` nebo `clear`, ne obojí @msg no anchor points selected nejsou vybrány žádné kotevní body @msg `points` must be two or three [x, y] pairs of numbers `points` musí být dvě nebo tři dvojice čísel [x, y] @msg direct-select two or three anchor points, or give `points` vyberte přímým výběrem dva nebo tři kotevní body, nebo zadejte `points` @@ -5898,6 +5928,8 @@ variable-list-end {0}, {1} {0} a {1} @msg Reload the page to go on (changes not saved yet may be lost). Pokračujte obnovením stránky (dosud neuložené změny se mohou ztratit). @msg tool (a tool id) is required tool (ID nástroje) je povinný @msg {tool} isn't in a toolbar group of several tools {tool} není ve skupině panelu nástrojů s více nástroji +@msg Presentation Mode hides the toolbars: change the screen mode to show them Režim prezentace skrývá panely nástrojů: zobrazíte je změnou režimu obrazovky +@msg Tab has hidden the toolbars: press Tab to show them Klávesa Tab skryla panely nástrojů: zobrazíte je stisknutím klávesy Tab @msg onto must name a panel floating in another group onto musí určovat panel plovoucí v jiné skupině @msg below and above must name a panel floating in another group below a above musí určovat panel plovoucí v jiné skupině @msg give only one of onto, below and above zadejte jen jedno z onto, below a above @@ -5988,6 +6020,7 @@ variable-list-end {0}, {1} {0} a {1} @msg a linked JavaScript file is outside the read roots propojený soubor JavaScript je mimo kořeny pro čtení @msg a linked image file is outside the read roots propojený soubor obrázku je mimo kořeny pro čtení @msg a linked file's export folder is outside the read roots exportní složka propojeného souboru je mimo kořeny pro čtení +@msg a linked file's editing data can't be read to check it against the read roots editační data propojeného souboru nelze přečíst a ověřit vůči kořenům pro čtení @msg automation path rejected: outside the write root {root}: {path} cesta automatizace odmítnuta: mimo kořen pro zápis {root}: {path} @msg automation path rejected: outside the write roots {roots}: {path} cesta automatizace odmítnuta: mimo kořeny pro zápis {roots}: {path} @msg automation path rejected: path is empty cesta automatizace odmítnuta: cesta je prázdná @@ -6417,6 +6450,7 @@ mark-style Japanese Japonské Cove Žlábek Depth Hloubka Front Zepředu + Side Z boku Isometric Bottom Izometricky zdola Isometric Left Izometricky zleva Isometric Right Izometricky zprava @@ -6511,7 +6545,7 @@ mark-style Japanese Japonské @msg each of `{GRAPHICS}` must be an object každá položka `{GRAPHICS}` musí být objekt @msg `{GRAPHICS}` entries take symbol, face, x, y, scale and rotation, not `{k}` položky `{GRAPHICS}` přijímají symbol, face, x, y, scale a rotation, ne `{k}` @msg each of `{GRAPHICS}` needs `symbol`, the name of a symbol každá položka `{GRAPHICS}` potřebuje `symbol`, název symbolu -@msg `{GRAPHICS}` face must be front or back face v `{GRAPHICS}` musí být front nebo back +@msg `{GRAPHICS}` face must be front, back or side face v `{GRAPHICS}` musí být front, back nebo side @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} {key} v `{GRAPHICS}` musí být číslo od {lo} do {hi} @msg `{GRAPHICS}` must be an array `{GRAPHICS}` musí být pole @msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types Grafika se mapuje na typy objektu Rovina, Vysunutí, Rotační těleso a Nafouknutí @@ -7745,6 +7779,14 @@ breakText Glyphs Glyfy Remove Gaps Odstranit mezery @msg that makes too many pieces (at most 100000): make the dashes longer tím vznikne příliš mnoho dílů (nejvýše 100000): prodlužte čárky @msg select paths, or segments, to divide vyberte cesty nebo segmenty k rozdělení +# Path Precision Tools add-on: Smooth Bridge. + Smooth Bridge… Hladký most… + Smooth Bridge Hladký most + Keep Originals Zachovat originály +@msg select two circles to bridge vyberte dva kruhy k propojení +@msg one circle is inside the other jeden kruh je uvnitř druhého +@msg the circles are too far apart for this radius: raise the radius kruhy jsou pro tento poloměr příliš daleko od sebe: zvětšete poloměr +@msg the circles are too far apart for this radius kruhy jsou pro tento poloměr příliš daleko od sebe # Path Precision Tools add-on: Common Tangents. Common Tangents… Společné tečny… Common Tangents Společné tečny diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 33ddb9e429..789dcc430f 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -235,6 +235,14 @@ liquify-list-end {0}, {1} {0} og {1} @msg is a prompt's answer, whose `value` must be a string or null er svaret på en prompt, hvis `value` skal være en streng eller null @msg must have `kind` alert, confirm or prompt skal have `kind` alert, confirm eller prompt @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` er kun til en kørsel uden nogen at spørge: i appen besvarer personen hver dialog +@msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` skal være et heltal fra 1 til {_1} +@msg `args{place}` is nested more than 64 levels deep `args{place}` er indlejret mere end 64 niveauer dybt +@msg `args` must be an object `args` skal være et objekt +@msg `args` is larger than 1 MiB `args` er større end 1 MiB +@msg `path` is empty `path` er tom +@msg `installed` takes a `path`, not a `source` `installed` tager en `path`, ikke en `source` +@msg `path` must name a .js or .jsx file `path` skal angive en .js- eller .jsx-fil +@msg give exactly one of `path` and `source` angiv præcis én af `path` og `source` @msg Running a script Kører et script @msg Data Recovery can't keep copies in {path}: {e} Datagendannelse kan ikke opbevare kopier i {path}: {e} @msg Plug-ins can't be loaded from {path}: {e} Plug-ins kan ikke indlæses fra {path}: {e} @@ -425,7 +433,7 @@ liquify-list-end {0}, {1} {0} og {1} @msg each of `{GRAPHICS}` must be an object hvert element i `{GRAPHICS}` skal være et objekt @msg `{GRAPHICS}` entries take symbol, face, x, y, scale and rotation, not `{k}` elementer i `{GRAPHICS}` tager symbol, face, x, y, scale og rotation, ikke `{k}` @msg each of `{GRAPHICS}` needs `symbol`, the name of a symbol hvert element i `{GRAPHICS}` kræver `symbol`, navnet på et symbol -@msg `{GRAPHICS}` face must be front or back `{GRAPHICS}`: face skal være front eller back +@msg `{GRAPHICS}` face must be front, back or side `{GRAPHICS}`: face skal være front, back eller side @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} `{GRAPHICS}`: {key} skal være et tal fra {lo} til {hi} @msg `{GRAPHICS}` must be an array `{GRAPHICS}` skal være et array @msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types Grafik kortlægges på objekttyperne Plan, Ekstrudér, Omdrej og Pust op @@ -1432,6 +1440,7 @@ liquify-list-end {0}, {1} {0} og {1} @msg a linked JavaScript file is outside the read roots en linket JavaScript-fil ligger uden for læserødderne @msg a linked image file is outside the read roots en linket billedfil ligger uden for læserødderne @msg a linked file's export folder is outside the read roots eksportmappen for en linket fil ligger uden for læserødderne +@msg a linked file's editing data can't be read to check it against the read roots redigeringsdataene for en linket fil kan ikke læses for at kontrollere dem mod læserødderne @msg a name names one asset: give multiple: false, or one object et navn angiver ét aktiv: angiv multiple: false eller ét objekt @msg a namespace declaration uses a reserved prefix or URI en navnerumserklæring bruger et reserveret præfiks eller en reserveret URI @msg a namespace qualifier is undefined en navnerumskvalifikator er udefineret @@ -4400,6 +4409,7 @@ digits Malayalam Malayalam Underline Understreget Vertical Scale % Lodret skalering % Axis Akse + Axis Angle Aksevinkel ICF Top/Right ICF øverst/højre ICF Bottom/Left ICF nederst/venstre Show Font Height Options Vis indstillinger for skrifthøjde @@ -4955,6 +4965,7 @@ digits Malayalam Malayalam Line Properties: Linjeegenskaber: Line Length: Linjelængde: Line Angle: Linjevinkel: + Constrain Pie Angle Fasthold udsnittets vinkel Rectangle Properties: Rektangelegenskaber: Shape Properties: Figuregenskaber: Shape Properties Figuregenskaber @@ -4996,6 +5007,7 @@ digits Malayalam Malayalam Scatter: Spredning: Rotation: Rotation: Rotation relative to: Rotation i forhold til: + Hue Jitter: Nuancevariation: Brush Scale Options Indstillinger for penselskalering Scale Proportionately Skalér proportionalt Stretch to Fit Stroke Length Stræk til konturens længde @@ -5034,6 +5046,7 @@ digits Malayalam Malayalam Size: Størrelse: Calligraphic Brush Options Indstillinger for kalligrafipensel Bristle Brush Options Indstillinger for børstepensel + Roundness Rundhed Roundness: Rundhed: Shape: Form: Bristle Length: Børstelængde: @@ -6030,6 +6043,8 @@ theme Appearance Udseende Current Brush Aktuel pensel Current Symbol Aktuelt symbol Delete Brush Slet pensel + Delete Color Slet farve + Restore Generated Table Gendan genereret tabel Delete Symbol Slet symbol Delete the selected symbol? Vil du slette det markerede symbol? Delete the selected symbols? Vil du slette de markerede symboler? @@ -6483,6 +6498,7 @@ theme Appearance Udseende 90° & 45° Angles 90° & 45°-vinkler 90° Angles 90°-vinkler Additional Plug-ins Folder Yderligere mappe med plug-ins + Plug-in Instruction Budget Instruktionsbudget for plug-ins Additional Fonts Folder Yderligere mappe med skrifttyper Alignment Guides Justeringshjælpelinjer Anchor Points, Handle, and Bounding Box Display Visning af ankerpunkter, håndtag og afgrænsningsboks @@ -6509,6 +6525,7 @@ theme Appearance Udseende Data Recovery Datgendannelse Default Language Standardsprog Disable Auto Add/Delete Deaktivér automatisk tilføjelse/sletning + Interpolate Control Points When Moving Anchors Interpolér retningshåndtag ved flytning af ankerpunkter Display All Blacks Accurately Vis alle sorte nøjagtigt Display All Blacks as Rich Black Vis alle sorte som rich black Display Bitmaps as Anti-aliased Images in Pixel Preview Vis bitmaps som antialiaserede billeder i pixelforhåndsvisning @@ -6597,6 +6614,9 @@ theme Appearance Udseende Printing / Exporting Udskrivning / eksport Real-time Drawing and Editing Tegning og redigering i realtid Use Monitor Profile for Canvas Brug skærmprofil til canvas + Refresh Monitor Profile Opdatér skærmprofil +@msg turn on Use Monitor Profile for Canvas first slå først „Brug skærmprofil til canvas“ til +@msg this build doesn't read display profiles denne version læser ikke skærmprofiler The canvas is drawn in sRGB. Canvasset tegnes i sRGB. Canvas display profile: Canvassets skærmprofil: The system matches the window to the display's colors. Systemet tilpasser vinduet til skærmens farver. @@ -6993,6 +7013,9 @@ font-technology Variable Variable Search commands, tools, panels and effects… Søg i kommandoer, værktøjer, paneler og effekter… No commands match Ingen kommandoer passer {pos} of {total}: {name} {pos} af {total}: {name} + No menu item Intet menupunkt + Toolbar Værktøjslinje + {toolbar}, in the {tool} group {toolbar}, i gruppen {tool} @plural {n} result|{n} results {n} resultat|{n} resultater @plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} af {n} resultat. Skriv videre for at indsnævre dem.|{shown} af {n} resultater. Skriv videre for at indsnævre dem. Recent Commands Seneste kommandoer @@ -7029,6 +7052,7 @@ font-technology Variable Variable The mouse wheel with Cmd/Ctrl held scrolls the canvas sideways. Musehjulet med Cmd/Ctrl holdt nede ruller lærredet sidelæns. Dragging sideways on a numeric field's label changes the field's value. Når du trækker sidelæns på et talfelts etiket, ændres feltets værdi. A two-finger rotate gesture on a trackpad rotates the canvas view. En rotationsbevægelse med to fingre på en pegeplade roterer visningen af lærredet. + When you move anchor points, each curve with one moved end keeps its shape relative to its ends. Når du flytter ankerpunkter, beholder hver kurve med ét flyttet endepunkt sin form i forhold til sine endepunkter. Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Når du holder et værktøjs genvejstast nede, er værktøjet valgt, indtil du slipper, og derefter vælges det forrige værktøj igen. Shows the bounding box while you move the selection or draw a shape. Viser afgrænsningsboksen, mens du flytter markeringen eller tegner en form. Create Trim Marks draws Japanese-style marks instead of Roman ones. Opret beskæringsmærker tegner mærker i japansk stil i stedet for romerske. @@ -7554,6 +7578,7 @@ imageTrace Outline Kontur @msg choose a folder to export to vælg en mappe at eksportere til @msg choose a location for the package vælg en placering til pakken @msg clipboard is empty udklipsholderen er tom +@msg colorTable.deleted: at least one color has to stay in the color table colorTable.deleted: mindst én farve skal blive i farvetabellen @msg colorTable.{what}: `{h}` is not a colour such as "#ff8800" colorTable.{what}: `{h}` er ikke en farve som "#ff8800" @msg colorTable.{what}: at most {MAX_TABLE} colours colorTable.{what}: højst {MAX_TABLE} farver @msg command `{0}` is not available right now: {1} kommandoen `{0}` er ikke tilgængelig lige nu: {1} @@ -8014,6 +8039,8 @@ imageTrace Outline Kontur @msg Reload the page to go on (changes not saved yet may be lost). Genindlæs siden for at fortsætte (ændringer, der endnu ikke er gemt, kan gå tabt). @msg tool (a tool id) is required tool (et værktøj-id) er påkrævet @msg {tool} isn't in a toolbar group of several tools {tool} er ikke i en værktøjsgruppe med flere værktøjer +@msg Presentation Mode hides the toolbars: change the screen mode to show them Præsentationstilstand skjuler værktøjslinjerne: skift skærmtilstand for at vise dem +@msg Tab has hidden the toolbars: press Tab to show them Tab har skjult værktøjslinjerne: tryk på Tab for at vise dem @msg onto must name a panel floating in another group onto skal angive et panel, der flyder i en anden gruppe @msg below and above must name a panel floating in another group below og above skal angive et panel, der flyder i en anden gruppe @msg give only one of onto, below and above angiv kun én af onto, below og above @@ -8464,6 +8491,7 @@ mark-style Japanese Japansk Cove Cove Depth Dybde Front Forfra + Side Siden Isometric Bottom Isometrisk bund Isometric Left Isometrisk venstre Isometric Right Isometrisk højre @@ -9805,6 +9833,14 @@ breakText Glyphs Glyffer Remove Gaps Fjern mellemrum @msg that makes too many pieces (at most 100000): make the dashes longer det giver for mange stykker (højst 100000): gør stregerne længere @msg select paths, or segments, to divide vælg stier eller segmenter, der skal opdeles +# Path Precision Tools add-on: Smooth Bridge. + Smooth Bridge… Blød bro… + Smooth Bridge Blød bro + Keep Originals Behold originaler +@msg select two circles to bridge vælg to cirkler, der skal forbindes +@msg one circle is inside the other den ene cirkel er inden i den anden +@msg the circles are too far apart for this radius: raise the radius cirklerne er for langt fra hinanden til denne radius: gør radius større +@msg the circles are too far apart for this radius cirklerne er for langt fra hinanden til denne radius # Path Precision Tools add-on: Common Tangents. Common Tangents… Fælles tangenter… Common Tangents Fælles tangenter diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 120a9e3751..b0d5cff68c 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -116,6 +116,7 @@ Add to Swatches Zu Farbfeldern hinzufügen Add Used Colors Verwendete Farben hinzufügen Additional Plug-ins Folder Zusätzlicher Plug-in-Ordner + Plug-in Instruction Budget Anweisungsbudget für Plug-ins Additional Fonts Folder Zusätzlicher Schriftenordner Adjust Adjoining Width Points Angrenzende Breitenpunkte anpassen Incoming Eingehend @@ -797,6 +798,8 @@ font-technology Variable Variabel Delete Artboard Zeichenfläche löschen Delete Artboards Zeichenflächen löschen Delete Brush Pinsel löschen + Delete Color Farbe löschen + Restore Generated Table Generierte Tabelle wiederherstellen Delete Character Style Zeichenformat löschen Delete Empty Artboards Leere Zeichenflächen löschen Delete Freeform Point Freiformpunkt löschen @@ -865,6 +868,7 @@ font-technology Variable Variabel Direct Selection Tool Direktauswahl-Werkzeug Direction Handles Richtungsgriffe Disable Auto Add/Delete Automatisches Hinzufügen/Löschen deaktivieren + Interpolate Control Points When Moving Anchors Richtungsgriffe beim Verschieben von Ankerpunkten interpolieren Disable Opacity Mask Deckkraftmaske deaktivieren Discard Verwerfen Preserve Beibehalten @@ -2251,6 +2255,7 @@ file-filter Templates Vorlagen New Bristle Brush Neuer Borstenpinsel Calligraphic Brush Options Optionen für Kalligrafiepinsel Bristle Brush Options Optionen für Borstenpinsel + Roundness Rundheit Roundness: Rundheit: Fixed Fest Pressure Druck @@ -2693,6 +2698,7 @@ diagnostics ui Oberfläche Line Properties: Linieneigenschaften: Line Length: Linienlänge: Line Angle: Linienwinkel: + Constrain Pie Angle Winkel des Kreissegments beibehalten Polygon Tool Polygon-Werkzeug Portrait Hochformat Power Saving (integrated) Energiesparen (integriert) @@ -2854,6 +2860,9 @@ digits Malayalam Malayalam Real World: Reale Welt: Real-time Drawing and Editing Zeichnen und Bearbeiten in Echtzeit Use Monitor Profile for Canvas Monitorprofil für Arbeitsfläche verwenden + Refresh Monitor Profile Monitorprofil aktualisieren +@msg turn on Use Monitor Profile for Canvas first aktivieren Sie zuerst „Monitorprofil für Arbeitsfläche verwenden“ +@msg this build doesn't read display profiles diese Version liest keine Bildschirmprofile The canvas is drawn in sRGB. Die Arbeitsfläche wird in sRGB dargestellt. Canvas display profile: Bildschirmprofil der Arbeitsfläche: The system matches the window to the display's colors. Das System passt das Fenster an die Farben des Bildschirms an. @@ -3116,6 +3125,7 @@ digits Malayalam Malayalam The mouse wheel with Cmd/Ctrl held scrolls the canvas sideways. Mit gedrückter Befehls-/Strg-Taste scrollt das Mausrad die Arbeitsfläche seitwärts. Dragging sideways on a numeric field's label changes the field's value. Seitliches Ziehen auf der Beschriftung eines Zahlenfelds ändert den Wert des Felds. A two-finger rotate gesture on a trackpad rotates the canvas view. Eine Drehgeste mit zwei Fingern auf einem Trackpad dreht die Ansicht der Arbeitsfläche. + When you move anchor points, each curve with one moved end keeps its shape relative to its ends. Wenn Sie Ankerpunkte verschieben, behält jede Kurve mit einem verschobenen Ende ihre Form relativ zu ihren Enden. Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Solange Sie das Tastaturkürzel eines Werkzeugs gedrückt halten, ist dieses Werkzeug gewählt; danach wird wieder das vorherige gewählt. Shows the bounding box while you move the selection or draw a shape. Zeigt den Begrenzungsrahmen an, während Sie die Auswahl verschieben oder eine Form zeichnen. Create Trim Marks draws Japanese-style marks instead of Roman ones. „Schnittmarken erstellen“ zeichnet japanische statt römische Marken. @@ -3427,6 +3437,11 @@ digits Malayalam Malayalam Search commands, tools, panels and effects… Befehle, Werkzeuge, Bedienfelder und Effekte suchen… No commands match Keine passenden Befehle {pos} of {total}: {name} {pos} von {total}: {name} + No menu item Kein Menüeintrag + Toolbar Werkzeugleiste + {toolbar}, in the {tool} group {toolbar}, in der Gruppe „{tool}“ + Tool Werkzeug + Command Befehl @plural {n} result|{n} results {n} Ergebnis|{n} Ergebnisse @plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} von {n} Ergebnis. Tippen Sie weiter, um sie einzugrenzen.|{shown} von {n} Ergebnissen. Tippen Sie weiter, um sie einzugrenzen. Recent Commands Zuletzt verwendete Befehle @@ -4470,6 +4485,7 @@ imageTrace Outline Kontur Bevel Abgeflacht Offset Versatz Axis Achse + Axis Angle Achsenwinkel axis Horizontal Horizontal axis Vertical Vertikal axis Both Beide @@ -4962,6 +4978,7 @@ liquify-list-end {0}, {1} {0} und {1} @msg choose a folder to export to wählen Sie einen Ordner für den Export @msg choose a location for the package wählen Sie einen Speicherort für das Paket @msg clipboard is empty die Zwischenablage ist leer +@msg colorTable.deleted: at least one color has to stay in the color table colorTable.deleted: Mindestens eine Farbe muss in der Farbtabelle bleiben @msg colorTable.{what}: `{h}` is not a colour such as "#ff8800" colorTable.{what}: `{h}` ist keine Farbe wie "#ff8800" @msg colorTable.{what}: at most {MAX_TABLE} colours colorTable.{what}: höchstens {MAX_TABLE} Farben @msg command `{0}` is not available right now: {1} der Befehl `{0}` ist derzeit nicht verfügbar: {1} @@ -5029,6 +5046,12 @@ liquify-list-end {0}, {1} {0} und {1} @msg no PNG encoder kein PNG-Encoder @msg no active document kein aktives Dokument @msg no active perspective plane keine aktive Perspektivebene +@msg the perspective grid is hidden das Perspektivenraster ist ausgeblendet +@msg Automatic Plane Positioning is off: turn on anchorPoint or gridlineIntersection (perspective.widget.options) Die automatische Ebenenpositionierung ist ausgeschaltet: Schalten Sie anchorPoint oder gridlineIntersection ein (perspective.widget.options) +@msg anchorPoint must be true or false anchorPoint muss true oder false sein +@msg gridlineIntersection must be true or false gridlineIntersection muss true oder false sein +@msg tolerance must be 0 or more tolerance muss 0 oder größer sein +@msg give `at` or `clear`, not both geben Sie `at` oder `clear` an, nicht beides @msg no anchor points selected keine Ankerpunkte ausgewählt @msg `points` must be two or three [x, y] pairs of numbers `points` muss aus zwei oder drei Zahlenpaaren [x, y] bestehen @msg direct-select two or three anchor points, or give `points` wählen Sie zwei oder drei Ankerpunkte direkt aus oder geben Sie `points` an @@ -5502,6 +5525,8 @@ variable-list-end {0}, {1} {0} und {1} @msg Reload the page to go on (changes not saved yet may be lost). Laden Sie die Seite neu, um fortzufahren (noch nicht gespeicherte Änderungen können verloren gehen). @msg tool (a tool id) is required tool (eine Werkzeug-ID) ist erforderlich @msg {tool} isn't in a toolbar group of several tools {tool} gehört zu keiner Werkzeuggruppe mit mehreren Werkzeugen +@msg Presentation Mode hides the toolbars: change the screen mode to show them der Präsentationsmodus blendet die Werkzeugleisten aus: Ändern Sie den Bildschirmmodus, um sie anzuzeigen +@msg Tab has hidden the toolbars: press Tab to show them die Tabulatortaste hat die Werkzeugleisten ausgeblendet: Drücken Sie die Tabulatortaste, um sie anzuzeigen @msg onto must name a panel floating in another group onto muss ein Bedienfeld nennen, das in einer anderen Gruppe schwebt @msg below and above must name a panel floating in another group below und above müssen ein Bedienfeld nennen, das in einer anderen Gruppe schwebt @msg give only one of onto, below and above nur eines von onto, below und above angeben @@ -5708,6 +5733,7 @@ variable-list-end {0}, {1} {0} und {1} Scatter: Streuung: Rotation: Drehung: Rotation relative to: Drehung relativ zu: + Hue Jitter: Farbtonvariation: Side Tile Seitenkachel Outer Corner Tile Äußere Eckkachel Inner Corner Tile Innere Eckkachel @@ -5992,6 +6018,7 @@ lighting Light Licht Cove Hohlkehle Depth Tiefe Front Vorne + Side Seite Isometric Bottom Isometrisch unten Isometric Left Isometrisch links Isometric Right Isometrisch rechts @@ -6086,7 +6113,7 @@ lighting Light Licht @msg each of `{GRAPHICS}` must be an object jeder Eintrag von `{GRAPHICS}` muss ein Objekt sein @msg `{GRAPHICS}` entries take symbol, face, x, y, scale and rotation, not `{k}` `{GRAPHICS}`-Einträge nehmen symbol, face, x, y, scale und rotation an, nicht `{k}` @msg each of `{GRAPHICS}` needs `symbol`, the name of a symbol jeder Eintrag von `{GRAPHICS}` braucht `symbol`, den Namen eines Symbols -@msg `{GRAPHICS}` face must be front or back face in `{GRAPHICS}` muss front oder back sein +@msg `{GRAPHICS}` face must be front, back or side face in `{GRAPHICS}` muss front, back oder side sein @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} {key} in `{GRAPHICS}` muss eine Zahl von {lo} bis {hi} sein @msg `{GRAPHICS}` must be an array `{GRAPHICS}` muss ein Array sein @msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types Grafiken werden auf die Objekttypen Ebene, Extrudieren, Kreiseln und Aufblasen abgebildet @@ -7340,6 +7367,14 @@ breakText Glyphs Glyphen Remove Gaps Lücken entfernen @msg that makes too many pieces (at most 100000): make the dashes longer das ergibt zu viele Teile (höchstens 100000): machen Sie die Striche länger @msg select paths, or segments, to divide wählen Sie Pfade oder Segmente zum Aufteilen aus +# Path Precision Tools add-on: Smooth Bridge. + Smooth Bridge… Weiche Brücke… + Smooth Bridge Weiche Brücke + Keep Originals Originale beibehalten +@msg select two circles to bridge wählen Sie zwei Kreise zum Verbinden aus +@msg one circle is inside the other ein Kreis liegt im anderen +@msg the circles are too far apart for this radius: raise the radius die Kreise liegen für diesen Radius zu weit auseinander: vergrößern Sie den Radius +@msg the circles are too far apart for this radius die Kreise liegen für diesen Radius zu weit auseinander # Path Precision Tools add-on: Common Tangents. Common Tangents… Gemeinsame Tangenten… Common Tangents Gemeinsame Tangenten @@ -7706,6 +7741,14 @@ breakText Glyphs Glyphen @msg `answers` has more than {MAX_ANSWERS} answers `answers` hat mehr als {MAX_ANSWERS} Antworten @msg `answers` is larger than 1 MiB `answers` ist größer als 1 MiB @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` ist nur für einen Lauf ohne jemanden, der gefragt werden kann: In der App beantwortet die Person jeden Dialog +@msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` muss eine ganze Zahl von 1 bis {_1} sein +@msg `args{place}` is nested more than 64 levels deep `args{place}` ist mehr als 64 Ebenen tief verschachtelt +@msg `args` must be an object `args` muss ein Objekt sein +@msg `args` is larger than 1 MiB `args` ist größer als 1 MiB +@msg `path` is empty `path` ist leer +@msg `installed` takes a `path`, not a `source` `installed` nimmt einen `path`, keine `source` +@msg `path` must name a .js or .jsx file `path` muss eine .js- oder .jsx-Datei angeben +@msg give exactly one of `path` and `source` geben Sie genau eines von `path` und `source` an @msg `answers` must be a list of answers `answers` muss eine Liste von Antworten sein @msg `artboard` must be the index of an artboard of the document `artboard` muss der Index einer Zeichenfläche des Dokuments sein @msg `artboardsAt` must be [x, y] `artboardsAt` muss [x, y] sein @@ -9545,6 +9588,7 @@ breakText Glyphs Glyphen @msg a linked JavaScript file is outside the read roots eine verknüpfte JavaScript-Datei liegt außerhalb der Lesestammordner @msg a linked image file is outside the read roots eine verknüpfte Bilddatei liegt außerhalb der Lesestammordner @msg a linked file's export folder is outside the read roots der Exportordner einer verknüpften Datei liegt außerhalb der Lesestammordner +@msg a linked file's editing data can't be read to check it against the read roots die Bearbeitungsdaten einer verknüpften Datei können nicht gelesen werden, um sie mit den Lesestammordnern abzugleichen @msg a number cannot be read eine Zahl kann nicht gelesen werden @msg a swatch exchange block is too long ein Block der Farbfeld-Austauschdatei ist zu lang @msg a swatch exchange name is too long ein Name in der Farbfeld-Austauschdatei ist zu lang diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 4f9cb47e9d..0166d82d30 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -121,6 +121,7 @@ Add to Swatches Προσθήκη στα δείγματα χρωμάτων Add Used Colors Προσθήκη των χρησιμοποιημένων χρωμάτων Additional Plug-ins Folder Πρόσθετος φάκελος επεκτάσεων + Plug-in Instruction Budget Προϋπολογισμός εντολών επεκτάσεων Additional Fonts Folder Πρόσθετος φάκελος γραμματοσειρών Adjust Adjoining Width Points Ρύθμιση γειτονικών σημείων πλάτους Incoming Εισερχόμενο @@ -775,6 +776,8 @@ font-technology Variable Μεταβλητές Delete Artboard Διαγραφή πίνακα σχεδίασης Delete Artboards Διαγραφή πινάκων σχεδίασης Delete Brush Διαγραφή πινέλου + Delete Color Διαγραφή χρώματος + Restore Generated Table Επαναφορά του παραγόμενου πίνακα Delete Character Style Διαγραφή στυλ χαρακτήρων Delete Empty Artboards Διαγραφή κενών πινάκων σχεδίασης Delete Freeform Point Διαγραφή ελεύθερου σημείου @@ -843,6 +846,7 @@ font-technology Variable Μεταβλητές Direct Selection Tool Άμεση επιλογή (Direct Selection Tool) Direction Handles Λαβές κατεύθυνσης Disable Auto Add/Delete Απενεργοποίηση αυτόματης προσθήκης/διαγραφής + Interpolate Control Points When Moving Anchors Παρεμβολή λαβών κατεύθυνσης κατά τη μετακίνηση σημείων αγκύρωσης Disable Opacity Mask Απενεργοποίηση μάσκας αδιαφάνειας Discard Απόρριψη Discard Empty Type Απόρριψη κενού κειμένου @@ -1935,6 +1939,7 @@ font-technology Variable Μεταβλητές Rotation: Περιστροφή: Flip: Αναστροφή: Fit Προσαρμογή + Roundness Στρογγυλότητα Roundness: Στρογγυλότητα: Fixed Σταθερό Pressure Πίεση @@ -2652,6 +2657,14 @@ liquify-list-end {0}, {1} {0} και {1} @msg is a prompt's answer, whose `value` must be a string or null είναι απάντηση σε prompt, οπότε το `value` πρέπει να είναι συμβολοσειρά ή null @msg must have `kind` alert, confirm or prompt πρέπει να έχει `kind` alert, confirm ή prompt @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog το `answers` είναι μόνο για εκτέλεση χωρίς κανέναν να ερωτηθεί: στην εφαρμογή, το άτομο απαντά σε κάθε παράθυρο διαλόγου +@msg `maxFuel` must be a whole number from 1 to {_1} το `maxFuel` πρέπει να είναι ακέραιος από 1 έως {_1} +@msg `args{place}` is nested more than 64 levels deep το `args{place}` έχει ένθεση μεγαλύτερη των 64 επιπέδων +@msg `args` must be an object το `args` πρέπει να είναι αντικείμενο +@msg `args` is larger than 1 MiB το `args` είναι μεγαλύτερο από 1 MiB +@msg `path` is empty το `path` είναι κενό +@msg `installed` takes a `path`, not a `source` το `installed` δέχεται `path`, όχι `source` +@msg `path` must name a .js or .jsx file το `path` πρέπει να ορίζει αρχείο .js ή .jsx +@msg give exactly one of `path` and `source` δώστε ακριβώς ένα από τα `path` και `source` @msg Running a script Εκτελείται σενάριο @msg Copied the script report Η αναφορά του σεναρίου αντιγράφηκε @msg Script file access denied: {path} Η πρόσβαση του σεναρίου σε αρχεία απορρίφθηκε: {path} @@ -3323,6 +3336,7 @@ theme Appearance Εμφάνιση Art Brush Options Επιλογές πινέλου σχεδίου Pattern Brush Options Επιλογές πινέλου μοτίβου Rotation relative to: Περιστροφή ως προς: + Hue Jitter: Διακύμανση απόχρωσης: Brush Scale Options Επιλογές κλιμάκωσης πινέλου Scale Proportionately Αναλογική κλιμάκωση Stretch to Fit Stroke Length Επέκταση για προσαρμογή στο μήκος περιγράμματος @@ -3630,6 +3644,7 @@ theme Appearance Εμφάνιση Line Properties: Ιδιότητες γραμμής: Line Length: Μήκος γραμμής: Line Angle: Γωνία γραμμής: + Constrain Pie Angle Διατήρηση γωνίας κυκλικού τομέα Power Saving (integrated) Εξοικονόμηση ενέργειας (ενσωματωμένη GPU) Portuguese Πορτογαλικά PostScript: PostScript: @@ -3749,6 +3764,9 @@ digits Malayalam Μαλαγιάλαμ Real World: Πραγματικός κόσμος: Real-time Drawing and Editing Σχεδίαση και επεξεργασία σε πραγματικό χρόνο Use Monitor Profile for Canvas Χρήση προφίλ οθόνης για τον καμβά + Refresh Monitor Profile Ανανέωση προφίλ οθόνης +@msg turn on Use Monitor Profile for Canvas first ενεργοποιήστε πρώτα τη «Χρήση προφίλ οθόνης για τον καμβά» +@msg this build doesn't read display profiles αυτή η έκδοση δεν διαβάζει προφίλ οθονών The canvas is drawn in sRGB. Ο καμβάς σχεδιάζεται σε sRGB. Canvas display profile: Προφίλ οθόνης καμβά: The system matches the window to the display's colors. Το σύστημα προσαρμόζει το παράθυρο στα χρώματα της οθόνης. @@ -3962,6 +3980,7 @@ digits Malayalam Μαλαγιάλαμ The mouse wheel with Cmd/Ctrl held scrolls the canvas sideways. Ο τροχός του ποντικιού με πατημένο το Cmd/Ctrl κυλά τον καμβά οριζόντια. Dragging sideways on a numeric field's label changes the field's value. Η μεταφορά προς τα πλάγια πάνω στην ετικέτα ενός αριθμητικού πεδίου αλλάζει την τιμή του πεδίου. A two-finger rotate gesture on a trackpad rotates the canvas view. Μια κίνηση περιστροφής με δύο δάχτυλα σε επιφάνεια αφής περιστρέφει την προβολή του καμβά. + When you move anchor points, each curve with one moved end keeps its shape relative to its ends. Όταν μετακινείτε σημεία αγκύρωσης, κάθε καμπύλη με ένα μετακινημένο άκρο διατηρεί το σχήμα της σε σχέση με τα άκρα της. Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Όσο κρατάτε πατημένη τη συντόμευση ενός εργαλείου, το εργαλείο είναι επιλεγμένο, και μετά επιλέγεται ξανά το προηγούμενο εργαλείο. Shows the bounding box while you move the selection or draw a shape. Εμφανίζει το πλαίσιο οριοθέτησης όσο μετακινείτε την επιλογή ή σχεδιάζετε ένα σχήμα. Create Trim Marks draws Japanese-style marks instead of Roman ones. Η Δημιουργία σημαδιών ξακρίσματος σχεδιάζει σημάδια ιαπωνικού τύπου αντί για ρωμαϊκά. @@ -4159,6 +4178,9 @@ digits Malayalam Μαλαγιάλαμ Search commands, tools, panels and effects… Αναζήτηση εντολών, εργαλείων, πλαισίων και εφέ… No commands match Καμία εντολή δεν ταιριάζει {pos} of {total}: {name} {pos} από {total}: {name} + No menu item Χωρίς στοιχείο μενού + Toolbar Γραμμή εργαλείων + {toolbar}, in the {tool} group {toolbar}, στην ομάδα {tool} @plural {n} result|{n} results {n} αποτέλεσμα|{n} αποτελέσματα @plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} από {n} αποτέλεσμα. Συνεχίστε να πληκτρολογείτε για να τα περιορίσετε.|{shown} από {n} αποτελέσματα. Συνεχίστε να πληκτρολογείτε για να τα περιορίσετε. Recent Commands Πρόσφατες εντολές @@ -4922,6 +4944,7 @@ digits Malayalam Μαλαγιάλαμ {people} contributors · {commits} commits {people} συνεισφέροντες · {commits} commits Joins Συνδέσεις Axis Άξονας + Axis Angle Γωνία άξονα Drag to move Σύρετε για μετακίνηση Drag to float as a toolbar Σύρετε για αποδέσμευση ως γραμμή εργαλείων Put back in the toolbar Επαναφορά στη γραμμή εργαλείων @@ -5017,6 +5040,7 @@ digits Malayalam Μαλαγιάλαμ @msg choose a folder to export to επιλέξτε φάκελο εξαγωγής @msg choose a location for the package επιλέξτε τοποθεσία συσκευασίας @msg clipboard is empty το πρόχειρο είναι κενό +@msg colorTable.deleted: at least one color has to stay in the color table colorTable.deleted: τουλάχιστον ένα χρώμα πρέπει να παραμείνει στον πίνακα χρωμάτων @msg colorTable.{what}: `{h}` is not a colour such as "#ff8800" colorTable.{what}: το `{h}` δεν είναι έγκυρο χρώμα, όπως το "#ff8800" @msg colorTable.{what}: at most {MAX_TABLE} colours colorTable.{what}: επιτρέπονται το πολύ {MAX_TABLE} χρώματα @msg command `{0}` is not available right now: {1} η εντολή `{0}` δεν είναι διαθέσιμη αυτήν τη στιγμή: {1} @@ -5084,6 +5108,12 @@ digits Malayalam Μαλαγιάλαμ @msg no PNG encoder δεν υπάρχει κωδικοποιητής PNG @msg no active document δεν υπάρχει ενεργό έγγραφο @msg no active perspective plane δεν υπάρχει ενεργό επίπεδο προοπτικής +@msg the perspective grid is hidden το πλέγμα προοπτικής είναι κρυφό +@msg Automatic Plane Positioning is off: turn on anchorPoint or gridlineIntersection (perspective.widget.options) Η αυτόματη τοποθέτηση επιπέδου είναι απενεργοποιημένη: ενεργοποιήστε το anchorPoint ή το gridlineIntersection (perspective.widget.options) +@msg anchorPoint must be true or false το anchorPoint πρέπει να είναι true ή false +@msg gridlineIntersection must be true or false το gridlineIntersection πρέπει να είναι true ή false +@msg tolerance must be 0 or more το tolerance πρέπει να είναι 0 ή μεγαλύτερο +@msg give `at` or `clear`, not both δώστε `at` ή `clear`, όχι και τα δύο @msg no anchor points selected δεν έχουν επιλεγεί σημεία αγκύρωσης @msg `points` must be two or three [x, y] pairs of numbers το `points` πρέπει να είναι δύο ή τρία ζεύγη αριθμών [x, y] @msg direct-select two or three anchor points, or give `points` επιλέξτε άμεσα δύο ή τρία σημεία αγκύρωσης ή δώστε `points` @@ -5553,6 +5583,8 @@ variable-list-end {0}, {1} {0} και {1} @msg Reload the page to go on (changes not saved yet may be lost). Ανανεώστε τη σελίδα για να συνεχίσετε (οι μη αποθηκευμένες αλλαγές ενδέχεται να χαθούν). @msg tool (a tool id) is required απαιτείται tool (αναγνωριστικό εργαλείου) @msg {tool} isn't in a toolbar group of several tools το {tool} δεν ανήκει σε ομάδα πολλών εργαλείων της γραμμής εργαλείων +@msg Presentation Mode hides the toolbars: change the screen mode to show them η Λειτουργία παρουσίασης κρύβει τις γραμμές εργαλείων: αλλάξτε τη λειτουργία οθόνης για να εμφανιστούν +@msg Tab has hidden the toolbars: press Tab to show them το Tab έκρυψε τις γραμμές εργαλείων: πατήστε Tab για να εμφανιστούν @msg onto must name a panel floating in another group το onto πρέπει να ορίζει πίνακα που αιωρείται σε άλλη ομάδα @msg below and above must name a panel floating in another group τα below και above πρέπει να ορίζουν πίνακα που αιωρείται σε άλλη ομάδα @msg give only one of onto, below and above δώστε μόνο ένα από τα onto, below και above @@ -5685,6 +5717,7 @@ variable-list-end {0}, {1} {0} και {1} @msg a linked JavaScript file is outside the read roots ένα συνδεδεμένο αρχείο JavaScript είναι εκτός των ριζών ανάγνωσης @msg a linked image file is outside the read roots ένα συνδεδεμένο αρχείο εικόνας είναι εκτός των ριζών ανάγνωσης @msg a linked file's export folder is outside the read roots ο φάκελος εξαγωγής ενός συνδεδεμένου αρχείου είναι εκτός των ριζών ανάγνωσης +@msg a linked file's editing data can't be read to check it against the read roots τα δεδομένα επεξεργασίας ενός συνδεδεμένου αρχείου δεν μπορούν να διαβαστούν για έλεγχο με τις ρίζες ανάγνωσης @msg the library's file is outside the read roots το αρχείο της βιβλιοθήκης είναι εκτός των ριζών ανάγνωσης @msg {file} names more than one linked JavaScript file το {file} αντιστοιχεί σε περισσότερα από ένα συνδεδεμένα αρχεία JavaScript @msg automation path rejected: outside the write root {root}: {path} απορρίφθηκε η διαδρομή αυτοματισμού: εκτός ρίζας εγγραφής {root}: {path} @@ -5813,6 +5846,7 @@ variable-list-end {0}, {1} {0} και {1} Both sides Και οι δύο πλευρές Cove Κοίλη ακμή Front Μπροστά + Side Πλάι Isometric Bottom Ισομετρική κάτω όψη Isometric Left Ισομετρική αριστερή όψη Isometric Right Ισομετρική δεξιά όψη @@ -5899,7 +5933,7 @@ variable-list-end {0}, {1} {0} και {1} @msg each of `{GRAPHICS}` must be an object κάθε στοιχείο του `{GRAPHICS}` πρέπει να είναι αντικείμενο @msg `{GRAPHICS}` entries take symbol, face, x, y, scale and rotation, not `{k}` οι καταχωρίσεις του `{GRAPHICS}` δέχονται symbol, face, x, y, scale και rotation, όχι `{k}` @msg each of `{GRAPHICS}` needs `symbol`, the name of a symbol κάθε στοιχείο του `{GRAPHICS}` χρειάζεται `symbol`, το όνομα ενός συμβόλου -@msg `{GRAPHICS}` face must be front or back το face του `{GRAPHICS}` πρέπει να είναι front ή back +@msg `{GRAPHICS}` face must be front, back or side το face του `{GRAPHICS}` πρέπει να είναι front, back ή side @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} το {key} του `{GRAPHICS}` πρέπει να είναι αριθμός από {lo} έως {hi} @msg `{GRAPHICS}` must be an array το `{GRAPHICS}` πρέπει να είναι πίνακας @msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types Τα γραφικά αντιστοιχίζονται στους τύπους αντικειμένου Επίπεδο, Εξώθηση, Περιστροφή γύρω από άξονα και Φούσκωμα @@ -7733,6 +7767,14 @@ breakText Glyphs Γλύφοι Remove Gaps Αφαίρεση κενών @msg that makes too many pieces (at most 100000): make the dashes longer αυτό δίνει πάρα πολλά κομμάτια (το πολύ 100000): κάντε τις παύλες μεγαλύτερες @msg select paths, or segments, to divide επιλέξτε διαδρομές ή τμήματα για διαίρεση +# Path Precision Tools add-on: Smooth Bridge. + Smooth Bridge… Ομαλή γέφυρα… + Smooth Bridge Ομαλή γέφυρα + Keep Originals Διατήρηση πρωτοτύπων +@msg select two circles to bridge επιλέξτε δύο κύκλους για γεφύρωση +@msg one circle is inside the other ο ένας κύκλος βρίσκεται μέσα στον άλλο +@msg the circles are too far apart for this radius: raise the radius οι κύκλοι απέχουν πολύ μεταξύ τους για αυτή την ακτίνα: αυξήστε την ακτίνα +@msg the circles are too far apart for this radius οι κύκλοι απέχουν πολύ μεταξύ τους για αυτή την ακτίνα # Path Precision Tools add-on: Common Tangents. Common Tangents… Κοινές εφαπτόμενες… Common Tangents Κοινές εφαπτόμενες diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index a50f7b05e0..d52a76a65d 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -141,6 +141,7 @@ Add to Swatches Agregar a muestras Add Used Colors Agregar colores usados Additional Plug-ins Folder Carpeta de plugins adicionales + Plug-in Instruction Budget Presupuesto de instrucciones de plugins Additional Fonts Folder Carpeta de fuentes adicionales Adjust Adjoining Width Points Ajustar puntos de anchura contiguos Incoming Entrante @@ -816,6 +817,8 @@ font-technology Variable Variables Delete Artboard Eliminar mesa de trabajo Delete Artboards Eliminar mesas de trabajo Delete Brush Eliminar pincel + Delete Color Eliminar color + Restore Generated Table Restaurar tabla generada Delete Character Style Eliminar estilo de carácter Delete Empty Artboards Eliminar mesas de trabajo vacías Delete Freeform Point Eliminar punto libre @@ -884,6 +887,7 @@ font-technology Variable Variables Direct Selection Tool Herramienta Selección directa Direction Handles Manejadores de dirección Disable Auto Add/Delete Desactivar agregar/eliminar automático + Interpolate Control Points When Moving Anchors Interpolar manejadores de dirección al mover puntos de ancla Disable Opacity Mask Desactivar máscara de opacidad Discard Descartar Discard Empty Type Descartar texto vacío @@ -2258,6 +2262,7 @@ font-technology Variable Variables Scatter: Dispersión: Rotation: Rotación: Rotation relative to: Rotación relativa a: + Hue Jitter: Variación del tono: Brush Scale Options Opciones de escala del pincel Scale Proportionately Escalar proporcionalmente Stretch to Fit Stroke Length Estirar para ajustar a la longitud del trazo @@ -2294,6 +2299,7 @@ font-technology Variable Variables Black becomes the stroke color and white stays white. Other colors become tints of the stroke color by their lightness. El negro pasa a ser el color del trazo y el blanco sigue siendo blanco. Los demás colores pasan a ser matices del color del trazo, y cuanto más claro es un color, más claro es su matiz. Black and white stay as they are. Dark colors become shades of the stroke color and light colors become tints of it. El negro sigue siendo negro y el blanco sigue siendo blanco. Los demás colores pasan a ser sombras del color del trazo cuando son oscuros y matices de él cuando son claros. The key color becomes the stroke color. The other colors shift their hue by the same amount and keep their saturation and brightness. El color clave pasa a ser el color del trazo. Los demás colores giran en la rueda de colores lo mismo que el color clave y conservan su saturación y su brillo. + Roundness Redondez Roundness: Redondez: Fixed Fijo Pressure Presión @@ -2732,6 +2738,7 @@ font-technology Variable Variables Line Properties: Propiedades de la línea: Line Length: Longitud de la línea: Line Angle: Ángulo de la línea: + Constrain Pie Angle Restringir ángulo del sector Polygon Tool Herramienta Polígono Portrait Vertical Power Saving (integrated) Ahorro de energía (integrada) @@ -2891,6 +2898,9 @@ digits Malayalam Malayálam Real World: Mundo real: Real-time Drawing and Editing Dibujo y edición en tiempo real Use Monitor Profile for Canvas Usar perfil del monitor para el lienzo + Refresh Monitor Profile Actualizar perfil del monitor +@msg turn on Use Monitor Profile for Canvas first activa primero «Usar perfil del monitor para el lienzo» +@msg this build doesn't read display profiles esta versión no lee perfiles de pantalla The canvas is drawn in sRGB. El lienzo se dibuja en sRGB. Canvas display profile: Perfil de pantalla del lienzo: The system matches the window to the display's colors. El sistema ajusta la ventana a los colores de la pantalla. @@ -3152,6 +3162,7 @@ digits Malayalam Malayálam The mouse wheel with Cmd/Ctrl held scrolls the canvas sideways. La rueda del mouse con Cmd/Ctrl pulsado desplaza el lienzo en horizontal. Dragging sideways on a numeric field's label changes the field's value. Arrastrar en horizontal sobre la etiqueta de un campo numérico cambia el valor del campo. A two-finger rotate gesture on a trackpad rotates the canvas view. Un gesto de giro con dos dedos en un trackpad gira la vista del lienzo. + When you move anchor points, each curve with one moved end keeps its shape relative to its ends. Al mover puntos de ancla, cada curva con un extremo movido conserva su forma respecto a sus extremos. Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Mantener pulsado el atajo de una herramienta la elige hasta que lo suelta, y después vuelve a elegirse la herramienta anterior. Shows the bounding box while you move the selection or draw a shape. Muestra el cuadro delimitador mientras mueve la selección o dibuja una forma. Create Trim Marks draws Japanese-style marks instead of Roman ones. Crear marcas de recorte dibuja marcas de estilo japonés en lugar de romanas. @@ -3461,6 +3472,9 @@ digits Malayalam Malayálam Search commands, tools, panels and effects… Buscar comandos, herramientas, paneles y efectos… No commands match Ningún comando coincide {pos} of {total}: {name} {pos} de {total}: {name} + No menu item Sin elemento de menú + Toolbar Barra de herramientas + {toolbar}, in the {tool} group {toolbar}, en el grupo {tool} @plural {n} result|{n} results {n} resultado|{n} resultados @plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} de {n} resultado. Sigue escribiendo para acotarlos.|{shown} de {n} resultados. Sigue escribiendo para acotarlos. Recent Commands Comandos recientes @@ -4552,6 +4566,7 @@ imageTrace Outline Contorno Bevel Bisel Offset Desplazamiento Axis Eje + Axis Angle Ángulo del eje axis Horizontal Horizontal axis Vertical Vertical axis Both Ambos @@ -4803,6 +4818,14 @@ liquify-list-end {0}, {1} {0}, {1} @msg is a prompt's answer, whose `value` must be a string or null es la respuesta de un prompt, cuyo `value` debe ser una cadena o null @msg must have `kind` alert, confirm or prompt debe tener `kind` alert, confirm o prompt @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` solo es para una ejecución sin nadie a quien preguntar: en la aplicación, la persona responde cada cuadro de diálogo +@msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` debe ser un número entero de 1 a {_1} +@msg `args{place}` is nested more than 64 levels deep `args{place}` está anidado a más de 64 niveles +@msg `args` must be an object `args` debe ser un objeto +@msg `args` is larger than 1 MiB `args` ocupa más de 1 MiB +@msg `path` is empty `path` está vacío +@msg `installed` takes a `path`, not a `source` `installed` admite un `path`, no un `source` +@msg `path` must name a .js or .jsx file `path` debe indicar un archivo .js o .jsx +@msg give exactly one of `path` and `source` indique exactamente uno de `path` y `source` @msg Running a script Ejecutando un script @msg Copied the script report Se copió el informe del script @msg Script file access denied: {path} Acceso del script a archivos denegado: {path} @@ -5067,6 +5090,7 @@ liquify-list-end {0}, {1} {0}, {1} @msg choose a folder to export to elige una carpeta a la que exportar @msg choose a location for the package elige una ubicación para el paquete @msg clipboard is empty el portapapeles está vacío +@msg colorTable.deleted: at least one color has to stay in the color table colorTable.deleted: al menos un color debe quedar en la tabla de colores @msg colorTable.{what}: `{h}` is not a colour such as "#ff8800" colorTable.{what}: `{h}` no es un color como "#ff8800" @msg colorTable.{what}: at most {MAX_TABLE} colours colorTable.{what}: como máximo {MAX_TABLE} colores @msg command `{0}` is not available right now: {1} el comando `{0}` no está disponible ahora: {1} @@ -5134,6 +5158,12 @@ liquify-list-end {0}, {1} {0}, {1} @msg no PNG encoder no hay codificador PNG @msg no active document no hay ningún documento activo @msg no active perspective plane no hay ningún plano de perspectiva activo +@msg the perspective grid is hidden la cuadrícula de perspectiva está oculta +@msg Automatic Plane Positioning is off: turn on anchorPoint or gridlineIntersection (perspective.widget.options) El posicionamiento automático del plano está desactivado: activa anchorPoint o gridlineIntersection (perspective.widget.options) +@msg anchorPoint must be true or false anchorPoint debe ser true o false +@msg gridlineIntersection must be true or false gridlineIntersection debe ser true o false +@msg tolerance must be 0 or more tolerance debe ser 0 o más +@msg give `at` or `clear`, not both indica `at` o `clear`, no ambos @msg no anchor points selected no hay puntos de ancla seleccionados @msg `points` must be two or three [x, y] pairs of numbers `points` debe ser dos o tres pares de números [x, y] @msg direct-select two or three anchor points, or give `points` seleccione directamente dos o tres puntos de ancla o indique `points` @@ -5610,6 +5640,8 @@ variable-list-end {0}, {1} {0} y {1} @msg Reload the page to go on (changes not saved yet may be lost). Vuelve a cargar la página para continuar (los cambios que aún no se guardaron podrían perderse). @msg tool (a tool id) is required se requiere tool (un id de herramienta) @msg {tool} isn't in a toolbar group of several tools {tool} no está en un grupo de la barra de herramientas con varias herramientas +@msg Presentation Mode hides the toolbars: change the screen mode to show them el Modo de presentación oculta las barras de herramientas: cambie el modo de pantalla para mostrarlas +@msg Tab has hidden the toolbars: press Tab to show them Tab ha ocultado las barras de herramientas: pulse Tab para mostrarlas @msg onto must name a panel floating in another group onto debe nombrar un panel que flote en otro grupo @msg below and above must name a panel floating in another group below y above deben nombrar un panel que flote en otro grupo @msg give only one of onto, below and above indica solo uno de onto, below y above @@ -5726,6 +5758,7 @@ variable-list-end {0}, {1} {0} y {1} @msg a linked JavaScript file is outside the read roots un archivo JavaScript vinculado está fuera de las carpetas raíz de lectura @msg a linked image file is outside the read roots un archivo de imagen vinculado está fuera de las carpetas raíz de lectura @msg a linked file's export folder is outside the read roots la carpeta de exportación de un archivo vinculado está fuera de las carpetas raíz de lectura +@msg a linked file's editing data can't be read to check it against the read roots no se pueden leer los datos de edición de un archivo vinculado para comprobarlos con las carpetas raíz de lectura @msg automation path rejected: outside the write root {root}: {path} ruta de automatización rechazada: fuera de la carpeta raíz de escritura {root}: {path} @msg automation path rejected: outside the write roots {roots}: {path} ruta de automatización rechazada: fuera de las carpetas raíz de escritura {roots}: {path} @msg automation path rejected: path is empty ruta de automatización rechazada: la ruta está vacía @@ -6388,6 +6421,7 @@ mark-style Japanese Japonesas Cove Cóncavo Depth Profundidad Front Frontal + Side Lateral Isometric Bottom Isométrica inferior Isometric Left Isométrica izquierda Isometric Right Isométrica derecha @@ -6483,7 +6517,7 @@ mark-style Japanese Japonesas @msg each of `{GRAPHICS}` must be an object cada elemento de `{GRAPHICS}` debe ser un objeto @msg `{GRAPHICS}` entries take symbol, face, x, y, scale and rotation, not `{k}` los elementos de `{GRAPHICS}` admiten symbol, face, x, y, scale y rotation, no `{k}` @msg each of `{GRAPHICS}` needs `symbol`, the name of a symbol cada elemento de `{GRAPHICS}` necesita `symbol`, el nombre de un símbolo -@msg `{GRAPHICS}` face must be front or back face de `{GRAPHICS}` debe ser front o back +@msg `{GRAPHICS}` face must be front, back or side face de `{GRAPHICS}` debe ser front, back o side @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} {key} de `{GRAPHICS}` debe ser un número de {lo} a {hi} @msg `{GRAPHICS}` must be an array `{GRAPHICS}` debe ser una matriz @msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types Los gráficos se asignan a los tipos de objeto Plano, Extrusión, Revolución e Inflar @@ -7721,6 +7755,14 @@ breakText Glyphs Glifos Remove Gaps Quitar separaciones @msg that makes too many pieces (at most 100000): make the dashes longer eso da demasiados trozos (como máximo 100000): alargue los guiones @msg select paths, or segments, to divide seleccione trazados o segmentos para dividir +# Path Precision Tools add-on: Smooth Bridge. + Smooth Bridge… Puente suave… + Smooth Bridge Puente suave + Keep Originals Conservar originales +@msg select two circles to bridge seleccione dos círculos para unir +@msg one circle is inside the other un círculo está dentro del otro +@msg the circles are too far apart for this radius: raise the radius los círculos están demasiado separados para este radio: aumente el radio +@msg the circles are too far apart for this radius los círculos están demasiado separados para este radio # Path Precision Tools add-on: Common Tangents. Common Tangents… Tangentes comunes… Common Tangents Tangentes comunes diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 8972c2de6b..c04fbd953c 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -1755,6 +1755,7 @@ digits Malayalam Malajalam Underline Alleviivaus Vertical Scale % Pystyskaalaus % Axis Akseli + Axis Angle Akselin kulma ICF Top/Right ICF ylä/oikea ICF Bottom/Left ICF ala/vasen Show Font Height Options Näytä fontin korkeuden asetukset @@ -2404,6 +2405,7 @@ digits Malayalam Malajalam Line Properties: Viivan ominaisuudet: Line Length: Viivan pituus: Line Angle: Viivan kulma: + Constrain Pie Angle Säilytä sektorin kulma Rectangle Properties: Suorakulmion ominaisuudet: Shape Properties: Muodon ominaisuudet: Shape Properties Muodon ominaisuudet @@ -2445,6 +2447,7 @@ digits Malayalam Malajalam Scatter: Sirottelu: Rotation: Kierto: Rotation relative to: Kierto suhteessa: + Hue Jitter: Sävyn vaihtelu: Brush Scale Options Siveltimen skaalausasetukset Scale Proportionately Skaalaa suhteellisesti Stretch to Fit Stroke Length Venytä viivan pituuteen @@ -2483,6 +2486,7 @@ digits Malayalam Malajalam Size: Koko: Calligraphic Brush Options Kalligrafisen siveltimen asetukset Bristle Brush Options Harjassiveltimen asetukset + Roundness Pyöreys Roundness: Pyöreys: Shape: Muoto: Bristle Length: Harjasten pituus: @@ -3524,6 +3528,8 @@ theme Appearance Ulkoasu Current Brush Nykyinen sivellin Current Symbol Nykyinen symboli Delete Brush Poista sivellin + Delete Color Poista väri + Restore Generated Table Palauta luotu taulukko Delete Symbol Poista symboli Delete the selected symbol? Poistetaanko valittu symboli? Delete the selected symbols? Poistetaanko valitut symbolit? @@ -3978,6 +3984,7 @@ theme Appearance Ulkoasu 90° & 45° Angles 90° ja 45° kulmat 90° Angles 90° kulmat Additional Plug-ins Folder Lisälaajennusten kansio + Plug-in Instruction Budget Laajennusten käskybudjetti Additional Fonts Folder Lisäfonttien kansio Alignment Guides Tasausapuviivat Anchor Points, Handle, and Bounding Box Display Ankkuripisteiden, kahvojen ja rajausruudun näyttö @@ -4004,6 +4011,7 @@ theme Appearance Ulkoasu Data Recovery Tietojen palautus Default Language Oletuskieli Disable Auto Add/Delete Poista automaattinen lisäys/poisto käytöstä + Interpolate Control Points When Moving Anchors Interpoloi suuntakahvat siirrettäessä ankkuripisteitä Display All Blacks Accurately Näytä kaikki mustat tarkasti Display All Blacks as Rich Black Näytä kaikki mustat syvämustina Display Bitmaps as Anti-aliased Images in Pixel Preview Näytä bittikartat reunanpehmennettyinä kuvina pikseliesikatselussa @@ -4092,6 +4100,9 @@ theme Appearance Ulkoasu Printing / Exporting Tulostus / vienti Real-time Drawing and Editing Reaaliaikainen piirto ja muokkaus Use Monitor Profile for Canvas Käytä näytön profiilia kankaalle + Refresh Monitor Profile Päivitä näytön profiili +@msg turn on Use Monitor Profile for Canvas first ota ensin käyttöön ”Käytä näytön profiilia kankaalle” +@msg this build doesn't read display profiles tämä versio ei lue näyttöjen profiileja The canvas is drawn in sRGB. Kangas piirretään sRGB-tilassa. Canvas display profile: Kankaan näyttöprofiili: The system matches the window to the display's colors. Järjestelmä sovittaa ikkunan näytön väreihin. @@ -4492,6 +4503,9 @@ font-technology Variable Muuttuvat Search commands, tools, panels and effects… Hae komentoja, työkaluja, paneeleita ja tehosteita… No commands match Mikään komento ei vastaa hakua {pos} of {total}: {name} {pos}/{total}: {name} + No menu item Ei valikkokohdetta + Toolbar Työkalurivi + {toolbar}, in the {tool} group {toolbar}, ryhmässä {tool} @plural {n} result|{n} results {n} tulos|{n} tulosta @plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown}/{n} tulosta. Kirjoita lisää rajataksesi tuloksia.|{shown}/{n} tulosta. Kirjoita lisää rajataksesi tuloksia. Recent Commands Viimeisimmät komennot @@ -4528,6 +4542,7 @@ font-technology Variable Muuttuvat The mouse wheel with Cmd/Ctrl held scrolls the canvas sideways. Hiiren rulla vierittää piirtopintaa sivuttain, kun Cmd/Ctrl on painettuna. Dragging sideways on a numeric field's label changes the field's value. Numerokentän nimiön vetäminen sivuttain muuttaa kentän arvoa. A two-finger rotate gesture on a trackpad rotates the canvas view. Kahden sormen kiertoele kosketuslevyllä kiertää piirtopinnan näkymää. + When you move anchor points, each curve with one moved end keeps its shape relative to its ends. Kun siirrät ankkuripisteitä, jokainen käyrä, jonka toinen pää siirtyy, säilyttää muotonsa suhteessa päihinsä. Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Työkalun pikanäppäimen pitäminen painettuna valitsee työkalun, kunnes päästät irti, ja sitten edellinen työkalu valitaan uudelleen. Shows the bounding box while you move the selection or draw a shape. Näyttää rajausruudun, kun siirrät valintaa tai piirrät muotoa. Create Trim Marks draws Japanese-style marks instead of Roman ones. Luo leikkuumerkit piirtää japanilaistyyliset merkit roomalaisten sijaan. @@ -5030,6 +5045,14 @@ liquify-list-end {0}, {1} {0} ja {1} @msg is a prompt's answer, whose `value` must be a string or null on prompt-vastaus, joten sen `value`-arvon on oltava merkkijono tai null @msg must have `kind` alert, confirm or prompt `kind`-arvon on oltava alert, confirm tai prompt @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` on vain ajolle, jossa ei ole ketään kysyttävää: sovelluksessa henkilö vastaa jokaiseen valintaikkunaan +@msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` on oltava kokonaisluku väliltä 1–{_1} +@msg `args{place}` is nested more than 64 levels deep `args{place}` on sisäkkäin yli 64 tason syvyydellä +@msg `args` must be an object `args` on oltava objekti +@msg `args` is larger than 1 MiB `args` on suurempi kuin 1 MiB +@msg `path` is empty `path` on tyhjä +@msg `installed` takes a `path`, not a `source` `installed` ottaa `path`-arvon, ei `source`-arvoa +@msg `path` must name a .js or .jsx file `path` on oltava .js- tai .jsx-tiedosto +@msg give exactly one of `path` and `source` anna tasan yksi arvoista `path` ja `source` @msg Running a script Suoritetaan komentosarjaa @msg Copied the script report Komentosarjan raportti kopioitiin @msg Script file access denied: {path} Komentosarjan tiedostojen käyttö estettiin: {path} @@ -5283,6 +5306,7 @@ liquify-list-end {0}, {1} {0} ja {1} @msg choose a folder to export to valitse kansio, johon viedään @msg choose a location for the package valitse paketin sijainti @msg clipboard is empty leikepöytä on tyhjä +@msg colorTable.deleted: at least one color has to stay in the color table colorTable.deleted: väritaulukkoon on jäätävä vähintään yksi väri @msg colorTable.{what}: `{h}` is not a colour such as "#ff8800" colorTable.{what}: `{h}` ei ole väri, kuten "#ff8800" @msg colorTable.{what}: at most {MAX_TABLE} colours colorTable.{what}: enintään {MAX_TABLE} väriä @msg command `{0}` is not available right now: {1} komento `{0}` ei ole nyt käytettävissä: {1} @@ -5350,6 +5374,12 @@ liquify-list-end {0}, {1} {0} ja {1} @msg no PNG encoder ei PNG-kooderia @msg no active document ei aktiivista asiakirjaa @msg no active perspective plane ei aktiivista perspektiivitasoa +@msg the perspective grid is hidden perspektiiviruudukko on piilotettu +@msg Automatic Plane Positioning is off: turn on anchorPoint or gridlineIntersection (perspective.widget.options) Tason automaattinen sijoittaminen on pois päältä: ota käyttöön anchorPoint tai gridlineIntersection (perspective.widget.options) +@msg anchorPoint must be true or false anchorPoint-arvon on oltava true tai false +@msg gridlineIntersection must be true or false gridlineIntersection-arvon on oltava true tai false +@msg tolerance must be 0 or more tolerance-arvon on oltava 0 tai enemmän +@msg give `at` or `clear`, not both anna `at` tai `clear`, ei molempia @msg no anchor points selected ankkuripisteitä ei ole valittu @msg `points` must be two or three [x, y] pairs of numbers `points` on annettava kahtena tai kolmena lukuparina [x, y] @msg direct-select two or three anchor points, or give `points` valitse suoraan kaksi tai kolme ankkuripistettä tai anna `points` @@ -5818,6 +5848,8 @@ variable-list-end {0}, {1} {0} ja {1} @msg Reload the page to go on (changes not saved yet may be lost). Lataa sivu uudelleen jatkaaksesi (tallentamattomat muutokset voivat kadota). @msg tool (a tool id) is required tool (työkalun tunnus) vaaditaan @msg {tool} isn't in a toolbar group of several tools {tool} ei ole usean työkalun työkaluriviryhmässä +@msg Presentation Mode hides the toolbars: change the screen mode to show them Esitystila piilottaa työkalurivit: tuo ne näkyviin vaihtamalla näyttötilaa +@msg Tab has hidden the toolbars: press Tab to show them Tab on piilottanut työkalurivit: tuo ne näkyviin painamalla Tab-näppäintä @msg onto must name a panel floating in another group onto-arvon on nimettävä toisessa ryhmässä kelluva paneeli @msg below and above must name a panel floating in another group below- ja above-arvojen on nimettävä toisessa ryhmässä kelluva paneeli @msg give only one of onto, below and above anna vain yksi arvoista onto, below ja above @@ -5908,6 +5940,7 @@ variable-list-end {0}, {1} {0} ja {1} @msg a linked JavaScript file is outside the read roots linkitetty JavaScript-tiedosto on lukujuurten ulkopuolella @msg a linked image file is outside the read roots linkitetty kuvatiedosto on lukujuurten ulkopuolella @msg a linked file's export folder is outside the read roots linkitetyn tiedoston vientikansio on lukujuurten ulkopuolella +@msg a linked file's editing data can't be read to check it against the read roots linkitetyn tiedoston muokkaustietoja ei voi lukea niiden tarkistamiseksi lukujuuria vasten @msg the library's file is outside the read roots kirjaston tiedosto on lukujuurten ulkopuolella @msg {file} names more than one linked JavaScript file {file} vastaa useampaa kuin yhtä linkitettyä JavaScript-tiedostoa @msg automation path rejected: outside the write root {root}: {path} automaation polku hylättiin: kirjoitusjuuren {root} ulkopuolella: {path} @@ -6321,6 +6354,7 @@ mark-style Japanese Japanilainen Cove Kouru Depth Syvyys Front Edestä + Side Sivulta Isometric Bottom Isometrinen ala Isometric Left Isometrinen vasen Isometric Right Isometrinen oikea @@ -6416,7 +6450,7 @@ mark-style Japanese Japanilainen @msg each of `{GRAPHICS}` must be an object jokaisen `{GRAPHICS}`-kohteen on oltava objekti @msg `{GRAPHICS}` entries take symbol, face, x, y, scale and rotation, not `{k}` `{GRAPHICS}`-kohteet hyväksyvät arvot symbol, face, x, y, scale ja rotation, eivät arvoa `{k}` @msg each of `{GRAPHICS}` needs `symbol`, the name of a symbol jokainen `{GRAPHICS}`-kohde tarvitsee arvon `symbol`, symbolin nimen -@msg `{GRAPHICS}` face must be front or back `{GRAPHICS}`-kohteen face-arvon on oltava front tai back +@msg `{GRAPHICS}` face must be front, back or side `{GRAPHICS}`-kohteen face-arvon on oltava front, back tai side @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} `{GRAPHICS}`-kohteen {key}-arvon on oltava luku, joka on vähintään {lo} ja enintään {hi} @msg `{GRAPHICS}` must be an array `{GRAPHICS}` on oltava taulukko @msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types Grafiikat sijoitetaan objektityypeille Taso, Pursota, Pyöräytä ja Täytä ilmalla @@ -7809,6 +7843,14 @@ breakText Glyphs Merkit Remove Gaps Poista välit @msg that makes too many pieces (at most 100000): make the dashes longer siitä tulee liian monta osaa (enintään 100000): pidennä viivoja @msg select paths, or segments, to divide valitse jaettavat polut tai segmentit +# Path Precision Tools add-on: Smooth Bridge. + Smooth Bridge… Pehmeä silta… + Smooth Bridge Pehmeä silta + Keep Originals Säilytä alkuperäiset +@msg select two circles to bridge valitse kaksi yhdistettävää ympyrää +@msg one circle is inside the other toinen ympyrä on toisen sisällä +@msg the circles are too far apart for this radius: raise the radius ympyrät ovat liian kaukana toisistaan tälle säteelle: suurenna sädettä +@msg the circles are too far apart for this radius ympyrät ovat liian kaukana toisistaan tälle säteelle # Path Precision Tools add-on: Common Tangents. Common Tangents… Yhteiset tangentit… Common Tangents Yhteiset tangentit diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index fc0a97a1a0..01e15553dd 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -142,6 +142,7 @@ Add to Swatches Ajouter au nuancier Add Used Colors Ajouter les couleurs utilisées Additional Plug-ins Folder Dossier de modules externes supplémentaires + Plug-in Instruction Budget Budget d’instructions des modules externes Additional Fonts Folder Dossier de polices supplémentaires Adjust Adjoining Width Points Ajuster les points de largeur adjacents Incoming Entrant @@ -818,6 +819,8 @@ font-technology Variable Variables Delete Artboard Supprimer le plan de travail Delete Artboards Supprimer les plans de travail Delete Brush Supprimer la forme + Delete Color Supprimer la couleur + Restore Generated Table Restaurer la table générée Delete Character Style Supprimer le style de caractère Delete Empty Artboards Supprimer les plans de travail vides Delete Freeform Point Supprimer le point libre @@ -887,6 +890,7 @@ font-technology Variable Variables Direct Selection Tool Outil Sélection directe Direction Handles Poignées de direction Disable Auto Add/Delete Désactiver l’ajout/suppression automatique + Interpolate Control Points When Moving Anchors Interpoler les poignées de direction lors du déplacement des points d’ancrage Disable Opacity Mask Désactiver le masque d’opacité Discard Ignorer Discard Empty Type Supprimer le texte vide @@ -2246,6 +2250,7 @@ font-technology Variable Variables Scatter: Dispersion : Rotation: Rotation : Rotation relative to: Rotation par rapport à : + Hue Jitter: Variation de teinte : Brush Scale Options Options de mise à l’échelle de la forme Scale Proportionately Mettre à l’échelle proportionnellement Stretch to Fit Stroke Length Étirer selon la longueur du contour @@ -2282,6 +2287,7 @@ font-technology Variable Variables Black and white stay as they are. Dark colors become shades of the stroke color and light colors become tints of it. Le noir reste noir et le blanc reste blanc. Les autres couleurs deviennent des ombres de la couleur du contour quand elles sont foncées et des teintes de celle-ci quand elles sont claires. The key color becomes the stroke color. The other colors shift their hue by the same amount and keep their saturation and brightness. La couleur clé devient la couleur du contour. Les autres couleurs tournent sur le cercle chromatique autant que la couleur clé et gardent leur saturation et leur luminosité. Key Color: Couleur clé : + Roundness Arrondi Roundness: Arrondi : Fixed Fixe Pressure Pression @@ -2720,6 +2726,7 @@ font-technology Variable Variables Line Properties: Propriétés de la ligne : Line Length: Longueur de la ligne : Line Angle: Angle de la ligne : + Constrain Pie Angle Conserver l’angle du secteur Polygon Tool Outil Polygone Portrait Portrait Power Saving (integrated) Économie d’énergie (intégrée) @@ -2879,6 +2886,9 @@ digits Malayalam Malayalam Real World: Monde réel : Real-time Drawing and Editing Dessin et édition en temps réel Use Monitor Profile for Canvas Utiliser le profil du moniteur pour la zone de travail + Refresh Monitor Profile Actualiser le profil du moniteur +@msg turn on Use Monitor Profile for Canvas first activez d’abord « Utiliser le profil du moniteur pour la zone de travail » +@msg this build doesn't read display profiles cette version ne lit pas les profils d’affichage The canvas is drawn in sRGB. La zone de travail est affichée en sRGB. Canvas display profile: Profil d’affichage de la zone de travail : The system matches the window to the display's colors. Le système adapte la fenêtre aux couleurs de l’écran. @@ -3140,6 +3150,7 @@ digits Malayalam Malayalam The mouse wheel with Cmd/Ctrl held scrolls the canvas sideways. La molette de la souris avec Cmd/Ctrl enfoncée fait défiler la zone de travail latéralement. Dragging sideways on a numeric field's label changes the field's value. Faire glisser latéralement le libellé d’un champ numérique modifie la valeur du champ. A two-finger rotate gesture on a trackpad rotates the canvas view. Un geste de rotation à deux doigts sur un pavé tactile fait pivoter la vue de la zone de travail. + When you move anchor points, each curve with one moved end keeps its shape relative to its ends. Quand vous déplacez des points d’ancrage, chaque courbe dont une extrémité bouge garde sa forme par rapport à ses extrémités. Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Maintenir le raccourci d’un outil choisit cet outil jusqu’à ce que vous le relâchiez, puis l’outil précédent est de nouveau choisi. Shows the bounding box while you move the selection or draw a shape. Affiche le cadre de sélection pendant que vous déplacez la sélection ou dessinez une forme. Create Trim Marks draws Japanese-style marks instead of Roman ones. Créer des traits de coupe dessine des traits de style japonais au lieu de traits romains. @@ -3449,6 +3460,9 @@ digits Malayalam Malayalam Search commands, tools, panels and effects… Chercher commandes, outils, panneaux et effets… No commands match Aucune commande ne correspond {pos} of {total}: {name} {pos} sur {total} : {name} + No menu item Aucun élément de menu + Toolbar Barre d’outils + {toolbar}, in the {tool} group {toolbar}, dans le groupe {tool} @plural {n} result|{n} results {n} résultat|{n} résultats @plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} sur {n} résultat. Continuez à taper pour les affiner.|{shown} sur {n} résultats. Continuez à taper pour les affiner. Recent Commands Commandes récentes @@ -4534,6 +4548,7 @@ imageTrace Outline Contour Bevel Biseauté Offset Décalage Axis Axe + Axis Angle Angle de l’axe axis Horizontal Horizontal axis Vertical Vertical axis Both Les deux @@ -4761,6 +4776,14 @@ liquify-list-end {0}, {1} {0} et {1} @msg `name` must be the name of a script engine `name` doit être le nom d’un moteur de script @msg the main script engine is new for each run and is never kept, so it cannot be dropped le moteur de script principal est nouveau à chaque exécution et n’est jamais conservé, il ne peut donc pas être supprimé @msg there is no script engine named {name} il n’y a aucun moteur de script nommé {name} +@msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` doit être un nombre entier de 1 à {_1} +@msg `args{place}` is nested more than 64 levels deep `args{place}` est imbriqué sur plus de 64 niveaux +@msg `args` must be an object `args` doit être un objet +@msg `args` is larger than 1 MiB `args` dépasse 1 Mio +@msg `path` is empty `path` est vide +@msg `installed` takes a `path`, not a `source` `installed` prend un `path`, pas un `source` +@msg `path` must name a .js or .jsx file `path` doit désigner un fichier .js ou .jsx +@msg give exactly one of `path` and `source` indiquez exactement un paramètre parmi `path` et `source` @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` est réservé à une exécution sans personne à qui demander : dans l’application, la personne répond à chaque boîte de dialogue @msg Running a script Exécution d’un script @msg Copied the script report Rapport du script copié @@ -5026,6 +5049,7 @@ liquify-list-end {0}, {1} {0} et {1} @msg choose a folder to export to choisissez un dossier d’exportation @msg choose a location for the package choisissez un emplacement pour l’assemblage @msg clipboard is empty le presse-papiers est vide +@msg colorTable.deleted: at least one color has to stay in the color table colorTable.deleted: au moins une couleur doit rester dans la table des couleurs @msg colorTable.{what}: `{h}` is not a colour such as "#ff8800" colorTable.{what} : `{h}` n’est pas une couleur comme "#ff8800" @msg colorTable.{what}: at most {MAX_TABLE} colours colorTable.{what} : {MAX_TABLE} couleurs au maximum @msg command `{0}` is not available right now: {1} la commande `{0}` n’est pas disponible pour le moment : {1} @@ -5093,6 +5117,12 @@ liquify-list-end {0}, {1} {0} et {1} @msg no PNG encoder aucun encodeur PNG @msg no active document aucun document actif @msg no active perspective plane aucun plan de perspective actif +@msg the perspective grid is hidden la grille de perspective est masquée +@msg Automatic Plane Positioning is off: turn on anchorPoint or gridlineIntersection (perspective.widget.options) Le positionnement automatique du plan est désactivé : activez anchorPoint ou gridlineIntersection (perspective.widget.options) +@msg anchorPoint must be true or false anchorPoint doit valoir true ou false +@msg gridlineIntersection must be true or false gridlineIntersection doit valoir true ou false +@msg tolerance must be 0 or more tolerance doit être supérieur ou égal à 0 +@msg give `at` or `clear`, not both indiquez `at` ou `clear`, pas les deux @msg no anchor points selected aucun point d’ancrage sélectionné @msg `points` must be two or three [x, y] pairs of numbers `points` doit contenir deux ou trois paires de nombres [x, y] @msg direct-select two or three anchor points, or give `points` sélectionnez deux ou trois points d’ancrage avec l’outil Sélection directe, ou indiquez `points` @@ -5563,6 +5593,8 @@ variable-list-end {0}, {1} {0} et {1} @msg Reload the page to go on (changes not saved yet may be lost). Rechargez la page pour continuer (les modifications non encore enregistrées risquent d’être perdues). @msg tool (a tool id) is required tool (un identifiant d’outil) est obligatoire @msg {tool} isn't in a toolbar group of several tools {tool} ne fait pas partie d’un groupe de plusieurs outils dans la barre d’outils +@msg Presentation Mode hides the toolbars: change the screen mode to show them pour afficher les barres d’outils masquées par le Mode Présentation, changez de mode d’affichage +@msg Tab has hidden the toolbars: press Tab to show them pour afficher les barres d’outils masquées par Tab, appuyez sur Tab @msg onto must name a panel floating in another group onto doit désigner un panneau flottant dans un autre groupe @msg below and above must name a panel floating in another group below et above doivent désigner un panneau flottant dans un autre groupe @msg give only one of onto, below and above indiquez un seul de onto, below et above @@ -5703,6 +5735,7 @@ variable-list-end {0}, {1} {0} et {1} @msg a linked JavaScript file is outside the read roots un fichier JavaScript lié est hors des dossiers racines de lecture @msg a linked image file is outside the read roots un fichier image lié est hors des dossiers racines de lecture @msg a linked file's export folder is outside the read roots le dossier d’exportation d’un fichier lié est hors des dossiers racines de lecture +@msg a linked file's editing data can't be read to check it against the read roots impossible de lire les données d’édition d’un fichier lié pour les vérifier par rapport aux dossiers racines de lecture @msg automation path rejected: outside the write root {root}: {path} chemin d’automatisation refusé : hors du dossier racine d’écriture {root} : {path} @msg automation path rejected: outside the write roots {roots}: {path} chemin d’automatisation refusé : hors des dossiers racines d’écriture {roots} : {path} @msg automation path rejected: path is empty chemin d’automatisation refusé : le chemin est vide @@ -5984,6 +6017,7 @@ lighting Light Lumière Cove Cavet Depth Profondeur Front Avant + Side Côté Isometric Bottom Isométrique dessous Isometric Left Isométrique gauche Isometric Right Isométrique droite @@ -6078,6 +6112,7 @@ lighting Light Lumière @msg each of `{GRAPHICS}` must be an object chaque élément de `{GRAPHICS}` doit être un objet @msg `{GRAPHICS}` entries take symbol, face, x, y, scale and rotation, not `{k}` les éléments de `{GRAPHICS}` acceptent symbol, face, x, y, scale et rotation, pas `{k}` @msg each of `{GRAPHICS}` needs `symbol`, the name of a symbol chaque élément de `{GRAPHICS}` nécessite `symbol`, le nom d’un symbole +@msg `{GRAPHICS}` face must be front, back or side face de `{GRAPHICS}` doit valoir front, back ou side @msg `{GRAPHICS}` face must be front or back face de `{GRAPHICS}` doit valoir front ou back @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} {key} de `{GRAPHICS}` doit être un nombre de {lo} à {hi} @msg `{GRAPHICS}` must be an array `{GRAPHICS}` doit être un tableau @@ -7740,6 +7775,14 @@ breakText Glyphs Glyphes Remove Gaps Supprimer les écarts @msg that makes too many pieces (at most 100000): make the dashes longer cela donne trop de morceaux (100000 au plus) : allongez les tirets @msg select paths, or segments, to divide sélectionnez des tracés ou des segments à diviser +# Path Precision Tools add-on: Smooth Bridge. + Smooth Bridge… Pont lissé… + Smooth Bridge Pont lissé + Keep Originals Conserver les originaux +@msg select two circles to bridge sélectionnez deux cercles à relier +@msg one circle is inside the other un cercle est à l’intérieur de l’autre +@msg the circles are too far apart for this radius: raise the radius les cercles sont trop éloignés pour ce rayon : augmentez le rayon +@msg the circles are too far apart for this radius les cercles sont trop éloignés pour ce rayon # Path Precision Tools add-on: Common Tangents. Common Tangents… Tangentes communes… Common Tangents Tangentes communes diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index bb504144ab..719175956a 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -164,6 +164,7 @@ Add to the Current Shortcuts વર્તમાન શૉર્ટકટમાં ઉમેરો Additional Fonts Folder વધારાનું ફોન્ટ ફોલ્ડર Additional Plug-ins Folder વધારાનું પ્લગ-ઇન ફોલ્ડર + Plug-in Instruction Budget પ્લગ-ઇન સૂચના બજેટ Adjust Adjoining Width Points અડીને આવેલા પહોળાઈ બિંદુઓ ગોઠવો Incoming આવતી બાજુ Outgoing જતી બાજુ @@ -230,6 +231,7 @@ Anchors selected: {count} પસંદ કરેલા એન્કર: {count} Anchors: એન્કર: Angle ખૂણો + Axis Angle અક્ષનો ખૂણો Angle: ખૂણો: Angled Strokes… ત્રાંસા સ્ટ્રોક… Angles ખૂણા @@ -920,6 +922,8 @@ Delete Artboard આર્ટબોર્ડ કાઢી નાખો Delete Artboards આર્ટબોર્ડ્સ કાઢી નાખો Delete Brush બ્રશ કાઢી નાખો + Delete Color રંગ કાઢી નાખો + Restore Generated Table જનરેટ થયેલું ટેબલ પુનઃસ્થાપિત કરો Delete Character Style અક્ષર સ્ટાઇલ કાઢી નાખો Delete Data Set ડેટા સેટ કાઢી નાખો Delete Data Sets ડેટા સેટ્સ કાઢી નાખો @@ -1011,6 +1015,7 @@ Direction: દિશા: Directives નિર્દેશો Disable Auto Add/Delete ઑટો ઍડ/ડિલીટ બંધ કરો + Interpolate Control Points When Moving Anchors એન્કર બિંદુઓ ખસેડતી વખતે દિશા હેન્ડલ્સ ઇન્ટરપોલેટ કરો Disable Opacity Mask ઓપેસિટી માસ્ક બંધ કરો Disable and Continue બંધ કરો અને ચાલુ રાખો Disabled plug-ins બંધ કરેલા પ્લગ-ઇન્સ @@ -1530,6 +1535,7 @@ From Selection પસંદગીમાંથી From: થી: Front આગળ + Side બાજુ Full Document સંપૂર્ણ દસ્તાવેજ Full Justify સંપૂર્ણ જસ્ટિફાય Full Screen Mode ફુલ સ્ક્રીન મોડ @@ -1929,6 +1935,7 @@ Kashidas કાશીદા Keep Formatting ફોર્મેટિંગ રાખો Keep Original મૂળ રાખો + Keep Originals મૂળ રાખો Keep Plain Text સાદો ટેક્સ્ટ રાખો Keep Shared Points Together વહેંચાયેલા પોઇન્ટ સાથે રાખો Keep Tools Beside the Canvas ટૂલ્સ કેનવાસની બાજુમાં રાખો @@ -2788,6 +2795,7 @@ Line Properties: રેખાના ગુણધર્મો: Line Length: રેખાની લંબાઈ: Line Angle: રેખાનો કોણ: + Constrain Pie Angle પાઇ કોણ મર્યાદિત કરો Polygon Tool બહુકોણ ટૂલ Polygonal Lasso બહુકોણીય લાસો Polygonal Lasso Tool બહુકોણીય લાસો ટૂલ @@ -3213,6 +3221,7 @@ The mouse wheel with Cmd/Ctrl held scrolls the canvas sideways. Cmd/Ctrl દબાવી રાખીને માઉસ વ્હીલ ફેરવવાથી કેનવાસ બાજુમાં સ્ક્રોલ થાય છે. Dragging sideways on a numeric field's label changes the field's value. સંખ્યાત્મક ફીલ્ડના લેબલ પર બાજુમાં ખેંચવાથી ફીલ્ડનું મૂલ્ય બદલાય છે. A two-finger rotate gesture on a trackpad rotates the canvas view. ટ્રેકપેડ પર બે આંગળીથી ફેરવવાનો હાવભાવ કેનવાસનું દૃશ્ય ફેરવે છે. + When you move anchor points, each curve with one moved end keeps its shape relative to its ends. જ્યારે તમે એન્કર પોઇન્ટ ખસેડો છો, ત્યારે એક ખસેલા છેડાવાળો દરેક વળાંક તેના છેડાઓની સાપેક્ષે પોતાનો આકાર જાળવે છે. Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. ટૂલની શોર્ટકટ કી દબાવી રાખવાથી છોડો ત્યાં સુધી તે ટૂલ પસંદ રહે છે, પછી અગાઉનું ટૂલ ફરી પસંદ થાય છે. Shows the bounding box while you move the selection or draw a shape. તમે પસંદગી ખસેડો કે આકાર દોરો ત્યારે બાઉન્ડિંગ બોક્સ બતાવે છે. Create Trim Marks draws Japanese-style marks instead of Roman ones. ટ્રિમ માર્ક્સ બનાવો રોમન ને બદલે જાપાની શૈલીના ચિહ્નો દોરે છે. @@ -3337,6 +3346,7 @@ Rotation Y પરિભ્રમણ Y Rotation Z પરિભ્રમણ Z Rotation relative to: આના સાપેક્ષે પરિભ્રમણ: + Hue Jitter: રંગછટામાં ફેરફાર: Rotation: પરિભ્રમણ: Rough Pastels… રફ પેસ્ટલ્સ… Roughen… રફ બનાવો… @@ -3348,6 +3358,7 @@ Rounded Rectangle ગોળાકાર લંબચોરસ Rounded Rectangle Tool ગોળાકાર લંબચોરસ ટૂલ Rounded Rectangle… ગોળાકાર લંબચોરસ… + Roundness ગોળાઈ Roundness: ગોળાઈ: Row Size: પંક્તિનું માપ: Rows પંક્તિઓ @@ -3558,6 +3569,12 @@ Search commands, tools, panels and effects… આદેશો, ટૂલ્સ, પેનલ્સ અને ઇફેક્ટ્સ શોધો… No commands match કોઈ આદેશ મેળ ખાતો નથી {pos} of {total}: {name} {total} માંથી {pos}: {name} + No menu item કોઈ મેનૂ આઇટમ નથી + Toolbar ટૂલબાર + {toolbar}, in the {tool} group {toolbar}, {tool} જૂથમાં + Tool ટૂલ + Command કમાન્ડ + Panel પેનલ @plural {n} result|{n} results {n} પરિણામ|{n} પરિણામો @plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {n} માંથી {shown} પરિણામ. તેમને સંકુચિત કરવા લખતા રહો.|{n} માંથી {shown} પરિણામો. તેમને સંકુચિત કરવા લખતા રહો. Recent Commands તાજેતરના આદેશો @@ -3865,6 +3882,8 @@ Report Results પરિણામોનો અહેવાલ Smooth સ્મૂધ Smooth Anchors… એન્કર સ્મૂધ કરો… + Smooth Bridge સ્મૂધ બ્રિજ + Smooth Bridge… સ્મૂધ બ્રિજ… Smooth Tool સ્મૂધ ટૂલ Smooth… સ્મૂધ કરો… Smudge Stick… સ્મજ સ્ટિક… @@ -4701,6 +4720,7 @@ antiAlias Sharp શાર્પ Include Placed Images પ્લેસ કરેલી ઇમેજો સામેલ કરો Include Fill Hatches ફિલ હેચિસ સામેલ કરો Use Monitor Profile for Canvas કેનવાસ માટે મોનિટર પ્રોફાઇલ વાપરો + Refresh Monitor Profile મોનિટર પ્રોફાઇલ તાજી કરો The canvas is drawn in sRGB. કેનવાસ sRGBમાં દોરાય છે. Canvas display profile: કેનવાસ ડિસ્પ્લે પ્રોફાઇલ: The system matches the window to the display's colors. સિસ્ટમ વિન્ડોના રંગો ડિસ્પ્લેના રંગો સાથે મેળવે છે. diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index a995907bd6..36bfd90eb2 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -257,6 +257,7 @@ Add Used Colors उपयोग किए रंग जोड़ें Additional Fonts Folder अतिरिक्त फ़ॉन्ट फ़ोल्डर Additional Plug-ins Folder अतिरिक्त प्लग-इन फ़ोल्डर + Plug-in Instruction Budget प्लग-इन निर्देश बजट Adjust Adjoining Width Points सटे हुए चौड़ाई पॉइंट समायोजित करें Incoming आने वाली ओर Outgoing जाने वाली ओर @@ -537,6 +538,7 @@ antiAlias Sharp शार्प Average… औसत… Away from the Line लाइन से दूर Axis अक्ष + Axis Angle अक्ष कोण Axis side अक्ष की तरफ़ Axis: अक्ष: B4 B4 @@ -1315,6 +1317,8 @@ antiAlias Sharp शार्प Delete Artboard आर्टबोर्ड हटाएँ Delete Artboards आर्टबोर्ड्स हटाएँ Delete Brush ब्रश हटाएँ + Delete Color रंग हटाएँ + Restore Generated Table जनरेट की गई तालिका पुनर्स्थापित करें Delete Character Style कैरेक्टर स्टाइल हटाएँ Delete Data Set डेटा सेट हटाएँ Delete Data Sets डेटा सेट्स हटाएँ @@ -1421,6 +1425,7 @@ antiAlias Sharp शार्प Direction: दिशा: Directives निर्देश Disable Auto Add/Delete ऑटो जोड़ना/हटाना अक्षम करें + Interpolate Control Points When Moving Anchors एंकर पॉइंट खिसकाते समय निर्देशन हैंडल इंटरपोलेट करें Disable Opacity Mask ओपेसिटी मास्क अक्षम करें Discard डिस्कर्ड Discard Empty Type खाली टाइप हटाएँ @@ -2089,6 +2094,7 @@ antiAlias Sharp शार्प From Selection सिलेक्शन से From: से: Front सामने + Side बगल Frosted फ़्रॉस्टेड Full Document पूरा डॉक्यूमेंट Full Justify फुल जस्टिफ़ाई @@ -2595,6 +2601,7 @@ antiAlias Sharp शार्प Keep graphics, colors and text styles here to use them in any document. Libraries are stored on this machine — no account required. ग्राफ़िक्स, रंग और टेक्स्ट स्टाइल्स यहाँ रखें ताकि किसी भी डॉक्यूमेंट में उपयोग कर सकें। लाइब्रेरीज़ इसी कंप्यूटर पर रहती हैं — अकाउंट की ज़रूरत नहीं है। Keep Handles हैंडल रखें Keep Original मूल रखें + Keep Originals मूल रखें Keep Plain Text प्लेन टेक्स्ट रखें Keep selected सिलेक्ट करें Keep Shared Points Together साझा पॉइंट्स एक साथ रखें @@ -3743,6 +3750,7 @@ antiAlias Sharp शार्प Line Properties: रेखा प्रॉपर्टीज़: Line Length: रेखा की लंबाई: Line Angle: रेखा का कोण: + Constrain Pie Angle पाई एंगल बनाए रखें Polygon Tool पॉलीगोन टूल Polygonal Lasso बहुभुज लैस्सो Polygonal Lasso Tool बहुभुज लैस्सो टूल @@ -3947,6 +3955,9 @@ antiAlias Sharp शार्प Real World: रियल वर्ल्ड: Real-time Drawing and Editing रियल टाइम ड्राइंग और संपादन Use Monitor Profile for Canvas कैनवास के लिए मॉनिटर प्रोफ़ाइल का उपयोग करें + Refresh Monitor Profile मॉनिटर प्रोफ़ाइल रिफ्रेश करें +@msg turn on Use Monitor Profile for Canvas first पहले "कैनवास के लिए मॉनिटर प्रोफ़ाइल का उपयोग करें" चालू करें +@msg this build doesn't read display profiles यह बिल्ड डिस्प्ले प्रोफ़ाइल नहीं पढ़ता The canvas is drawn in sRGB. कैनवास sRGB में बनाया जाता है। Canvas display profile: कैनवास की डिस्प्ले प्रोफ़ाइल: The system matches the window to the display's colors. सिस्टम विंडो को डिस्प्ले के रंगों से मिलाता है। @@ -4264,6 +4275,7 @@ antiAlias Sharp शार्प The mouse wheel with Cmd/Ctrl held scrolls the canvas sideways. Cmd/Ctrl दबाकर माउस व्हील घुमाने से कैनवास बगल की ओर स्क्रॉल होता है। Dragging sideways on a numeric field's label changes the field's value. किसी संख्या वाले फ़ील्ड के लेबल पर बगल की ओर ड्रैग करने से फ़ील्ड का मान बदलता है। A two-finger rotate gesture on a trackpad rotates the canvas view. ट्रैकपैड पर दो उंगलियों से घुमाने का जेस्चर कैनवास के व्यू को घुमाता है। + When you move anchor points, each curve with one moved end keeps its shape relative to its ends. जब आप एंकर पॉइंट हिलाते हैं, तो एक हिले हुए सिरे वाला हर वक्र अपने सिरों के सापेक्ष अपना आकार बनाए रखता है। Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. किसी टूल की शॉर्टकट कुंजी दबाए रखने पर वह टूल छोड़ने तक चुना रहता है, फिर पिछला टूल दोबारा चुना जाता है। Shows the bounding box while you move the selection or draw a shape. सिलेक्शन खिसकाते या आकार ड्रॉ करते समय बाउंडिंग बॉक्स दिखाता है। Create Trim Marks draws Japanese-style marks instead of Roman ones. ट्रिम मार्क्स बनाएं रोमन की जगह जापानी शैली के निशान ड्रॉ करता है। @@ -4409,6 +4421,7 @@ antiAlias Sharp शार्प Rotate… घुमाव… Rotation घुमाव Rotation relative to: इसके सापेक्ष: + Hue Jitter: रंगत में भिन्नता: Rotation X रोटेशन X Rotation Y रोटेशन वाई Rotation Z रोटेशन Z @@ -4429,6 +4442,7 @@ antiAlias Sharp शार्प Rounded Rectangle गोल आयत Rounded Rectangle Tool राउंडेड रेक्टेंगल टूल Rounded Rectangle… गोल आयत… + Roundness राउंडनेस Roundness: राउंडनेस: Row Size: पंक्ति का आकार: Rows पंक्तियाँ @@ -4640,6 +4654,9 @@ antiAlias Sharp शार्प Search commands, tools, panels and effects… आदेश, टूल, पैनल्स और इफ़ेक्ट्स खोजें… No commands match कोई आदेश मेल नहीं खाता {pos} of {total}: {name} {total} में से {pos}: {name} + No menu item कोई मेनू आइटम नहीं + Toolbar टूलबार + {toolbar}, in the {tool} group {toolbar}, {tool} समूह में @plural {n} result|{n} results {n} परिणाम|{n} परिणाम @plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {n} में से {shown} परिणाम। इन्हें सीमित करने के लिए लिखते रहें।|{n} में से {shown} परिणाम। इन्हें सीमित करने के लिए लिखते रहें। Recent Commands हाल के आदेश @@ -5042,6 +5059,8 @@ antiAlias Sharp शार्प Smooth स्मूथ Smooth Anchors चिकना एंकर Smooth Anchors… चिकना एंकर… + Smooth Bridge स्मूद ब्रिज + Smooth Bridge… स्मूद ब्रिज… Smooth Color चिकना रंग Smooth Tool चिकना टूल Smooth… चिकना करें… @@ -6275,6 +6294,8 @@ antiAlias Sharp शार्प @msg {std} files embed their fonts, and the file would have one that isn't {std} फ़ाइलें अपने फ़ॉन्ट एम्बेड करती हैं, और इस फ़ाइल में एक ऐसा फ़ॉन्ट होता जो एम्बेड नहीं है @msg {target} is the file this document was read from, and reading it left things out ({what}): writing over it would lose them for good. Write another file instead, or pass acknowledgeLoss: true to replace it anyway यह डॉक्यूमेंट {target} से पढ़ा गया था और पढ़ते समय कुछ चीज़ें छूट गईं ({what}): उसी फ़ाइल पर लिखने से वे स्थायी रूप से खो जाएँगी। दूसरी फ़ाइल लिखें या फिर भी बदलने के लिए acknowledgeLoss: true दें @msg {tool} isn't in a toolbar group of several tools {tool} कई टूल्स के टूलबार समूह में नहीं है +@msg Presentation Mode hides the toolbars: change the screen mode to show them प्रस्तुति मोड टूलबार्स छिपाता है: उन्हें दिखाने के लिए स्क्रीन मोड बदलें +@msg Tab has hidden the toolbars: press Tab to show them Tab ने टूलबार्स छिपा दिए हैं: उन्हें दिखाने के लिए Tab दबाएँ @msg {ty} brushes need selected art (or params.{k}) {ty} ब्रश के लिए सिलेक्टेड आर्टवर्क (या params.{k}) चाहिए @msg {v} is not an asset id {v} एक परिसंपत्ति आईडी नहीं है @msg {what} can't be intertwined {what} अंतर नहीं किया जा सकता है @@ -6835,6 +6856,7 @@ antiAlias Sharp शार्प @msg a linked JavaScript file is outside the read roots एक लिंक की गई जावास्क्रिप्ट फ़ाइल पढ़ने की जड़ों के बाहर है @msg a linked image file is outside the read roots एक लिंक की गई छवि फ़ाइल पढ़ने की जड़ों के बाहर है @msg a linked file's export folder is outside the read roots एक लिंक की गई फ़ाइल का निर्यात फ़ोल्डर पढ़ने की जड़ों के बाहर है +@msg a linked file's editing data can't be read to check it against the read roots एक लिंक की गई फ़ाइल का संपादन डेटा पढ़ने की जड़ों से जाँचने के लिए पढ़ा नहीं जा सकता @msg the library's file is outside the read roots लाइब्रेरी की फ़ाइल पढ़ने की जड़ों के बाहर है @msg {file} names more than one linked JavaScript file {file} एक से अधिक लिंक की गई जावास्क्रिप्ट फ़ाइलों से मेल खाता है @msg automation path rejected: outside the write root {root}: {path} स्वचालन पाथ खारिज: लिखने की जड़ के बाहर {root}: {path} @@ -6957,6 +6979,7 @@ antiAlias Sharp शार्प @msg color.profile: no RGB or CMYK profile is called “{profile}” color.profile: "{profile}" नाम की कोई RGB या CMYK प्रोफ़ाइल नहीं है @msg colorMode must be rgb or cmyk, not `{m}` colorMode को rgb या cmyk होना चाहिए, `{m}` नहीं @msg colorModel must be {own} (the document's mode), grayscale or bitmap colorModel को {own} (डॉक्यूमेंट का मोड), grayscale या bitmap होना चाहिए +@msg colorTable.deleted: at least one color has to stay in the color table colorTable.deleted: रंग तालिका में कम से कम एक रंग रहना चाहिए @msg colorTable.{what}: `{h}` is not a colour such as "#ff8800" colorTable.{what}: `{h}`, "#ff8800" जैसा रंग नहीं है @msg colorTable.{what}: at most {MAX_TABLE} colours colorTable.{what}: अधिकतम {MAX_TABLE} रंग @msg colour groups can't go into colour groups रंग समूह रंग समूहों में नहीं जा सकते हैं @@ -7177,6 +7200,14 @@ liquify-list-end {0}, {1} {0} और {1} @msg is a prompt's answer, whose `value` must be a string or null यह prompt का उत्तर है, इसलिए इसका `value` स्ट्रिंग या null होना चाहिए @msg must have `kind` alert, confirm or prompt `kind` alert, confirm या prompt होना चाहिए @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` केवल ऐसे रन के लिए है जिसमें पूछने के लिए कोई नहीं है: ऐप में, व्यक्ति हर डायलॉग का उत्तर देता है +@msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` 1 से {_1} तक की पूर्ण संख्या होनी चाहिए +@msg `args{place}` is nested more than 64 levels deep `args{place}` 64 से अधिक स्तर गहराई तक नेस्ट किया गया है +@msg `args` must be an object `args` एक ऑब्जेक्ट होना चाहिए +@msg `args` is larger than 1 MiB `args` 1 MiB से बड़ा है +@msg `path` is empty `path` खाली है +@msg `installed` takes a `path`, not a `source` `installed` एक `path` लेता है, `source` नहीं +@msg `path` must name a .js or .jsx file `path` में किसी .js या .jsx फ़ाइल का नाम होना चाहिए +@msg give exactly one of `path` and `source` `path` और `source` में से ठीक एक दें @msg Running a script स्क्रिप्ट चल रही है @msg Copied the script report Copied स्क्रिप्ट रिपोर्ट @msg Script file access denied: {path} स्क्रिप्ट की फ़ाइल पहुँच अस्वीकार की गई: {path} @@ -7763,6 +7794,12 @@ liquify-list-end {0}, {1} {0} और {1} @msg no active data set कोई सक्रिय डेटा सेट नहीं @msg no active document कोई सक्रिय डॉक्यूमेंट @msg no active perspective plane कोई सक्रिय पर्सपेक्टिव विमान नहीं +@msg the perspective grid is hidden पर्सपेक्टिव ग्रिड छिपा हुआ है +@msg Automatic Plane Positioning is off: turn on anchorPoint or gridlineIntersection (perspective.widget.options) स्वचालित प्लेन पोज़िशनिंग बंद है: anchorPoint या gridlineIntersection चालू करें (perspective.widget.options) +@msg anchorPoint must be true or false anchorPoint को true या false होना चाहिए +@msg gridlineIntersection must be true or false gridlineIntersection को true या false होना चाहिए +@msg tolerance must be 0 or more tolerance को 0 या अधिक होना चाहिए +@msg give `at` or `clear`, not both `at` या `clear` दें, दोनों नहीं @msg no anchor points selected कोई एंकर पॉइंट सिलेक्ट नहीं है @msg `points` must be two or three [x, y] pairs of numbers `points` में संख्याओं के दो या तीन [x, y] जोड़े होने चाहिए @msg direct-select two or three anchor points, or give `points` दो या तीन एंकर पॉइंट्स डायरेक्ट-सिलेक्ट करें, या `points` दें @@ -8114,6 +8151,7 @@ liquify-list-end {0}, {1} {0} और {1} @msg Offset Path: the offset leaves nothing of the selected paths (an inset larger than the shapes) ऑफसेट पाथ: ऑफ़सेट सिलेक्टेड पाथ की कुछ भी नहीं छोड़ता है (आकार की तुलना में एक निर्धारित बड़ा) @msg Offset Path: the path is too complex to offset ऑफसेट पाथ: पाथ ऑफसेट करने के लिए बहुत जटिल है @msg on must be true or false on को true या false होना चाहिए +@msg one circle is inside the other एक वृत्त दूसरे के अंदर है @msg only a dock group above or below others collapses, not one beside another केवल दूसरों के ऊपर या नीचे एक डॉक समूह गिर जाता है, एक दूसरे के बगल में नहीं @msg only an exporter or an importer declares `extensions` केवल एक्सपोर्टर या इंपोर्टर `extensions` घोषित करता है @msg only an object of the Global Edit other than the one it started from can be left out केवल ग्लोबल एडिट का एक ऑब्जेक्ट, इसके अलावा इसे शुरू किया जा सकता है, छोड़ दिया जा सकता है @@ -8459,6 +8497,7 @@ liquify-list-end {0}, {1} {0} और {1} @msg select the objects to attach to the path ऑब्जेक्ट्स का सिलेक्ट करने के लिए संलग्न करने के लिए पाथ @msg select the objects to bind ऑब्जेक्ट्स को बांधने के लिए चुनें @msg select the objects to transform in perspective ऑब्जेक्ट्स को पर्सपेक्टिव में बदलने के लिए चुनें +@msg select two circles to bridge जोड़ने के लिए दो वृत्त चुनें @msg select two open path ends, or two open paths, to average and join औसत निकालकर जोड़ने के लिए दो खुले पाथ एंड पॉइंट्स या दो खुले पाथ सिलेक्ट करें @msg select two or more graphic styles to merge दो या अधिक ग्राफिक स्टाइल्स का सिलेक्ट करने के लिए विलय @msg select two or more objects to distribute वितरित करने के लिए दो या दो से अधिक ऑब्जेक्ट चुनें @@ -8603,7 +8642,7 @@ liquify-list-end {0}, {1} {0} और {1} @msg each of `{GRAPHICS}` must be an object `{GRAPHICS}` की हर प्रविष्टि एक ऑब्जेक्ट होनी चाहिए @msg `{GRAPHICS}` entries take symbol, face, x, y, scale and rotation, not `{k}` `{GRAPHICS}` की प्रविष्टियाँ symbol, face, x, y, scale और rotation लेती हैं, `{k}` नहीं @msg each of `{GRAPHICS}` needs `symbol`, the name of a symbol `{GRAPHICS}` की हर प्रविष्टि को `symbol` चाहिए, यानी किसी सिंबल का नाम -@msg `{GRAPHICS}` face must be front or back `{GRAPHICS}` का face, front या back होना चाहिए +@msg `{GRAPHICS}` face must be front, back or side `{GRAPHICS}` का face, front, back या side होना चाहिए @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} `{GRAPHICS}` का {key}, {lo} से {hi} तक की संख्या होना चाहिए @msg `{GRAPHICS}` must be an array `{GRAPHICS}` एक ऐरे होना चाहिए @msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types ग्राफ़िक्स समतल, एक्सट्रूड, रिवॉल्व और फुलाएँ ऑब्जेक्ट प्रकारों पर लगते हैं @@ -8645,6 +8684,8 @@ liquify-list-end {0}, {1} {0} और {1} @msg the background worker stopped पृष्ठभूमि कार्यकर्ता बंद कर दिया @msg the blend has no spine मिश्रण में कोई रीढ़ नहीं है @msg the character's size can't be measured कैरेक्टर का आकार मापा नहीं जा सकता है +@msg the circles are too far apart for this radius इस त्रिज्या के लिए वृत्त एक-दूसरे से बहुत दूर हैं +@msg the circles are too far apart for this radius: raise the radius इस त्रिज्या के लिए वृत्त एक-दूसरे से बहुत दूर हैं: त्रिज्या बढ़ाएँ @msg the CMYK image couldn't be written CMYK इमेज को नहीं लिखा जा सकता @msg the Color Picker is not open रंग पिकर खुला नहीं है @msg the compound shape is too complex to expand मिश्रित आकार का विस्तार करने के लिए बहुत जटिल है diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index c85ff75f0e..798ca1697d 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -211,6 +211,7 @@ Add Used Colors Használt színek hozzáadása Additional Fonts Folder További betűtípusok mappája Additional Plug-ins Folder További bővítmények mappája + Plug-in Instruction Budget Bővítmények utasításkerete Adjust Adjoining Width Points Szomszédos szélességi pontok igazítása Incoming Bejövő Outgoing Kimenő @@ -387,6 +388,7 @@ font-technology Variable Változó Average Átlagolás Average… Átlagolás… Axis Tengely + Axis Angle Tengely szöge Axis side Tengely oldala Axis: Tengely: B4 B4 @@ -1044,6 +1046,8 @@ font-technology Variable Változó Delete Artboard Rajztábla törlése Delete Artboards Rajztáblák törlése Delete Brush Ecset törlése + Delete Color Szín törlése + Restore Generated Table Előállított tábla visszaállítása Delete Character Style Karakterstílus törlése Delete Data Set Adatkészlet törlése Delete Empty Artboards Üres rajztáblák törlése @@ -1132,6 +1136,7 @@ font-technology Variable Változó Direction Handles Iránykezelő fogantyúk Direction: Irány: Disable Auto Add/Delete Automatikus hozzáadás és törlés kikapcsolása + Interpolate Control Points When Moving Anchors Iránykezelő fogantyúk interpolálása horgonypontok mozgatásakor Disable Opacity Mask Átlátszósági maszk kikapcsolása Discard Elvetés Discard Empty Type Üres szöveg elvetése @@ -3282,6 +3287,7 @@ diagnostics ui felület Line Properties: Vonal tulajdonságai: Line Length: Vonal hossza: Line Angle: Vonal szöge: + Constrain Pie Angle Körcikk szögének megtartása Polygon Tool Sokszög Portrait Álló Portrait (flipped) Álló (megfordítva) @@ -3461,6 +3467,9 @@ mark-style Japanese Japán Real World: Valós méret: Real-time Drawing and Editing Valós idejű rajzolás és szerkesztés Use Monitor Profile for Canvas Monitorprofil használata a vászonhoz + Refresh Monitor Profile Monitorprofil frissítése +@msg turn on Use Monitor Profile for Canvas first előbb kapcsolja be a „Monitorprofil használata a vászonhoz” beállítást +@msg this build doesn't read display profiles ez a változat nem olvassa be a kijelzőprofilokat The canvas is drawn in sRGB. A vászon sRGB-ben jelenik meg. Canvas display profile: A vászon kijelzőprofilja: The system matches the window to the display's colors. A rendszer a kijelző színeihez igazítja az ablakot. @@ -3734,6 +3743,7 @@ mark-style Japanese Japán The mouse wheel with Cmd/Ctrl held scrolls the canvas sideways. Az egérgörgő lenyomott Cmd/Ctrl billentyűvel oldalirányban görgeti a vásznat. Dragging sideways on a numeric field's label changes the field's value. Egy számmező címkéjén oldalirányban húzva módosul a mező értéke. A two-finger rotate gesture on a trackpad rotates the canvas view. Az érintőpadon végzett kétujjas forgató kézmozdulat elforgatja a vászon nézetét. + When you move anchor points, each curve with one moved end keeps its shape relative to its ends. Horgonypontok mozgatásakor minden olyan görbe, amelynek egyik vége elmozdul, megtartja az alakját a végeihez képest. Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Egy eszköz billentyűparancsát lenyomva tartva az eszköz a felengedésig ki van választva, utána ismét az előző eszköz lesz kiválasztva. Shows the bounding box while you move the selection or draw a shape. Megjeleníti a befoglaló keretet, miközben a kijelölést mozgatja vagy alakzatot rajzol. Create Trim Marks draws Japanese-style marks instead of Roman ones. A Vágójelek létrehozása római helyett japán stílusú jeleket rajzol. @@ -3872,6 +3882,7 @@ mark-style Japanese Japán Rotate… Elforgatás… Rotation Elforgatás Rotation relative to: Elforgatás viszonyítási alapja: + Hue Jitter: Színárnyalat-szórás: Rotation X X-elforgatás Rotation Y Y-elforgatás Rotation Z Z-elforgatás @@ -3890,6 +3901,7 @@ mark-style Japanese Japán Rounded Rectangle Lekerekített téglalap Rounded Rectangle Tool Lekerekített téglalap Rounded Rectangle… Lekerekített téglalap… + Roundness Kerekség Roundness: Kerekség: Row Size: Sorméret: Rows Sorok @@ -4083,6 +4095,9 @@ mark-style Japanese Japán Search commands, tools, panels and effects… Parancsok, eszközök, panelek és effektusok keresése… No commands match Nincs egyező parancs {pos} of {total}: {name} {pos}/{total}: {name} + No menu item Nincs menüpont + Toolbar Eszköztár + {toolbar}, in the {tool} group {toolbar}, a(z) {tool} csoportjában @plural {n} result|{n} results {n} találat @plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {n} találatból {shown} látható. Gépeljen tovább a szűkítéshez. Recent Commands Legutóbbi parancsok @@ -5388,6 +5403,7 @@ imageTrace Outline Körvonal @msg a linked JavaScript file is outside the read roots egy csatolt JavaScript-fájl kívül esik az olvasási gyökereken @msg a linked image file is outside the read roots egy csatolt képfájl kívül esik az olvasási gyökereken @msg a linked file's export folder is outside the read roots egy csatolt fájl exportálási mappája kívül esik az olvasási gyökereken +@msg a linked file's editing data can't be read to check it against the read roots egy csatolt fájl szerkesztési adatai nem olvashatók be az olvasási gyökerekkel való ellenőrzéshez @msg automation path rejected: outside the write root {root}: {path} az automatizálás útvonala elutasítva: kívül esik az írási gyökéren ({root}): {path} @msg automation path rejected: outside the write roots {roots}: {path} az automatizálás útvonala elutasítva: kívül esik az írási gyökereken ({roots}): {path} @msg automation path rejected: parent traversal below a folder that doesn't exist: {path} az automatizálás útvonala elutasítva: szülőmappára lépés egy nem létező mappa alatt: {path} @@ -5437,6 +5453,7 @@ imageTrace Outline Körvonal @msg choose the font files to add válaszd ki a hozzáadandó betűtípusfájlokat @msg clipboard is empty a vágólap üres @msg closing needs three anchors a lezáráshoz három horgonypont kell +@msg colorTable.deleted: at least one color has to stay in the color table colorTable.deleted: legalább egy színnek a színtáblában kell maradnia @msg colorTable.{what}: `{h}` is not a colour such as "#ff8800" colorTable.{what}: `{h}` nem szín (például "#ff8800") @msg colorTable.{what}: at most {MAX_TABLE} colours colorTable.{what}: legfeljebb {MAX_TABLE} szín @msg column must be true or a number from 1 a column értéke true vagy 1-től kezdődő szám lehet @@ -5606,6 +5623,14 @@ liquify-list-end {0}, {1} {0} és {1} @msg there is no script engine named {name} nincs {name} nevű parancsfájlmotor @msg `answers[{i}]` {e} `answers[{i}]`: {e} @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog az `answers` csak olyan futtatáshoz való, ahol nincs kit megkérdezni: az alkalmazásban minden párbeszédpanelre a felhasználó válaszol +@msg `maxFuel` must be a whole number from 1 to {_1} a `maxFuel` értéke 1 és {_1} közötti egész szám lehet +@msg `args{place}` is nested more than 64 levels deep az `args{place}` 64 szintnél mélyebben van egymásba ágyazva +@msg `args` must be an object az `args` értékének objektumnak kell lennie +@msg `args` is larger than 1 MiB `args`: nagyobb 1 MiB-nál +@msg `path` is empty a `path` üres +@msg `installed` takes a `path`, not a `source` az `installed` `path` értéket vár, nem `source` értéket +@msg `path` must name a .js or .jsx file a `path` értékének .js vagy .jsx fájlt kell megadnia +@msg give exactly one of `path` and `source` pontosan egyet adj meg ezek közül: `path`, `source` @msg Running a script Parancsfájl futtatása @msg Copied the script report Szkriptjelentés másolva @msg Script file access denied: {path} A parancsfájl fájlhozzáférése megtagadva: {path} @@ -5797,6 +5822,12 @@ liquify-list-end {0}, {1} {0} és {1} @msg name the file adj nevet a fájlnak @msg no active document nincs aktív dokumentum @msg no active perspective plane nincs aktív perspektivikus sík +@msg the perspective grid is hidden a perspektivikus rács rejtett +@msg Automatic Plane Positioning is off: turn on anchorPoint or gridlineIntersection (perspective.widget.options) Az automatikus síkpozicionálás ki van kapcsolva: kapcsold be az anchorPoint vagy a gridlineIntersection beállítást (perspective.widget.options) +@msg anchorPoint must be true or false anchorPoint: true vagy false kell +@msg gridlineIntersection must be true or false gridlineIntersection: true vagy false kell +@msg tolerance must be 0 or more tolerance: 0 vagy nagyobb érték kell +@msg give `at` or `clear`, not both az `at` vagy a `clear` értéket add meg, ne mindkettőt @msg no anchor points selected nincs kijelölt horgonypont @msg `points` must be two or three [x, y] pairs of numbers a `points` két vagy három [x, y] számpár legyen @msg direct-select two or three anchor points, or give `points` jelölj ki közvetlen kijelöléssel két vagy három horgonypontot, vagy add meg a `points` értéket @@ -6381,6 +6412,8 @@ variable-list-end {0}, {1} {0} és {1} @msg {path}: {e} {path}: {e} @msg {status} ({e}) {status} ({e}) @msg {tool} isn't in a toolbar group of several tools az eszköz nincs többeszközös eszköztár-csoportban: {tool} +@msg Presentation Mode hides the toolbars: change the screen mode to show them a Bemutató mód elrejti az eszköztárakat: a megjelenítésükhöz váltson képernyőmódot +@msg Tab has hidden the toolbars: press Tab to show them a Tab elrejtette az eszköztárakat: a megjelenítésükhöz nyomja meg a Tab billentyűt @msg the compressed file unpacks to more than VectorCraft reads ({_1} MB of document, {_2} MB per image) a tömörített fájl kicsomagolva nagyobb lenne, mint amennyit a VectorCraft beolvas ({_1} MB dokumentum, képenként {_2} MB) @msg the document is too large to save compressed ({0}): save it with Use Compression off a dokumentum túl nagy a tömörített mentéshez ({0}): mentsd a Tömörítés használata beállítás kikapcsolásával @msg the file stopped being read (please report this bug) a fájl beolvasása megszakadt (kérjük, jelentsd ezt a hibát) @@ -6401,6 +6434,7 @@ variable-list-end {0}, {1} {0} és {1} Cove Homorú Depth Mélység Front Elölről + Side Oldalról Isometric Bottom Izometrikus alsó Isometric Left Izometrikus bal Isometric Right Izometrikus jobb @@ -6495,7 +6529,7 @@ variable-list-end {0}, {1} {0} és {1} @msg each of `{GRAPHICS}` must be an object a `{GRAPHICS}` minden elemének objektumnak kell lennie @msg `{GRAPHICS}` entries take symbol, face, x, y, scale and rotation, not `{k}` a `{GRAPHICS}` elemei symbol, face, x, y, scale és rotation értéket fogadnak, nem `{k}` értéket @msg each of `{GRAPHICS}` needs `symbol`, the name of a symbol a `{GRAPHICS}` minden eleméhez kell `symbol`, egy szimbólum neve -@msg `{GRAPHICS}` face must be front or back a `{GRAPHICS}` face értéke front vagy back lehet +@msg `{GRAPHICS}` face must be front, back or side a `{GRAPHICS}` face értéke front, back vagy side lehet @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} a `{GRAPHICS}` {key} értéke {lo} és {hi} közötti szám lehet @msg `{GRAPHICS}` must be an array a `{GRAPHICS}` értéke tömb kell legyen @msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types A grafikák a Sík, a Kihúzás, a Forgatás tengely körül és a Felfújás objektumtípusra kerülnek @@ -7730,6 +7764,14 @@ breakText Glyphs Glifák Remove Gaps Hézagok eltávolítása @msg that makes too many pieces (at most 100000): make the dashes longer ez túl sok darabot adna (legfeljebb 100000): hosszabbítsa meg a szaggatásokat @msg select paths, or segments, to divide jelöljön ki felosztandó útvonalakat vagy szakaszokat +# Path Precision Tools add-on: Smooth Bridge. + Smooth Bridge… Sima híd… + Smooth Bridge Sima híd + Keep Originals Eredetik megtartása +@msg select two circles to bridge jelöljön ki két kört az összekötéshez +@msg one circle is inside the other az egyik kör a másikon belül van +@msg the circles are too far apart for this radius: raise the radius a körök túl messze vannak egymástól ehhez a sugárhoz: növelje a sugarat +@msg the circles are too far apart for this radius a körök túl messze vannak egymástól ehhez a sugárhoz # Path Precision Tools add-on: Common Tangents. Common Tangents… Közös érintők… Common Tangents Közös érintők diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index bc3239c31b..1cf9cd9a10 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -1637,6 +1637,7 @@ digits Malayalam Malayalam Underline Garis bawah Vertical Scale % Skala vertikal % Axis Sumbu + Axis Angle Sudut sumbu ICF Top/Right ICF atas/kanan ICF Bottom/Left ICF bawah/kiri Show Font Height Options Tampilkan opsi tinggi font @@ -2192,6 +2193,7 @@ digits Malayalam Malayalam Line Properties: Properti garis: Line Length: Panjang garis: Line Angle: Sudut garis: + Constrain Pie Angle Kendalikan sudut pai Rectangle Properties: Properti persegi panjang: Shape Properties: Properti bentuk: Shape Properties Properti bentuk @@ -2233,6 +2235,7 @@ digits Malayalam Malayalam Scatter: Sebaran: Rotation: Rotasi: Rotation relative to: Rotasi relatif terhadap: + Hue Jitter: Variasi rona: Brush Scale Options Opsi skala kuas Scale Proportionately Skalakan proporsional Stretch to Fit Stroke Length Regangkan sesuai panjang stroke @@ -2271,6 +2274,7 @@ digits Malayalam Malayalam Size: Ukuran: Calligraphic Brush Options Opsi kuas kaligrafi Bristle Brush Options Opsi kuas bristle + Roundness Kebulatan Roundness: Kebulatan: Shape: Bentuk: Bristle Length: Panjang bristle: @@ -3256,6 +3260,8 @@ theme Appearance Tampilan Current Brush Kuas saat ini Current Symbol Simbol saat ini Delete Brush Hapus kuas + Delete Color Hapus warna + Restore Generated Table Pulihkan tabel yang dibuat Delete Symbol Hapus simbol Delete the selected symbol? Hapus simbol yang dipilih? Delete the selected symbols? Hapus simbol yang dipilih? @@ -3709,6 +3715,7 @@ theme Appearance Tampilan 90° & 45° Angles Sudut 90° & 45° 90° Angles Sudut 90° Additional Plug-ins Folder Folder plug-in tambahan + Plug-in Instruction Budget Anggaran instruksi plug-in Additional Fonts Folder Folder font tambahan Alignment Guides Panduan perataan Anchor Points, Handle, and Bounding Box Display Tampilan titik jangkar, pegangan, dan kotak pembatas @@ -3735,6 +3742,7 @@ theme Appearance Tampilan Data Recovery Pemulihan data Default Language Bahasa standar Disable Auto Add/Delete Nonaktifkan tambah/hapus otomatis + Interpolate Control Points When Moving Anchors Interpolasikan gagang arah saat memindahkan titik jangkar Display All Blacks Accurately Tampilkan semua warna hitam secara akurat Display All Blacks as Rich Black Tampilkan semua warna hitam sebagai rich black Display Bitmaps as Anti-aliased Images in Pixel Preview Tampilkan bitmap sebagai gambar anti-alias dalam pratinjau piksel @@ -3823,6 +3831,7 @@ theme Appearance Tampilan Printing / Exporting Pencetakan / Ekspor Real-time Drawing and Editing Penggambaran dan pengeditan waktu nyata Use Monitor Profile for Canvas Gunakan profil monitor untuk kanvas + Refresh Monitor Profile Segarkan profil monitor The canvas is drawn in sRGB. Kanvas digambar dalam sRGB. Canvas display profile: Profil layar kanvas: The system matches the window to the display's colors. Sistem menyesuaikan jendela dengan warna layar. @@ -4219,6 +4228,9 @@ font-technology Variable Variabel Search commands, tools, panels and effects… Cari perintah, alat, panel, dan efek… No commands match Tidak ada perintah yang cocok {pos} of {total}: {name} {pos} dari {total}: {name} + No menu item Tidak ada item menu + Toolbar Bilah alat + {toolbar}, in the {tool} group {toolbar}, dalam grup {tool} @plural {n} result|{n} results {n} hasil @plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} dari {n} hasil. Terus ketik untuk mempersempitnya. Recent Commands Perintah terbaru @@ -4255,6 +4267,7 @@ font-technology Variable Variabel The mouse wheel with Cmd/Ctrl held scrolls the canvas sideways. Roda mouse dengan Cmd/Ctrl ditahan menggulir kanvas ke samping. Dragging sideways on a numeric field's label changes the field's value. Menyeret ke samping pada label bidang angka mengubah nilai bidang itu. A two-finger rotate gesture on a trackpad rotates the canvas view. Gerakan putar dua jari pada trackpad memutar tampilan kanvas. + When you move anchor points, each curve with one moved end keeps its shape relative to its ends. Saat Anda memindahkan titik jangkar, setiap kurva dengan satu ujung yang dipindahkan mempertahankan bentuknya terhadap ujung-ujungnya. Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Menahan tombol pintasan alat memilih alat itu sampai Anda melepasnya, lalu alat sebelumnya dipilih lagi. Shows the bounding box while you move the selection or draw a shape. Menampilkan kotak pembatas saat Anda memindahkan seleksi atau menggambar bentuk. Create Trim Marks draws Japanese-style marks instead of Roman ones. Buat tanda potong menggambar tanda bergaya Jepang, bukan Romawi. @@ -4777,6 +4790,7 @@ imageTrace Outline Kontur @msg choose a folder to export to pilih folder tujuan ekspor @msg choose a location for the package pilih lokasi untuk paket @msg clipboard is empty papan klip kosong +@msg colorTable.deleted: at least one color has to stay in the color table colorTable.deleted: setidaknya satu warna harus tetap ada di tabel warna @msg colorTable.{what}: `{h}` is not a colour such as "#ff8800" colorTable.{what}: `{h}` bukan warna seperti "#ff8800" @msg colorTable.{what}: at most {MAX_TABLE} colours colorTable.{what}: maksimal {MAX_TABLE} warna @msg command `{0}` is not available right now: {1} perintah `{0}` tidak tersedia saat ini: {1} @@ -5676,6 +5690,7 @@ mark-style Japanese Jepang Cove Cove Depth Kedalaman Front Depan + Side Samping Isometric Bottom Isometrik bawah Isometric Left Isometrik kiri Isometric Right Isometrik kanan @@ -7006,6 +7021,14 @@ breakText Glyphs Glif Remove Gaps Hapus celah @msg that makes too many pieces (at most 100000): make the dashes longer itu menghasilkan terlalu banyak potongan (paling banyak 100000): perpanjang garisnya @msg select paths, or segments, to divide pilih jalur atau segmen yang akan dibagi +# Path Precision Tools add-on: Smooth Bridge. + Smooth Bridge… Jembatan Halus… + Smooth Bridge Jembatan Halus + Keep Originals Pertahankan Asli +@msg select two circles to bridge pilih dua lingkaran untuk dijembatani +@msg one circle is inside the other satu lingkaran berada di dalam lingkaran lainnya +@msg the circles are too far apart for this radius: raise the radius lingkaran terlalu berjauhan untuk radius ini: perbesar radius +@msg the circles are too far apart for this radius lingkaran terlalu berjauhan untuk radius ini # Path Precision Tools add-on: Common Tangents. Common Tangents… Garis Singgung Persekutuan… Common Tangents Garis Singgung Persekutuan diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index a5de66f381..1483c97f4a 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -141,6 +141,7 @@ Add to Swatches Aggiungi ai campioni Add Used Colors Aggiungi colori usati Additional Plug-ins Folder Cartella plug-in aggiuntivi + Plug-in Instruction Budget Budget di istruzioni dei plug-in Additional Fonts Folder Cartella font aggiuntivi Adjust Adjoining Width Points Regola punti di larghezza adiacenti Incoming In entrata @@ -818,6 +819,8 @@ font-technology Variable Variabili Delete Artboard Elimina tavola da disegno Delete Artboards Elimina tavole da disegno Delete Brush Elimina pennello + Delete Color Elimina colore + Restore Generated Table Ripristina tabella generata Delete Character Style Elimina stile carattere Delete Empty Artboards Elimina tavole da disegno vuote Delete Freeform Point Elimina punto libero @@ -886,6 +889,7 @@ font-technology Variable Variabili Direct Selection Tool Strumento Selezione diretta Direction Handles Maniglie di direzione Disable Auto Add/Delete Disattiva aggiunta/eliminazione automatica + Interpolate Control Points When Moving Anchors Interpola le maniglie di direzione durante lo spostamento dei punti di ancoraggio Disable Opacity Mask Disattiva maschera di opacità Discard Scarta Preserve Mantieni @@ -2299,6 +2303,7 @@ file-filter Templates Modelli Scatter: Dispersione: Rotation: Rotazione: Rotation relative to: Rotazione relativa a: + Hue Jitter: Variazione tonalità: Brush Scale Options Opzioni di scala del pennello Scale Proportionately Ridimensiona proporzionalmente Stretch to Fit Stroke Length Allunga per adattare alla lunghezza del tratto @@ -2335,6 +2340,7 @@ file-filter Templates Modelli Black becomes the stroke color and white stays white. Other colors become tints of the stroke color by their lightness. Il nero diventa il colore della traccia e il bianco resta bianco. Gli altri colori diventano tinte del colore della traccia, e più un colore è chiaro, più è chiara la sua tinta. Black and white stay as they are. Dark colors become shades of the stroke color and light colors become tints of it. Il nero resta nero e il bianco resta bianco. Gli altri colori diventano ombre del colore della traccia quando sono scuri e tinte di esso quando sono chiari. The key color becomes the stroke color. The other colors shift their hue by the same amount and keep their saturation and brightness. Il colore chiave diventa il colore della traccia. Gli altri colori ruotano sulla ruota dei colori quanto il colore chiave e mantengono la loro saturazione e luminosità. + Roundness Rotondità Roundness: Rotondità: Fixed Fisso Pressure Pressione @@ -2777,6 +2783,7 @@ diagnostics ui interfaccia Line Properties: Proprietà linea: Line Length: Lunghezza linea: Line Angle: Angolo linea: + Constrain Pie Angle Vincola angolo del settore Polygon Tool Strumento Poligono Portrait Verticale Power Saving (integrated) Risparmio energetico (integrata) @@ -2938,6 +2945,9 @@ digits Malayalam Malayalam Real World: Mondo reale: Real-time Drawing and Editing Disegno e modifica in tempo reale Use Monitor Profile for Canvas Usa il profilo del monitor per l'area di disegno + Refresh Monitor Profile Aggiorna profilo del monitor +@msg turn on Use Monitor Profile for Canvas first attiva prima «Usa il profilo del monitor per l'area di disegno» +@msg this build doesn't read display profiles questa versione non legge i profili dei display The canvas is drawn in sRGB. L'area di disegno è visualizzata in sRGB. Canvas display profile: Profilo del display per l'area di disegno: The system matches the window to the display's colors. Il sistema adatta la finestra ai colori del display. @@ -3200,6 +3210,7 @@ digits Malayalam Malayalam The mouse wheel with Cmd/Ctrl held scrolls the canvas sideways. La rotellina del mouse con Cmd/Ctrl premuto scorre l'area di lavoro in orizzontale. Dragging sideways on a numeric field's label changes the field's value. Trascinare in orizzontale sull'etichetta di un campo numerico ne cambia il valore. A two-finger rotate gesture on a trackpad rotates the canvas view. Un gesto di rotazione con due dita sul trackpad ruota la vista dell'area di lavoro. + When you move anchor points, each curve with one moved end keeps its shape relative to its ends. Quando sposti i punti di ancoraggio, ogni curva con un’estremità spostata mantiene la propria forma rispetto alle sue estremità. Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Tenere premuta la scorciatoia di uno strumento lo sceglie finché non la rilasci, poi viene scelto di nuovo lo strumento precedente. Shows the bounding box while you move the selection or draw a shape. Mostra il riquadro di delimitazione mentre sposti la selezione o disegni una forma. Create Trim Marks draws Japanese-style marks instead of Roman ones. Crea segni di taglio disegna segni in stile giapponese invece di quelli romani. @@ -3511,6 +3522,11 @@ digits Malayalam Malayalam Search commands, tools, panels and effects… Cerca comandi, strumenti, pannelli ed effetti… No commands match Nessun comando corrisponde {pos} of {total}: {name} {pos} di {total}: {name} + No menu item Nessuna voce di menu + Toolbar Barra degli strumenti + {toolbar}, in the {tool} group {toolbar}, nel gruppo {tool} + Tool Strumento + Command Comando @plural {n} result|{n} results {n} risultato|{n} risultati @plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} di {n} risultato. Continua a digitare per restringerli.|{shown} di {n} risultati. Continua a digitare per restringerli. Recent Commands Comandi recenti @@ -4608,6 +4624,7 @@ imageTrace Outline Contorno Bevel Smussato Offset Spostamento Axis Asse + Axis Angle Angolo dell'asse axis Horizontal Orizzontale axis Vertical Verticale axis Both Entrambi @@ -5099,6 +5116,7 @@ liquify-list-end {0}, {1} {0} e {1} @msg choose a folder to export to scegli una cartella in cui esportare @msg choose a location for the package scegli una posizione per il pacchetto @msg clipboard is empty gli appunti sono vuoti +@msg colorTable.deleted: at least one color has to stay in the color table colorTable.deleted: almeno un colore deve restare nella tabella colori @msg colorTable.{what}: `{h}` is not a colour such as "#ff8800" colorTable.{what}: `{h}` non è un colore come "#ff8800" @msg colorTable.{what}: at most {MAX_TABLE} colours colorTable.{what}: al massimo {MAX_TABLE} colori @msg command `{0}` is not available right now: {1} il comando `{0}` non è disponibile in questo momento: {1} @@ -5166,6 +5184,12 @@ liquify-list-end {0}, {1} {0} e {1} @msg no PNG encoder nessun codificatore PNG @msg no active document nessun documento attivo @msg no active perspective plane nessun piano prospettico attivo +@msg the perspective grid is hidden la griglia prospettica è nascosta +@msg Automatic Plane Positioning is off: turn on anchorPoint or gridlineIntersection (perspective.widget.options) Il posizionamento automatico del piano è disattivato: attiva anchorPoint o gridlineIntersection (perspective.widget.options) +@msg anchorPoint must be true or false anchorPoint deve essere true o false +@msg gridlineIntersection must be true or false gridlineIntersection deve essere true o false +@msg tolerance must be 0 or more tolerance deve essere 0 o maggiore +@msg give `at` or `clear`, not both indica `at` o `clear`, non entrambi @msg no anchor points selected nessun punto di ancoraggio selezionato @msg `points` must be two or three [x, y] pairs of numbers `points` deve essere composto da due o tre coppie di numeri [x, y] @msg direct-select two or three anchor points, or give `points` seleziona con Selezione diretta due o tre punti di ancoraggio oppure indica `points` @@ -5638,6 +5662,8 @@ variable-list-end {0}, {1} {0} e {1} @msg Reload the page to go on (changes not saved yet may be lost). Ricarica la pagina per continuare (le modifiche non ancora salvate potrebbero andare perse). @msg tool (a tool id) is required tool (un id di strumento) è obbligatorio @msg {tool} isn't in a toolbar group of several tools {tool} non fa parte di un gruppo di più strumenti nella barra degli strumenti +@msg Presentation Mode hides the toolbars: change the screen mode to show them la Modalità presentazione nasconde le barre degli strumenti: cambia la modalità schermo per mostrarle +@msg Tab has hidden the toolbars: press Tab to show them Tab ha nascosto le barre degli strumenti: premi Tab per mostrarle @msg onto must name a panel floating in another group onto deve indicare un pannello mobile in un altro gruppo @msg below and above must name a panel floating in another group below e above devono indicare un pannello mobile in un altro gruppo @msg give only one of onto, below and above indica solo uno tra onto, below e above @@ -5754,6 +5780,7 @@ variable-list-end {0}, {1} {0} e {1} @msg a linked JavaScript file is outside the read roots un file JavaScript collegato è fuori dalle cartelle radice di lettura @msg a linked image file is outside the read roots un file immagine collegato è fuori dalle cartelle radice di lettura @msg a linked file's export folder is outside the read roots la cartella di esportazione di un file collegato è fuori dalle cartelle radice di lettura +@msg a linked file's editing data can't be read to check it against the read roots impossibile leggere i dati di modifica di un file collegato per verificarli rispetto alle cartelle radice di lettura @msg automation path rejected: outside the write root {root}: {path} percorso di automazione rifiutato: fuori dalla cartella radice di scrittura {root}: {path} @msg automation path rejected: outside the write roots {roots}: {path} percorso di automazione rifiutato: fuori dalle cartelle radice di scrittura {roots}: {path} @msg automation path rejected: path is empty percorso di automazione rifiutato: il percorso è vuoto @@ -6038,6 +6065,7 @@ lighting Light Luce Cove Guscio Depth Profondità Front Fronte + Side Lato Isometric Bottom Isometrica sotto Isometric Left Isometrica sinistra Isometric Right Isometrica destra @@ -6132,7 +6160,7 @@ lighting Light Luce @msg each of `{GRAPHICS}` must be an object ogni voce di `{GRAPHICS}` deve essere un oggetto @msg `{GRAPHICS}` entries take symbol, face, x, y, scale and rotation, not `{k}` le voci di `{GRAPHICS}` accettano symbol, face, x, y, scale e rotation, non `{k}` @msg each of `{GRAPHICS}` needs `symbol`, the name of a symbol ogni voce di `{GRAPHICS}` richiede `symbol`, il nome di un simbolo -@msg `{GRAPHICS}` face must be front or back face di `{GRAPHICS}` deve essere front o back +@msg `{GRAPHICS}` face must be front, back or side face di `{GRAPHICS}` deve essere front, back o side @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} {key} di `{GRAPHICS}` deve essere un numero da {lo} a {hi} @msg `{GRAPHICS}` must be an array `{GRAPHICS}` deve essere un array @msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types Le grafiche si applicano ai tipi di oggetto Piano, Estrusione, Rivoluzione e Gonfia @@ -7378,6 +7406,14 @@ breakText Glyphs Glifi Remove Gaps Rimuovi le distanze @msg that makes too many pieces (at most 100000): make the dashes longer così si ottengono troppi pezzi (al massimo 100000): allunga i trattini @msg select paths, or segments, to divide seleziona tracciati o segmenti da dividere +# Path Precision Tools add-on: Smooth Bridge. + Smooth Bridge… Ponte morbido… + Smooth Bridge Ponte morbido + Keep Originals Mantieni originali +@msg select two circles to bridge seleziona due cerchi da unire +@msg one circle is inside the other un cerchio è dentro l’altro +@msg the circles are too far apart for this radius: raise the radius i cerchi sono troppo distanti per questo raggio: aumenta il raggio +@msg the circles are too far apart for this radius i cerchi sono troppo distanti per questo raggio # Path Precision Tools add-on: Common Tangents. Common Tangents… Tangenti comuni… Common Tangents Tangenti comuni @@ -7747,6 +7783,14 @@ breakText Glyphs Glifi @msg `answers` has more than {MAX_ANSWERS} answers `answers` ha più di {MAX_ANSWERS} risposte @msg `answers` is larger than 1 MiB `answers` supera 1 MiB @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` è solo per un'esecuzione senza nessuno a cui chiedere: nell'app, la persona risponde a ogni finestra di dialogo +@msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` deve essere un numero intero da 1 a {_1} +@msg `args{place}` is nested more than 64 levels deep `args{place}` è annidato per più di 64 livelli +@msg `args` must be an object `args` deve essere un oggetto +@msg `args` is larger than 1 MiB `args` supera 1 MiB +@msg `path` is empty `path` è vuoto +@msg `installed` takes a `path`, not a `source` `installed` accetta un `path`, non un `source` +@msg `path` must name a .js or .jsx file `path` deve indicare un file .js o .jsx +@msg give exactly one of `path` and `source` indica esattamente uno tra `path` e `source` @msg `answers` must be a list of answers `answers` deve essere un elenco di risposte @msg `artboard` must be the index of an artboard of the document `artboard` deve essere l'indice di una tavola da disegno del documento @msg `artboardsAt` must be [x, y] `artboardsAt` deve essere [x, y] diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index a75788156e..d4abe69ee5 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -1093,6 +1093,7 @@ digits Malayalam マラヤーラム数字 Add to Selection 選択範囲に追加 Add to Swatches スウォッチに追加 Additional Plug-ins Folder 追加プラグインフォルダー + Plug-in Instruction Budget プラグインの命令予算 Additional Fonts Folder 追加フォントフォルダー Adjust Adjoining Width Points 隣接する幅ポイントを調整 Incoming 入り側 @@ -1519,6 +1520,8 @@ antiAlias Sharp シャープ Delete Artboard アートボードを削除 Delete Artboards アートボードを削除 Delete Brush ブラシを削除 + Delete Color カラーを削除 + Restore Generated Table 生成されたテーブルを復元 Delete Character Style 文字スタイルを削除 Delete Empty Artboards 空のアートボードを削除 Delete Freeform Point フリーフォームポイントを削除 @@ -1581,6 +1584,7 @@ antiAlias Sharp シャープ Dimensions 寸法 Direct Selection Tool ダイレクト選択ツール Disable Auto Add/Delete 自動追加/削除機能を使用しない + Interpolate Control Points When Moving Anchors アンカーポイントの移動時に方向線ハンドルを補間 Disable Opacity Mask 不透明マスクを無効にする Discard 破棄 Preserve 保持 @@ -2498,6 +2502,7 @@ antiAlias Sharp シャープ Scatter: 散布: Rotation: 回転: Rotation relative to: 回転の基準: + Hue Jitter: 色相のばらつき: Brush Scale Options ブラシ伸縮オプション Scale Proportionately 縦横比を保持して拡大・縮小 Stretch to Fit Stroke Length ストロークの長さに合わせて伸縮 @@ -2534,6 +2539,7 @@ antiAlias Sharp シャープ Black becomes the stroke color and white stays white. Other colors become tints of the stroke color by their lightness. 黒は線のカラーになり、白は白のままです。その他のカラーは線のカラーの淡彩になり、明るいカラーほど明るい淡彩になります。 Black and white stay as they are. Dark colors become shades of the stroke color and light colors become tints of it. 黒は黒のまま、白は白のままです。その他のカラーは、暗い場合は線のカラーの陰影に、明るい場合は淡彩になります。 The key color becomes the stroke color. The other colors shift their hue by the same amount and keep their saturation and brightness. キーカラーが線のカラーになります。その他のカラーはキーカラーと同じだけカラーホイール上を移動し、彩度と明るさは保たれます。 + Roundness 真円率 Roundness: 真円率: Fixed 固定 Pressure 筆圧 @@ -2870,6 +2876,7 @@ diagnostics ui UI Line Properties: 線のプロパティ: Line Length: 線の長さ: Line Angle: 線の角度: + Constrain Pie Angle 扇形の角度を固定 Polygon Tool 多角形ツール Portrait 縦置き Portuguese ポルトガル語 @@ -2971,6 +2978,9 @@ mark-style Japanese 日本式 Real World: 実寸: Real-time Drawing and Editing リアルタイム描画および編集 Use Monitor Profile for Canvas キャンバスにモニタープロファイルを使用 + Refresh Monitor Profile モニタープロファイルを更新 +@msg turn on Use Monitor Profile for Canvas first 先に「キャンバスにモニタープロファイルを使用」をオンにしてください +@msg this build doesn't read display profiles このビルドはディスプレイプロファイルを読み込みません The canvas is drawn in sRGB. キャンバスは sRGB で描画されます。 Canvas display profile: キャンバスのディスプレイプロファイル: The system matches the window to the display's colors. システムがウィンドウをディスプレイのカラーに合わせます。 @@ -3184,6 +3194,7 @@ mark-style Japanese 日本式 The mouse wheel with Cmd/Ctrl held scrolls the canvas sideways. Cmd/Ctrl キーを押しながらマウスホイールを回すとカンバスを横にスクロールします。 Dragging sideways on a numeric field's label changes the field's value. 数値フィールドのラベルを横にドラッグすると、フィールドの値が変わります。 A two-finger rotate gesture on a trackpad rotates the canvas view. トラックパッドで 2 本指の回転ジェスチャーをすると、カンバスの表示が回転します。 + When you move anchor points, each curve with one moved end keeps its shape relative to its ends. アンカーポイントを移動すると、一方の端が移動した各曲線は、両端に対する形状を保ちます。 Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. ツールのショートカットキーを押している間はそのツールを選び、離すと前のツールに戻ります。 Shows the bounding box while you move the selection or draw a shape. 選択範囲の移動中や図形の描画中にバウンディングボックスを表示します。 Create Trim Marks draws Japanese-style marks instead of Roman ones. トリムマークを作成で、西洋式ではなく日本式のトンボを描きます。 @@ -3396,6 +3407,9 @@ mark-style Japanese 日本式 Search commands, tools, panels and effects… コマンド、ツール、パネル、効果を検索… No commands match 一致するコマンドはありません {pos} of {total}: {name} {total} 件中 {pos} 件目: {name} + No menu item メニュー項目なし + Toolbar ツールバー + {toolbar}, in the {tool} group {toolbar}、{tool} のグループ内 @plural {n} result|{n} results {n} 件 @plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {n} 件中 {shown} 件。続けて入力すると絞り込めます。 Recent Commands 最近使ったコマンド @@ -4549,6 +4563,7 @@ imageTrace Outline アウトライン Bevel ベベル Offset オフセット Axis 軸 + Axis Angle 軸の角度 axis Horizontal 水平方向 axis Vertical 垂直方向 axis Both 両方 @@ -5064,6 +5079,7 @@ variable-list-end {0}, {1} {0}、{1} @msg Create Outlines: select text objects アウトラインを作成: テキストオブジェクトを選択してください @msg paste unavailable 貼り付けを使用できません @msg Save for Web: the image is empty Web 用に保存: 画像が空です +@msg colorTable.deleted: at least one color has to stay in the color table colorTable.deleted: カラーテーブルには少なくとも 1 つのカラーを残す必要があります @msg colorTable.{what}: `{h}` is not a colour such as "#ff8800" colorTable.{what}: `{h}` は「#ff8800」のような形式のカラーではありません @msg colorTable.{what}: at most {MAX_TABLE} colours colorTable.{what}: 指定できるカラーは {MAX_TABLE} 色までです @msg no artboard {i} (0-based; the document has {_1}) アートボード {i} はありません (番号は 0 始まり、このドキュメントには {_1} 個あります) @@ -5311,6 +5327,12 @@ variable-list-end {0}, {1} {0}、{1} @msg no preset editor プリセットの編集ダイアログが開いていません @msg no perspective grid preset named `{name}` `{name}` という名前の遠近グリッドプリセットが見つかりません @msg no active perspective plane アクティブな遠近面がありません +@msg the perspective grid is hidden 遠近グリッドが非表示になっています +@msg Automatic Plane Positioning is off: turn on anchorPoint or gridlineIntersection (perspective.widget.options) 遠近面の自動配置がオフになっています: anchorPoint または gridlineIntersection をオンにしてください (perspective.widget.options) +@msg anchorPoint must be true or false anchorPoint には true または false を指定してください +@msg gridlineIntersection must be true or false gridlineIntersection には true または false を指定してください +@msg tolerance must be 0 or more tolerance には 0 以上の値を指定してください +@msg give `at` or `clear`, not both `at` または `clear` のどちらか一方を指定してください @msg plane must be left, right or ground plane には left、right、ground のいずれかを指定してください @msg missing `id` (see plugin.list) `id` が指定されていません (plugin.list を参照) @msg no plug-in {id} is installed プラグイン {id} はインストールされていません @@ -5628,6 +5650,14 @@ liquify-list-end {0}, {1} {0}、{1} @msg the main script engine is new for each run and is never kept, so it cannot be dropped メインのスクリプトエンジンは実行ごとに新しく作られ、保持されないため、破棄できません @msg there is no script engine named {name} {name} という名前のスクリプトエンジンはありません @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` は尋ねる相手がいない実行専用です。アプリでは、各ダイアログに本人が回答します +@msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` には 1 から {_1} までの整数を指定してください +@msg `args{place}` is nested more than 64 levels deep `args{place}` の入れ子が 64 階層を超えています +@msg `args` must be an object `args` はオブジェクトである必要があります +@msg `args` is larger than 1 MiB `args` が 1 MiB を超えています +@msg `path` is empty `path` が空です +@msg `installed` takes a `path`, not a `source` `installed` には `source` ではなく `path` を指定してください +@msg `path` must name a .js or .jsx file `path` には .js または .jsx ファイルを指定してください +@msg give exactly one of `path` and `source` `path` と `source` のうち 1 つだけを指定してください @msg Running a script スクリプトを実行中 @msg Copied the script report スクリプトのレポートをコピーしました @msg Script file access denied: {path} スクリプトのファイルアクセスが拒否されました: {path} @@ -5745,6 +5775,8 @@ liquify-list-end {0}, {1} {0}、{1} @msg the {tool} tool has no options {tool} ツールにはオプションがありません @msg unknown tool `{tool}` `{tool}` は不明なツールです @msg {tool} isn't in a toolbar group of several tools {tool} は複数のツールからなるツールグループに含まれていません +@msg Presentation Mode hides the toolbars: change the screen mode to show them プレゼンテーションモードではツールバーが表示されません: 表示するにはスクリーンモードを変更してください +@msg Tab has hidden the toolbars: press Tab to show them Tab でツールバーが非表示になっています: 表示するには Tab キーを押してください @msg no such document 指定されたドキュメントが見つかりません @msg {_1}: not saved, so not closed {_1}: 保存されていないため、閉じませんでした @msg `{name}` is a built-in workspace; choose another name `{name}` は組み込みのワークスペースなので、別の名前を指定してください @@ -5796,6 +5828,7 @@ liquify-list-end {0}, {1} {0}、{1} @msg a linked JavaScript file is outside the read roots リンクされた JavaScript ファイルが読み込みルートの外にあります @msg a linked image file is outside the read roots リンクされた画像ファイルが読み込みルートの外にあります @msg a linked file's export folder is outside the read roots リンクされたファイルの書き出しフォルダーが読み込みルートの外にあります +@msg a linked file's editing data can't be read to check it against the read roots リンクされたファイルの編集データを読み込めないため、読み込みルートと照合できません @msg automation path rejected: outside the write root {root}: {path} 自動化のパスを拒否しました: 書き込みルート {root} の外です: {path} @msg automation path rejected: outside the write roots {roots}: {path} 自動化のパスを拒否しました: 書き込みルート {roots} のいずれの中でもありません: {path} @msg automation path rejected: path is empty 自動化のパスを拒否しました: パスが空です @@ -6081,6 +6114,7 @@ lighting Light ライト Cove 凹面 Depth 奥行き Front 正面 + Side 側面 Isometric Bottom 等角図(底面) Isometric Left 等角図(左) Isometric Right 等角図(右) @@ -6175,7 +6209,7 @@ lighting Light ライト @msg each of `{GRAPHICS}` must be an object `{GRAPHICS}` の各項目はオブジェクトにしてください @msg `{GRAPHICS}` entries take symbol, face, x, y, scale and rotation, not `{k}` `{GRAPHICS}` の項目に指定できるのは symbol、face、x、y、scale、rotation で、`{k}` は指定できません @msg each of `{GRAPHICS}` needs `symbol`, the name of a symbol `{GRAPHICS}` の各項目にはシンボルの名前 `symbol` が必要です -@msg `{GRAPHICS}` face must be front or back `{GRAPHICS}` の face には front または back を指定してください +@msg `{GRAPHICS}` face must be front, back or side `{GRAPHICS}` の face には front、back、side のいずれかを指定してください @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} `{GRAPHICS}` の {key} は {lo} から {hi} までの数値にしてください @msg `{GRAPHICS}` must be an array `{GRAPHICS}` は配列にしてください @msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types グラフィックはオブジェクトの種類が平面、押し出し、回転体、膨張のときにマッピングされます @@ -9262,6 +9296,14 @@ breakText Glyphs 字形 Remove Gaps 間隔を削除 @msg that makes too many pieces (at most 100000): make the dashes longer 分割数が多すぎます(最大 100000):ダッシュを長くしてください @msg select paths, or segments, to divide 分割するパスまたはセグメントを選択してください +# Path Precision Tools add-on: Smooth Bridge. + Smooth Bridge… スムーズブリッジ… + Smooth Bridge スムーズブリッジ + Keep Originals オリジナルを保持 +@msg select two circles to bridge ブリッジでつなぐ円を 2 つ選択してください +@msg one circle is inside the other 一方の円がもう一方の円の内側にあります +@msg the circles are too far apart for this radius: raise the radius この半径では円が離れすぎています:半径を大きくしてください +@msg the circles are too far apart for this radius この半径では円が離れすぎています # Path Precision Tools add-on: Common Tangents. Common Tangents… 共通接線… Common Tangents 共通接線 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 77c4ece361..d03d46435f 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -2066,6 +2066,7 @@ @msg {var_key} must be at most {most} {var_key} უნდა იყოს მაქსიმუმ {most} @msg a linked image file is outside the read roots დაკავშირებული გამოსახულების ფაილი წაკითხვის ძირეული საქაღალდეების გარეთაა @msg a linked file's export folder is outside the read roots დაკავშირებული ფაილის ექსპორტის საქაღალდე წაკითხვის ძირეული საქაღალდეების გარეთაა +@msg a linked file's editing data can't be read to check it against the read roots დაკავშირებული ფაილის რედაქტირების მონაცემების წაკითხვა ვერ ხერხდება წაკითხვის ძირეულ საქაღალდეებთან შესამოწმებლად Neon & Glow ნეონი და ნათება Show Hidden Panels at Edge დამალული პანელების ჩვენება კიდესთან @msg `anchor` must be a [subpath, anchor] pair `anchor` უნდა იყოს წყვილი [subpath, anchor] @@ -3815,6 +3816,7 @@ digits Malayalam მალაიალამური Underline ხაზგასმული Vertical Scale % ვერტიკალური მასშტაბი % Axis ღერძი + Axis Angle ღერძის კუთხე ICF Top/Right ICF ზედა/მარჯვენა ICF Bottom/Left ICF ქვედა/მარცხენა Show Font Height Options შრიფტის სიმაღლის პარამეტრების ჩვენება @@ -4360,6 +4362,7 @@ digits Malayalam მალაიალამური Line Properties: ხაზის თვისებები: Line Length: ხაზის სიგრძე: Line Angle: ხაზის კუთხე: + Constrain Pie Angle სექტორის კუთხის შენარჩუნება Rectangle Properties: მართკუთხედის თვისებები: Shape Properties: ფიგურის თვისებები: Shape Properties ფიგურის თვისებები @@ -4400,6 +4403,7 @@ digits Malayalam მალაიალამური Scatter: გაფანტვა: Rotation: შემობრუნება: Rotation relative to: შემობრუნების ათვლა: + Hue Jitter: ელფერის ვარიაცია: Brush Scale Options ფუნჯის მასშტაბირების პარამეტრები Scale Proportionately პროპორციული მასშტაბირება Stretch to Fit Stroke Length კონტურის სიგრძეზე გაწელვა @@ -4438,6 +4442,7 @@ digits Malayalam მალაიალამური Size: ზომა: Calligraphic Brush Options კალიგრაფიული ფუნჯის პარამეტრები Bristle Brush Options ჯაგრის ფუნჯის პარამეტრები + Roundness სიმრგვალე Roundness: სიმრგვალე: Shape: ფორმა: Bristle Length: ჯაგრის სიგრძე: @@ -5349,6 +5354,8 @@ theme Appearance იერსახე Current Brush მიმდინარე ფუნჯი Current Symbol მიმდინარე სიმბოლო Delete Brush ფუნჯის წაშლა + Delete Color ფერის წაშლა + Restore Generated Table გენერირებული ცხრილის აღდგენა Delete Symbol სიმბოლოს წაშლა Delete the selected symbol? წაიშალოს მონიშნული სიმბოლო? Delete the selected symbols? წაიშალოს მონიშნული სიმბოლოები? @@ -5803,6 +5810,7 @@ theme Appearance იერსახე 90° & 45° Angles 90° და 45° კუთხეები 90° Angles 90° კუთხეები Additional Plug-ins Folder დამატებითი პლაგინები + Plug-in Instruction Budget პლაგინების ინსტრუქციების ბიუჯეტი Additional Fonts Folder შრიფტების დამატებითი საქაღალდე Alignment Guides გასწორების დამხმარე ხაზები Anchor Points, Handle, and Bounding Box Display საყრდენი წერტილების, სახელურებისა და შემომსაზღვრელი ჩარჩოს ჩვენება @@ -5829,6 +5837,7 @@ theme Appearance იერსახე Data Recovery მონაცემების აღდგენა Default Language ნაგულისხმევი ენა Disable Auto Add/Delete ავტომატური დამატება/წაშლის გამორთვა + Interpolate Control Points When Moving Anchors სახელურების ინტერპოლაცია საყრდენი წერტილების გადაადგილებისას Display All Blacks Accurately ყველა შავის ზუსტად ჩვენება Display All Blacks as Rich Black ყველა შავის მდიდარ შავად ჩვენება Display Bitmaps as Anti-aliased Images in Pixel Preview პიქსელურ ნახვაში ბიტმაპების ანტიალიასინგიან გამოსახულებებად ჩვენება @@ -5917,6 +5926,9 @@ theme Appearance იერსახე Printing / Exporting ბეჭდვა / ექსპორტირება Real-time Drawing and Editing რეალურ დროში ხატვა და რედაქტირება Use Monitor Profile for Canvas მონიტორის პროფილის გამოყენება ტილოსთვის + Refresh Monitor Profile მონიტორის პროფილის განახლება +@msg turn on Use Monitor Profile for Canvas first ჯერ ჩართეთ „მონიტორის პროფილის გამოყენება ტილოსთვის“ +@msg this build doesn't read display profiles ეს ვერსია ეკრანის პროფილებს არ კითხულობს The canvas is drawn in sRGB. ტილო sRGB-ში იხატება. Canvas display profile: ტილოს ეკრანის პროფილი: The system matches the window to the display's colors. სისტემა ფანჯარას ეკრანის ფერებს უსადაგებს. @@ -6287,6 +6299,9 @@ font-technology Variable ცვლადი Search commands, tools, panels and effects… ბრძანებების, ხელსაწყოების, პანელებისა და ეფექტების ძიება… No commands match შესაბამისი ბრძანება არ არის {pos} of {total}: {name} {pos} / {total}: {name} + No menu item მენიუს ელემენტი არ არის + Toolbar ხელსაწყოთა ზოლი + {toolbar}, in the {tool} group {toolbar}, ჯგუფში {tool} @plural {n} result|{n} results {n} შედეგი @plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {n} შედეგიდან {shown}. გააგრძელეთ აკრეფა მათ შესამცირებლად. Recent Commands ბოლოდროინდელი ბრძანებები @@ -6324,6 +6339,7 @@ font-technology Variable ცვლადი The mouse wheel with Cmd/Ctrl held scrolls the canvas sideways. დაჭერილი Cmd/Ctrl-ით მაუსის ბორბალი ტილოს გვერდულად გადაახვევს. Dragging sideways on a numeric field's label changes the field's value. რიცხვითი ველის წარწერაზე გვერდულად გადათრევა ველის მნიშვნელობას ცვლის. A two-finger rotate gesture on a trackpad rotates the canvas view. ტრეკპადზე ორი თითით მობრუნების ჟესტი ტილოს ხედს აბრუნებს. + When you move anchor points, each curve with one moved end keeps its shape relative to its ends. როცა ღუზის წერტილებს გადაადგილებთ, ყოველი მრუდი, რომლის ერთი ბოლოც გადაადგილდა, ინარჩუნებს ფორმას თავის ბოლოებთან მიმართებით. Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. ხელსაწყოს მალსახმობი კლავიშის დაჭერით ხელსაწყო არჩეულია მის აშვებამდე, შემდეგ კი ისევ წინა ხელსაწყო აირჩევა. Shows the bounding box while you move the selection or draw a shape. აჩვენებს შემომსაზღვრელ ჩარჩოს, სანამ მონიშნულს გადაადგილებთ ან ფიგურას ხატავთ. Create Trim Marks draws Japanese-style marks instead of Roman ones. ჭრის ნიშნების შექმნა რომაულის ნაცვლად იაპონური სტილის ნიშნებს ხატავს. @@ -6841,6 +6857,7 @@ font-technology Variable ცვლადი @msg choose a folder to export to აირჩიეთ ექსპორტის საქაღალდე @msg choose a location for the package აირჩიეთ შეფუთვის მდებარეობა @msg clipboard is empty გაცვლის ბუფერი ცარიელია +@msg colorTable.deleted: at least one color has to stay in the color table colorTable.deleted: ფერების ცხრილში ერთი ფერი მაინც უნდა დარჩეს @msg colorTable.{what}: `{h}` is not a colour such as "#ff8800" colorTable.{what}: `{h}` ფერი არ არის, მაგალითად "#ff8800" @msg colorTable.{what}: at most {MAX_TABLE} colours colorTable.{what}: არაუმეტეს {MAX_TABLE} ფერი @msg command `{0}` is not available right now: {1} ბრძანება `{0}` ახლა ხელმისაწვდომი არ არის: {1} @@ -7334,6 +7351,8 @@ font-technology Variable ცვლადი @msg Reload the page to go on (changes not saved yet may be lost). გასაგრძელებლად გადატვირთეთ გვერდი (ჯერ შეუნახავი ცვლილებები შეიძლება დაიკარგოს). @msg tool (a tool id) is required tool (ხელსაწყოს id) აუცილებელია @msg {tool} isn't in a toolbar group of several tools {tool} რამდენიმე ხელსაწყოს მქონე ხელსაწყოთა ჯგუფში არ არის +@msg Presentation Mode hides the toolbars: change the screen mode to show them პრეზენტაციის რეჟიმი მალავს ხელსაწყოთა ზოლებს: მათ საჩვენებლად შეცვალეთ ეკრანის რეჟიმი +@msg Tab has hidden the toolbars: press Tab to show them Tab-მა დამალა ხელსაწყოთა ზოლები: მათ საჩვენებლად დააჭირეთ Tab-ს @msg onto must name a panel floating in another group onto უნდა ასახელებდეს სხვა ჯგუფში მცურავ პანელს @msg below and above must name a panel floating in another group below და above უნდა ასახელებდეს სხვა ჯგუფში მცურავ პანელს @msg give only one of onto, below and above მიუთითეთ მხოლოდ ერთი: onto, below ან above @@ -7798,6 +7817,7 @@ font-technology Variable ცვლადი Cove ღარი Depth სიღრმე Front წინიდან + Side გვერდიდან Isometric Bottom იზომეტრია ქვემოდან Isometric Left იზომეტრია მარცხნიდან Isometric Right იზომეტრია მარჯვნიდან @@ -7877,7 +7897,7 @@ font-technology Variable ცვლადი @msg each of `{GRAPHICS}` must be an object `{GRAPHICS}`-ის თითოეული ჩანაწერი უნდა იყოს ობიექტი @msg `{GRAPHICS}` entries take symbol, face, x, y, scale and rotation, not `{k}` `{GRAPHICS}`-ის ჩანაწერები იღებს symbol, face, x, y, scale და rotation მნიშვნელობებს და არა `{k}`-ს @msg each of `{GRAPHICS}` needs `symbol`, the name of a symbol `{GRAPHICS}`-ის თითოეულ ჩანაწერს სჭირდება `symbol`, სიმბოლოს სახელი -@msg `{GRAPHICS}` face must be front or back `{GRAPHICS}`-ის face უნდა იყოს front ან back +@msg `{GRAPHICS}` face must be front, back or side `{GRAPHICS}`-ის face უნდა იყოს front, back ან side @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} `{GRAPHICS}`-ის {key} უნდა იყოს რიცხვი {lo}-დან {hi}-მდე @msg `{GRAPHICS}` must be an array `{GRAPHICS}` უნდა იყოს მასივი @msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types გრაფიკა თავსდება ობიექტის ტიპებზე „სიბრტყე“, „ამოწევა“, „ბრუნვა“ და „გაბერვა“ @@ -9957,6 +9977,14 @@ breakText Glyphs გლიფები Remove Gaps ღრეჩოების მოცილება @msg that makes too many pieces (at most 100000): make the dashes longer ეს ძალიან ბევრ ნაწილს იძლევა (მაქსიმუმ 100000): გაზარდეთ ტირეების სიგრძე @msg select paths, or segments, to divide აირჩიეთ დასაყოფი ტრაექტორიები ან სეგმენტები +# Path Precision Tools add-on: Smooth Bridge. + Smooth Bridge… გლუვი ხიდი… + Smooth Bridge გლუვი ხიდი + Keep Originals ორიგინალების შენარჩუნება +@msg select two circles to bridge აირჩიეთ ორი წრე დასაკავშირებლად +@msg one circle is inside the other ერთი წრე მეორის შიგნითაა +@msg the circles are too far apart for this radius: raise the radius ამ რადიუსისთვის წრეები ერთმანეთისგან ძალიან შორსაა: გაზარდეთ რადიუსი +@msg the circles are too far apart for this radius ამ რადიუსისთვის წრეები ერთმანეთისგან ძალიან შორსაა # Path Precision Tools add-on: Common Tangents. Common Tangents… საერთო მხებები… Common Tangents საერთო მხებები diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 31891aba17..363de4c969 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -1083,6 +1083,7 @@ digits Malayalam 말라얄람어 Add to Selection 선택 영역에 추가 Add to Swatches 견본에 추가 Additional Plug-ins Folder 추가 플러그인 폴더 + Plug-in Instruction Budget 플러그인 명령어 예산 Additional Fonts Folder 추가 글꼴 폴더 Adjust Adjoining Width Points 인접한 너비 점 조정 Incoming 들어오는 쪽 @@ -1509,6 +1510,8 @@ antiAlias Sharp 날카롭게 Delete Artboard 아트보드 삭제 Delete Artboards 아트보드 삭제 Delete Brush 브러시 삭제 + Delete Color 색상 삭제 + Restore Generated Table 생성된 표 복원 Delete Character Style 문자 스타일 삭제 Delete Empty Artboards 빈 아트보드 삭제 Delete Freeform Point 자유 형태 포인트 삭제 @@ -1571,6 +1574,7 @@ antiAlias Sharp 날카롭게 Dimensions 치수 Direct Selection Tool 직접 선택 도구 Disable Auto Add/Delete 자동 추가/삭제 사용 안 함 + Interpolate Control Points When Moving Anchors 앵커 포인트 이동 시 방향 핸들 보간 Disable Opacity Mask 불투명 마스크 사용 안 함 Discard 삭제 Preserve 보존 @@ -2488,6 +2492,7 @@ antiAlias Sharp 날카롭게 Scatter: 흩뿌림: Rotation: 회전: Rotation relative to: 회전 기준: + Hue Jitter: 색조 변화: Brush Scale Options 브러시 크기 조절 옵션 Scale Proportionately 비율에 맞게 크기 조절 Stretch to Fit Stroke Length 선 길이에 맞게 늘이기 @@ -2524,6 +2529,7 @@ antiAlias Sharp 날카롭게 Black becomes the stroke color and white stays white. Other colors become tints of the stroke color by their lightness. 검정은 선 색상이 되고 흰색은 흰색으로 남습니다. 다른 색상은 선 색상의 틴트가 되며, 색상이 밝을수록 틴트도 밝아집니다. Black and white stay as they are. Dark colors become shades of the stroke color and light colors become tints of it. 검정은 검정으로 남고 흰색은 흰색으로 남습니다. 다른 색상은 어두우면 선 색상의 셰이드가 되고 밝으면 틴트가 됩니다. The key color becomes the stroke color. The other colors shift their hue by the same amount and keep their saturation and brightness. 키 색상은 선 색상이 됩니다. 다른 색상은 키 색상과 같은 만큼 색상환에서 이동하며 채도와 밝기를 유지합니다. + Roundness 원형률 Roundness: 원형률: Fixed 고정 Pressure 필압 @@ -2860,6 +2866,7 @@ diagnostics ui UI Line Properties: 선 속성: Line Length: 선 길이: Line Angle: 선 각도: + Constrain Pie Angle 파이 각도 고정 Polygon Tool 다각형 도구 Portrait 세로 Portuguese Português @@ -2961,6 +2968,9 @@ mark-style Japanese 일본식 Real World: 실제 크기: Real-time Drawing and Editing 실시간 그리기 및 편집 Use Monitor Profile for Canvas 캔버스에 모니터 프로필 사용 + Refresh Monitor Profile 모니터 프로필 새로 고침 +@msg turn on Use Monitor Profile for Canvas first 먼저 "캔버스에 모니터 프로필 사용"을 켜세요 +@msg this build doesn't read display profiles 이 빌드는 디스플레이 프로필을 읽지 않습니다 The canvas is drawn in sRGB. 캔버스는 sRGB로 그려집니다. Canvas display profile: 캔버스 디스플레이 프로필: The system matches the window to the display's colors. 시스템이 창을 디스플레이 색상에 맞춥니다. @@ -3173,6 +3183,7 @@ mark-style Japanese 일본식 The mouse wheel with Cmd/Ctrl held scrolls the canvas sideways. Cmd/Ctrl 키를 누른 채 마우스 휠을 돌리면 캔버스가 가로로 스크롤됩니다. Dragging sideways on a numeric field's label changes the field's value. 숫자 필드의 레이블을 옆으로 드래그하면 필드 값이 바뀝니다. A two-finger rotate gesture on a trackpad rotates the canvas view. 트랙패드에서 두 손가락으로 회전하는 동작을 하면 캔버스 보기가 회전합니다. + When you move anchor points, each curve with one moved end keeps its shape relative to its ends. 고정점을 이동하면 한쪽 끝이 이동한 각 곡선은 양 끝을 기준으로 모양을 유지합니다. Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. 도구의 바로 가기 키를 누르고 있는 동안 그 도구가 선택되고, 키를 놓으면 이전 도구가 다시 선택됩니다. Shows the bounding box while you move the selection or draw a shape. 선택 영역을 이동하거나 모양을 그리는 동안 테두리 상자를 표시합니다. Create Trim Marks draws Japanese-style marks instead of Roman ones. 트림 마크 만들기에서 서양식 대신 일본식 표시를 그립니다. @@ -3385,6 +3396,11 @@ mark-style Japanese 일본식 Search commands, tools, panels and effects… 명령, 도구, 패널 및 효과 검색… No commands match 일치하는 명령이 없습니다 {pos} of {total}: {name} {total}개 중 {pos}번째: {name} + No menu item 메뉴 항목 없음 + Toolbar 도구 모음 + {toolbar}, in the {tool} group {toolbar}, {tool} 그룹 + Tool 도구 + Command 명령 @plural {n} result|{n} results 결과 {n}개 @plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. 결과 {n}개 중 {shown}개. 계속 입력하여 범위를 좁히세요. Recent Commands 최근 명령 @@ -4533,6 +4549,7 @@ imageTrace Outline 윤곽선 Bevel 베벨 Offset 오프셋 Axis 축 + Axis Angle 축 각도 axis Horizontal 가로 axis Vertical 세로 axis Both 양쪽 @@ -4991,6 +5008,7 @@ variable-list-end {0}, {1} {0} 및 {1} @msg Create Outlines: select text objects 윤곽선 만들기: 텍스트 개체를 선택하세요 @msg paste unavailable 붙여넣을 수 없습니다 @msg Save for Web: the image is empty 웹용으로 저장: 이미지가 비어 있습니다 +@msg colorTable.deleted: at least one color has to stay in the color table colorTable.deleted: 색상 표에 색상이 하나 이상 남아 있어야 합니다 @msg colorTable.{what}: `{h}` is not a colour such as "#ff8800" colorTable.{what}: `{h}`은(는) "#ff8800" 같은 색상이 아닙니다 @msg colorTable.{what}: at most {MAX_TABLE} colours colorTable.{what}: 색상은 최대 {MAX_TABLE}개입니다 @msg no artboard {i} (0-based; the document has {_1}) 아트보드 {i}이(가) 없습니다(0부터 시작, 문서의 아트보드 수: {_1}) @@ -5238,6 +5256,12 @@ variable-list-end {0}, {1} {0} 및 {1} @msg no preset editor 프리셋 편집기가 없습니다 @msg no perspective grid preset named `{name}` `{name}`이라는 원근 격자 프리셋이 없습니다 @msg no active perspective plane 활성 원근 평면이 없습니다 +@msg the perspective grid is hidden 원근 격자가 숨겨져 있습니다 +@msg Automatic Plane Positioning is off: turn on anchorPoint or gridlineIntersection (perspective.widget.options) 자동 평면 배치가 꺼져 있습니다: anchorPoint 또는 gridlineIntersection을 켜세요 (perspective.widget.options) +@msg anchorPoint must be true or false anchorPoint는 true 또는 false여야 합니다 +@msg gridlineIntersection must be true or false gridlineIntersection은 true 또는 false여야 합니다 +@msg tolerance must be 0 or more tolerance는 0 이상이어야 합니다 +@msg give `at` or `clear`, not both `at`과 `clear` 중 하나만 지정하세요 @msg plane must be left, right or ground plane은 left, right 또는 ground여야 합니다 @msg missing `id` (see plugin.list) `id`가 없습니다(plugin.list 참조) @msg no plug-in {id} is installed 플러그인 {id}이(가) 설치되어 있지 않습니다 @@ -5555,6 +5579,14 @@ liquify-list-end {0}, {1} {0} 및 {1} @msg the main script engine is new for each run and is never kept, so it cannot be dropped 기본 스크립트 엔진은 실행마다 새로 만들어지고 유지되지 않으므로 삭제할 수 없습니다 @msg there is no script engine named {name} 이름이 {name}인 스크립트 엔진이 없습니다 @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers`는 물어볼 사람이 없는 실행에만 쓰입니다. 앱에서는 사람이 각 대화 상자에 답합니다 +@msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel`은(는) 1에서 {_1} 사이의 정수여야 합니다 +@msg `args{place}` is nested more than 64 levels deep `args{place}`이(가) 64단계보다 깊게 중첩되어 있습니다 +@msg `args` must be an object `args`은(는) 개체여야 합니다 +@msg `args` is larger than 1 MiB `args`이(가) 1 MiB보다 큽니다 +@msg `path` is empty `path`이(가) 비어 있습니다 +@msg `installed` takes a `path`, not a `source` `installed`에는 `source`가 아니라 `path`를 지정하세요 +@msg `path` must name a .js or .jsx file `path`은(는) .js 또는 .jsx 파일을 가리켜야 합니다 +@msg give exactly one of `path` and `source` `path`, `source` 중 정확히 하나를 지정하세요 @msg Running a script 스크립트 실행 중 @msg Copied the script report 스크립트 보고서를 복사했습니다 @msg Script file access denied: {path} 스크립트 파일 접근이 거부되었습니다: {path} @@ -5672,6 +5704,8 @@ liquify-list-end {0}, {1} {0} 및 {1} @msg the {tool} tool has no options {tool} 도구에는 옵션이 없습니다 @msg unknown tool `{tool}` 알 수 없는 도구 `{tool}` @msg {tool} isn't in a toolbar group of several tools {tool}은(는) 여러 도구가 있는 도구 모음 그룹에 속하지 않습니다 +@msg Presentation Mode hides the toolbars: change the screen mode to show them 프레젠테이션 모드에서는 도구 모음이 숨겨집니다: 표시하려면 화면 모드를 변경하세요 +@msg Tab has hidden the toolbars: press Tab to show them Tab으로 도구 모음이 숨겨졌습니다: 표시하려면 Tab을 누르세요 @msg no such document 해당 문서가 없습니다 @msg {_1}: not saved, so not closed {_1}: 저장되지 않아 닫지 않았습니다 @msg `{name}` is a built-in workspace; choose another name `{name}`은(는) 기본 제공 작업 영역입니다: 다른 이름을 선택하세요 @@ -5723,6 +5757,7 @@ liquify-list-end {0}, {1} {0} 및 {1} @msg a linked JavaScript file is outside the read roots 연결된 JavaScript 파일이 읽기 루트 밖에 있습니다 @msg a linked image file is outside the read roots 연결된 이미지 파일이 읽기 루트 밖에 있습니다 @msg a linked file's export folder is outside the read roots 연결된 파일의 내보내기 폴더가 읽기 루트 밖에 있습니다 +@msg a linked file's editing data can't be read to check it against the read roots 연결된 파일의 편집 데이터를 읽을 수 없어 읽기 루트와 대조할 수 없습니다 @msg automation path rejected: outside the write root {root}: {path} 자동화 경로가 거부되었습니다: 쓰기 루트 {root} 밖입니다: {path} @msg automation path rejected: outside the write roots {roots}: {path} 자동화 경로가 거부되었습니다: 쓰기 루트 {roots} 밖입니다: {path} @msg automation path rejected: path is empty 자동화 경로가 거부되었습니다: 경로가 비어 있습니다 @@ -6000,6 +6035,7 @@ lighting Light 광원 Cove 오목 Depth 깊이 Front 앞면 + Side 옆면 Isometric Bottom 등각 밑면 Isometric Left 등각 왼쪽 Isometric Right 등각 오른쪽 @@ -6094,7 +6130,7 @@ lighting Light 광원 @msg each of `{GRAPHICS}` must be an object `{GRAPHICS}`의 각 항목은 개체여야 합니다 @msg `{GRAPHICS}` entries take symbol, face, x, y, scale and rotation, not `{k}` `{GRAPHICS}` 항목에는 symbol, face, x, y, scale, rotation만 사용할 수 있으며 `{k}`은(는) 사용할 수 없습니다 @msg each of `{GRAPHICS}` needs `symbol`, the name of a symbol `{GRAPHICS}`의 각 항목에는 심볼 이름인 `symbol`이 필요합니다 -@msg `{GRAPHICS}` face must be front or back `{GRAPHICS}`의 face는 front 또는 back이어야 합니다 +@msg `{GRAPHICS}` face must be front, back or side `{GRAPHICS}`의 face는 front, back 또는 side여야 합니다 @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} `{GRAPHICS}`의 {key}은(는) {lo}에서 {hi} 사이의 숫자여야 합니다 @msg `{GRAPHICS}` must be an array `{GRAPHICS}`은(는) 배열이어야 합니다 @msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types 그래픽은 평면, 돌출, 회전체, 부풀리기 개체 유형에 매핑됩니다 @@ -7342,6 +7378,14 @@ breakText Glyphs 글리프 Remove Gaps 간격 제거 @msg that makes too many pieces (at most 100000): make the dashes longer 조각이 너무 많아집니다(최대 100000개). 대시를 더 길게 하십시오 @msg select paths, or segments, to divide 나눌 패스나 세그먼트를 선택하십시오 +# Path Precision Tools add-on: Smooth Bridge. + Smooth Bridge… 부드러운 브리지… + Smooth Bridge 부드러운 브리지 + Keep Originals 원본 유지 +@msg select two circles to bridge 연결할 원 두 개를 선택하십시오 +@msg one circle is inside the other 한 원이 다른 원 안에 있습니다 +@msg the circles are too far apart for this radius: raise the radius 이 반경에서는 원이 너무 멀리 떨어져 있습니다. 반경을 늘리십시오 +@msg the circles are too far apart for this radius 이 반경에서는 원이 너무 멀리 떨어져 있습니다 # Path Precision Tools add-on: Common Tangents. Common Tangents… 공통 접선… Common Tangents 공통 접선 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 73a4921d78..b13e066e49 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -213,6 +213,14 @@ liquify-list-end {0}, {1} {0} en {1} @msg the main script engine is new for each run and is never kept, so it cannot be dropped de hoofdscriptengine is bij elke uitvoering nieuw en wordt nooit bewaard, dus kan hij niet worden verwijderd @msg there is no script engine named {name} er is geen scriptengine met de naam {name} @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` is alleen voor een uitvoering zonder iemand om te vragen: in de app beantwoordt de persoon elk dialoogvenster +@msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` moet een geheel getal van 1 tot {_1} zijn +@msg `args{place}` is nested more than 64 levels deep `args{place}` is meer dan 64 niveaus diep genest +@msg `args` must be an object `args` moet een object zijn +@msg `args` is larger than 1 MiB `args` is groter dan 1 MiB +@msg `path` is empty `path` is leeg +@msg `installed` takes a `path`, not a `source` `installed` neemt een `path`, geen `source` +@msg `path` must name a .js or .jsx file `path` moet een .js- of .jsx-bestand aanwijzen +@msg give exactly one of `path` and `source` geef precies een van `path` en `source` @msg Running a script Er wordt een script uitgevoerd @msg Data Recovery can't keep copies in {path}: {e} Gegevensherstel kan geen kopieën bewaren in {path}: {e} @msg Plug-ins can't be loaded from {path}: {e} Plug-ins kunnen niet worden geladen uit {path}: {e} @@ -2273,6 +2281,7 @@ digits Malayalam Malayalam Underline Onderstrepen Vertical Scale % Verticale schaal % Axis As + Axis Angle Ashoek ICF Top/Right ICF boven/rechts ICF Bottom/Left ICF onder/links Show Font Height Options Opties voor letterhoogte tonen @@ -2828,6 +2837,7 @@ digits Malayalam Malayalam Line Properties: Lijneigenschappen: Line Length: Lijnlengte: Line Angle: Lijnhoek: + Constrain Pie Angle Taarthoek vastleggen Rectangle Properties: Rechthoekeigenschappen: Shape Properties: Vormeigenschappen: Shape Properties Vormeigenschappen @@ -2869,6 +2879,7 @@ digits Malayalam Malayalam Scatter: Verspreiding: Rotation: Rotatie: Rotation relative to: Rotatie ten opzichte van: + Hue Jitter: Tintvariatie: Brush Scale Options Opties voor penseelschaling Scale Proportionately Proportioneel schalen Stretch to Fit Stroke Length Uitrekken tot lijnlengte @@ -2907,6 +2918,7 @@ digits Malayalam Malayalam Size: Grootte: Calligraphic Brush Options Opties voor kalligrafisch penseel Bristle Brush Options Opties voor borstelpenseel + Roundness Rondheid Roundness: Rondheid: Shape: Vorm: Bristle Length: Borstellengte: @@ -3903,6 +3915,8 @@ theme Appearance Vormgeving Current Brush Huidig penseel Current Symbol Huidig symbool Delete Brush Penseel verwijderen + Delete Color Kleur verwijderen + Restore Generated Table Gegenereerde tabel herstellen Delete Symbol Symbool verwijderen Delete the selected symbol? Het geselecteerde symbool verwijderen? Delete the selected symbols? De geselecteerde symbolen verwijderen? @@ -4356,6 +4370,7 @@ theme Appearance Vormgeving 90° & 45° Angles Hoeken van 90° & 45° 90° Angles Hoeken van 90° Additional Plug-ins Folder Extra map met plug-ins + Plug-in Instruction Budget Instructiebudget voor plug-ins Additional Fonts Folder Extra map met lettertypen Alignment Guides Uitlijnhulplijnen Anchor Points, Handle, and Bounding Box Display Weergave van ankerpunten, greep en begrenzingskader @@ -4382,6 +4397,7 @@ theme Appearance Vormgeving Data Recovery Gegevensherstel Default Language Standaardtaal Disable Auto Add/Delete Automatisch toevoegen/verwijderen uitschakelen + Interpolate Control Points When Moving Anchors Richtingsgrepen interpoleren bij het verplaatsen van ankerpunten Display All Blacks Accurately Alle zwarttinten nauwkeurig weergeven Display All Blacks as Rich Black Alle zwarttinten weergeven als rijk zwart Display Bitmaps as Anti-aliased Images in Pixel Preview Bitmaps in pixelvoorbeeld weergeven als afbeeldingen met antialiasing @@ -4470,6 +4486,9 @@ theme Appearance Vormgeving Printing / Exporting Afdrukken / exporteren Real-time Drawing and Editing Tekenen en bewerken in realtime Use Monitor Profile for Canvas Monitorprofiel gebruiken voor canvas + Refresh Monitor Profile Monitorprofiel vernieuwen +@msg turn on Use Monitor Profile for Canvas first schakel eerst 'Monitorprofiel gebruiken voor canvas' in +@msg this build doesn't read display profiles deze versie leest geen beeldschermprofielen The canvas is drawn in sRGB. Het canvas wordt in sRGB getekend. Canvas display profile: Weergaveprofiel van het canvas: The system matches the window to the display's colors. Het systeem stemt het venster af op de kleuren van het scherm. @@ -4866,6 +4885,9 @@ font-technology Variable Variabel Search commands, tools, panels and effects… Opdrachten, gereedschappen, panelen en effecten zoeken… No commands match Geen opdrachten gevonden {pos} of {total}: {name} {pos} van {total}: {name} + No menu item Geen menu-item + Toolbar Gereedschapsbalk + {toolbar}, in the {tool} group {toolbar}, in de groep {tool} @plural {n} result|{n} results {n} resultaat|{n} resultaten @plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} van {n} resultaat. Typ verder om ze te beperken.|{shown} van {n} resultaten. Typ verder om ze te beperken. Recent Commands Recente opdrachten @@ -4902,6 +4924,7 @@ font-technology Variable Variabel The mouse wheel with Cmd/Ctrl held scrolls the canvas sideways. Het muiswiel met Cmd/Ctrl ingedrukt schuift het canvas zijwaarts. Dragging sideways on a numeric field's label changes the field's value. Zijwaarts slepen over het label van een numeriek veld wijzigt de waarde van het veld. A two-finger rotate gesture on a trackpad rotates the canvas view. Een draaigebaar met twee vingers op een trackpad draait de weergave van het canvas. + When you move anchor points, each curve with one moved end keeps its shape relative to its ends. Als u ankerpunten verplaatst, behoudt elke curve met één verplaatst uiteinde zijn vorm ten opzichte van zijn uiteinden. Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Als u de sneltoets van een gereedschap ingedrukt houdt, is dat gereedschap gekozen tot u loslaat, en daarna wordt het vorige gereedschap weer gekozen. Shows the bounding box while you move the selection or draw a shape. Toont het begrenzingskader terwijl u de selectie verplaatst of een vorm tekent. Create Trim Marks draws Japanese-style marks instead of Roman ones. Afsnijtekens maken tekent tekens in Japanse stijl in plaats van Romeinse. @@ -5428,6 +5451,7 @@ imageTrace Outline Contour @msg choose a folder to export to kies een map om naar te exporteren @msg choose a location for the package kies een locatie voor het pakket @msg clipboard is empty het klembord is leeg +@msg colorTable.deleted: at least one color has to stay in the color table colorTable.deleted: er moet ten minste één kleur in de kleurentabel blijven @msg colorTable.{what}: `{h}` is not a colour such as "#ff8800" colorTable.{what}: `{h}` is geen kleur zoals "#ff8800" @msg colorTable.{what}: at most {MAX_TABLE} colours colorTable.{what}: maximaal {MAX_TABLE} kleuren @msg command `{0}` is not available right now: {1} opdracht `{0}` is nu niet beschikbaar: {1} @@ -5482,6 +5506,12 @@ imageTrace Outline Contour @msg no PNG encoder geen PNG-encoder @msg no active document geen actief document @msg no active perspective plane geen actief perspectiefvlak +@msg the perspective grid is hidden het perspectiefraster is verborgen +@msg Automatic Plane Positioning is off: turn on anchorPoint or gridlineIntersection (perspective.widget.options) Automatische vlakpositionering staat uit: zet anchorPoint of gridlineIntersection aan (perspective.widget.options) +@msg anchorPoint must be true or false anchorPoint moet true of false zijn +@msg gridlineIntersection must be true or false gridlineIntersection moet true of false zijn +@msg tolerance must be 0 or more tolerance moet 0 of meer zijn +@msg give `at` or `clear`, not both geef `at` of `clear`, niet beide @msg no anchor points selected geen ankerpunten geselecteerd @msg `points` must be two or three [x, y] pairs of numbers `points` moet uit twee of drie getallenparen [x, y] bestaan @msg direct-select two or three anchor points, or give `points` selecteer met directe selectie twee of drie ankerpunten of geef `points` op @@ -5887,6 +5917,8 @@ imageTrace Outline Contour @msg Reload the page to go on (changes not saved yet may be lost). Laad de pagina opnieuw om door te gaan (nog niet opgeslagen wijzigingen kunnen verloren gaan). @msg tool (a tool id) is required tool (een gereedschaps-id) is vereist @msg {tool} isn't in a toolbar group of several tools {tool} zit niet in een werkbalkgroep met meerdere gereedschappen +@msg Presentation Mode hides the toolbars: change the screen mode to show them Presentatiemodus verbergt de werkbalken: wijzig de schermmodus om ze te tonen +@msg Tab has hidden the toolbars: press Tab to show them Tab heeft de werkbalken verborgen: druk op Tab om ze te tonen @msg onto must name a panel floating in another group onto moet een zwevend paneel in een andere groep benoemen @msg below and above must name a panel floating in another group below en above moeten een zwevend paneel in een andere groep benoemen @msg give only one of onto, below and above geef slechts één van onto, below en above @@ -6460,6 +6492,7 @@ imageTrace Outline Contour @msg a linked JavaScript file is outside the read roots een gekoppeld JavaScript-bestand staat buiten de leesroots @msg a linked image file is outside the read roots een gekoppeld afbeeldingsbestand staat buiten de leesroots @msg a linked file's export folder is outside the read roots de exportmap van een gekoppeld bestand staat buiten de leesroots +@msg a linked file's editing data can't be read to check it against the read roots de bewerkingsgegevens van een gekoppeld bestand kunnen niet worden gelezen om ze aan de leesroots te toetsen @msg a name names one asset: give multiple: false, or one object een naam noemt één asset: geef multiple: false, of één object @msg a namespace declaration uses a reserved prefix or URI een naamruimtedeclaratie gebruikt een gereserveerd voorvoegsel of een gereserveerde URI @msg a namespace qualifier is undefined een naamruimtekwalificatie is niet gedefinieerd @@ -8172,6 +8205,7 @@ mark-style Japanese Japans Cove Cove Depth Diepte Front Voorkant + Side Zijkant Isometric Bottom Isometrisch onder Isometric Left Isometrisch links Isometric Right Isometrisch rechts @@ -8266,7 +8300,7 @@ mark-style Japanese Japans @msg each of `{GRAPHICS}` must be an object elk item van `{GRAPHICS}` moet een object zijn @msg `{GRAPHICS}` entries take symbol, face, x, y, scale and rotation, not `{k}` items van `{GRAPHICS}` nemen symbol, face, x, y, scale en rotation aan, niet `{k}` @msg each of `{GRAPHICS}` needs `symbol`, the name of a symbol elk item van `{GRAPHICS}` heeft `symbol` nodig, de naam van een symbool -@msg `{GRAPHICS}` face must be front or back face in `{GRAPHICS}` moet front of back zijn +@msg `{GRAPHICS}` face must be front, back or side face in `{GRAPHICS}` moet front, back of side zijn @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} {key} in `{GRAPHICS}` moet een getal van {lo} tot {hi} zijn @msg `{GRAPHICS}` must be an array `{GRAPHICS}` moet een array zijn @msg Graphics map onto planar faces: use the Extrude or Plane object type Illustraties worden op platte vlakken geplaatst: gebruik het objecttype Extruderen of Vlak @@ -9637,6 +9671,14 @@ breakText Glyphs Glyphs Remove Gaps Tussenruimten verwijderen @msg that makes too many pieces (at most 100000): make the dashes longer dat geeft te veel stukken (hoogstens 100000): maak de streepjes langer @msg select paths, or segments, to divide selecteer paden of segmenten om te verdelen +# Path Precision Tools add-on: Smooth Bridge. + Smooth Bridge… Vloeiende brug… + Smooth Bridge Vloeiende brug + Keep Originals Originelen behouden +@msg select two circles to bridge selecteer twee cirkels om te verbinden +@msg one circle is inside the other de ene cirkel ligt binnen de andere +@msg the circles are too far apart for this radius: raise the radius de cirkels liggen te ver uit elkaar voor deze straal: vergroot de straal +@msg the circles are too far apart for this radius de cirkels liggen te ver uit elkaar voor deze straal # Path Precision Tools add-on: Common Tangents. Common Tangents… Gemeenschappelijke raaklijnen… Common Tangents Gemeenschappelijke raaklijnen diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index a8b7b583cf..4d5c25d727 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -1691,6 +1691,7 @@ digits Malayalam Malajalam Underline Podkreślenie Vertical Scale % Skala pionowa % Axis Oś + Axis Angle Kąt osi ICF Top/Right ICF góra/prawo ICF Bottom/Left ICF dół/lewo Show Font Height Options Pokaż opcje wysokości czcionki @@ -2249,8 +2250,8 @@ digits Malayalam Malajalam Weight: Grubość: Art using a deleted global swatch keeps its colour. Kompozycja używająca usuniętej próbki globalnej zachowa swój kolor. Color Group: {name} Grupa kolorów: {name} - Delete the selected items and their artwork? Usunąć zaznaczone elementy razem z grafiką? - Delete this layer and its artwork? Usunąć tę warstwę razem z grafiką? + Delete the selected items and their artwork? Usunąć zaznaczone elementy razem z kompozycją? + Delete this layer and its artwork? Usunąć tę warstwę razem z kompozycją? Delete “{name}”? Usunąć „{name}”? Document Swatches Próbki dokumentu Edit or Apply Color Group Edytuj lub zastosuj grupę kolorów @@ -2359,6 +2360,7 @@ digits Malayalam Malajalam Line Properties: Właściwości linii: Line Length: Długość linii: Line Angle: Kąt linii: + Constrain Pie Angle Zachowaj kąt wycinka Rectangle Properties: Właściwości prostokąta: Shape Properties: Właściwości kształtu: Shape Properties Właściwości kształtu @@ -2399,6 +2401,7 @@ digits Malayalam Malajalam Scatter: Rozproszenie: Rotation: Obrót: Rotation relative to: Obrót względem: + Hue Jitter: Zmienność barwy: Brush Scale Options Opcje skali pędzla Scale Proportionately Skaluj proporcjonalnie Stretch to Fit Stroke Length Rozciągnij do długości obrysu @@ -2437,6 +2440,7 @@ digits Malayalam Malajalam Size: Rozmiar: Calligraphic Brush Options Opcje pędzla kaligraficznego Bristle Brush Options Opcje pędzla włosiankowego + Roundness Okrągłość Roundness: Okrągłość: Shape: Kształt: Bristle Length: Długość włosia: @@ -2691,7 +2695,7 @@ digits Malayalam Malajalam Consider Open Filled Paths as Closed Traktuj otwarte wypełnione ścieżki jako zamknięte In Merge Mode, Clicking Stroke Splits the Path W trybie scalania kliknięcie obrysu dzieli ścieżkę Pick Color From: Źródło koloru: - Artwork Grafika + Artwork Kompozycja Cursor Swatch Preview Podgląd próbek przy kursorze Selection: Zaznaczanie: Straight Line Linia prosta @@ -3269,7 +3273,7 @@ antiAlias Sharp Ostre Export Preset: Ustawienie eksportu: Folders: Foldery: Insert Wstaw - Nothing is selected. Select the art to export, then open this tab again. Nic nie zaznaczono. Zaznacz grafikę do eksportu i ponownie otwórz tę kartę. + Nothing is selected. Select the art to export, then open this tab again. Nic nie zaznaczono. Zaznacz kompozycję do eksportu i ponownie otwórz tę kartę. One File of the Selection Jeden plik z zaznaczenia Start at: Zacznij od: {n} objects selected Zaznaczone obiekty: {n} @@ -3461,6 +3465,8 @@ theme Appearance Wygląd Current Brush Bieżący pędzel Current Symbol Bieżący symbol Delete Brush Usuń pędzel + Delete Color Usuń kolor + Restore Generated Table Przywróć wygenerowaną tablicę Delete Symbol Usuń symbol Delete the selected symbol? Usunąć zaznaczony symbol? Delete the selected symbols? Usunąć zaznaczone symbole? @@ -3921,6 +3927,7 @@ theme Appearance Wygląd 90° & 45° Angles Kąty 90° i 45° 90° Angles Kąty 90° Additional Plug-ins Folder Dodatkowy folder wtyczek + Plug-in Instruction Budget Budżet instrukcji wtyczek Additional Fonts Folder Dodatkowy folder czcionek Alignment Guides Linie wyrównania Anchor Points, Handle, and Bounding Box Display Wyświetlanie punktów kontrolnych, uchwytów i obwiedni @@ -3947,6 +3954,7 @@ theme Appearance Wygląd Data Recovery Odzyskiwanie danych Default Language Język domyślny Disable Auto Add/Delete Wyłącz automatyczne dodawanie/usuwanie + Interpolate Control Points When Moving Anchors Interpoluj uchwyty kierunkowe podczas przesuwania punktów kontrolnych Display All Blacks Accurately Wyświetlaj wszystkie czernie dokładnie Display All Blacks as Rich Black Wyświetlaj wszystkie czernie jako czerń głęboką Display Bitmaps as Anti-aliased Images in Pixel Preview Wyświetlaj bitmapy wygładzone w podglądzie pikseli @@ -4035,6 +4043,9 @@ theme Appearance Wygląd Printing / Exporting Drukowanie / eksportowanie Real-time Drawing and Editing Rysowanie i edycja w czasie rzeczywistym Use Monitor Profile for Canvas Użyj profilu monitora dla płótna + Refresh Monitor Profile Odśwież profil monitora +@msg turn on Use Monitor Profile for Canvas first najpierw włącz „Użyj profilu monitora dla płótna” +@msg this build doesn't read display profiles ta wersja nie odczytuje profili wyświetlaczy The canvas is drawn in sRGB. Płótno jest rysowane w sRGB. Canvas display profile: Profil wyświetlacza płótna: The system matches the window to the display's colors. System dopasowuje okno do kolorów wyświetlacza. @@ -4420,6 +4431,9 @@ font-technology Variable Zmienne Search commands, tools, panels and effects… Szukaj poleceń, narzędzi, paneli i efektów… No commands match Żadne polecenie nie pasuje {pos} of {total}: {name} {pos} z {total}: {name} + No menu item Brak pozycji menu + Toolbar Pasek narzędzi + {toolbar}, in the {tool} group {toolbar}, w grupie {tool} @plural {n} result|{n} results {n} wynik|{n} wyniki|{n} wyników @plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} z {n} wyniku. Pisz dalej, aby je zawęzić.|{shown} z {n} wyników. Pisz dalej, aby je zawęzić.|{shown} z {n} wyników. Pisz dalej, aby je zawęzić. Recent Commands Ostatnie polecenia @@ -4443,23 +4457,24 @@ font-technology Variable Zmienne Drawing tools show a crosshair pointer instead of their icon; Caps Lock does the same while it is on. Narzędzia do rysowania pokazują wskaźnik w kształcie krzyżyka zamiast swojej ikony; Caps Lock działa tak samo, dopóki jest włączony. Shows a tip when the pointer rests on a button or field that has one. Pokazuje wskazówkę, gdy wskaźnik zatrzyma się na przycisku lub polu, które ją ma. Shows a warning before a script you choose runs. Pokazuje ostrzeżenie przed uruchomieniem wybranego skryptu. - Smooths the edges of artwork on the canvas. Wygładza krawędzie grafiki na obszarze roboczym. + Smooths the edges of artwork on the canvas. Wygładza krawędzie kompozycji na obszarze roboczym. Select › Same › Fill Color, Stroke Color and Fill & Stroke match only the same tint of a global or spot swatch, not any tint of it. Zaznacz › Taki sam › Kolor wypełnienia, Kolor obrysu oraz Wypełnienie i obrys dopasowują tylko ten sam odcień globalnej lub dodatkowej próbki, a nie dowolny jej odcień. Shows the Home screen when no document is open; off, the window stays empty until you click Home. Pokazuje stronę startową, gdy nie jest otwarty żaden dokument; po wyłączeniu okno pozostaje puste, dopóki nie klikniesz Strona startowa. Measures objects with their strokes and shape-changing effects for size, position and alignment; shadows, glows and blurs are not measured. Mierzy obiekty razem z obrysami i efektami zmieniającymi kształt na potrzeby rozmiaru, położenia i wyrównania; cienie, poświaty i rozmycia nie są mierzone. At 100% zoom, one inch of the document takes 96 screen points instead of 72. Przy powiększeniu 100% jeden cal dokumentu zajmuje 96 punktów ekranu zamiast 72. Double-clicking a group, path or image with the Selection tool opens it in isolation mode. Dwukrotne kliknięcie grupy, ścieżki lub obrazu narzędziem Zaznaczanie otwiera je w trybie izolacji. - Pattern fills and strokes transform with the art, unless a transform or the Transform panel's menu chooses otherwise. Wypełnienia i obrysy wzorkiem przekształcają się razem z grafiką, chyba że przekształcenie lub menu panelu Przekształć wybierze inaczej. - Live corner radii scale with the art, unless the scale chooses otherwise. Promienie narożników dynamicznych skalują się razem z grafiką, chyba że skalowanie wybierze inaczej. - Stroke weights, dashes and effect distances scale with the art, unless the scale chooses otherwise. Grubości obrysów, kreski i odległości efektów skalują się razem z grafiką, chyba że skalowanie wybierze inaczej. + Pattern fills and strokes transform with the art, unless a transform or the Transform panel's menu chooses otherwise. Wypełnienia i obrysy wzorkiem przekształcają się razem z kompozycją, chyba że przekształcenie lub menu panelu Przekształć wybierze inaczej. + Live corner radii scale with the art, unless the scale chooses otherwise. Promienie narożników dynamicznych skalują się razem z kompozycją, chyba że skalowanie wybierze inaczej. + Stroke weights, dashes and effect distances scale with the art, unless the scale chooses otherwise. Grubości obrysów, kreski i odległości efektów skalują się razem z kompozycją, chyba że skalowanie wybierze inaczej. The mouse wheel zooms the canvas instead of scrolling it. Kółko myszy powiększa obszar roboczy zamiast go przewijać. The mouse wheel with Cmd/Ctrl held scrolls the canvas sideways. Kółko myszy z wciśniętym Cmd/Ctrl przewija obszar roboczy w poziomie. Dragging sideways on a numeric field's label changes the field's value. Przeciąganie w bok po etykiecie pola liczbowego zmienia wartość pola. A two-finger rotate gesture on a trackpad rotates the canvas view. Gest obrotu dwoma palcami na gładziku obraca widok obszaru roboczego. + When you move anchor points, each curve with one moved end keeps its shape relative to its ends. Podczas przesuwania punktów kontrolnych każda krzywa z jednym przesuniętym końcem zachowuje kształt względem swoich końców. Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Przytrzymanie skrótu narzędzia wybiera je do momentu puszczenia klawisza, a potem ponownie wybierane jest poprzednie narzędzie. Shows the bounding box while you move the selection or draw a shape. Pokazuje obwiednię podczas przesuwania zaznaczenia lub rysowania kształtu. Create Trim Marks draws Japanese-style marks instead of Roman ones. Utwórz znaczniki przycięcia rysuje znaczniki w stylu japońskim zamiast rzymskich. - New art takes only the fill and stroke of the selection; off, it takes the selected object's whole appearance. Nowa grafika przejmuje tylko wypełnienie i obrys zaznaczenia; po wyłączeniu przejmuje cały wygląd zaznaczonego obiektu. + New art takes only the fill and stroke of the selection; off, it takes the selected object's whole appearance. Nowa kompozycja przejmuje tylko wypełnienie i obrys zaznaczenia; po wyłączeniu przejmuje cały wygląd zaznaczonego obiektu. Changing the width or height in the Transform panel, the Properties panel or the Control bar changes the other in proportion. Zmiana szerokości lub wysokości w panelu Przekształć, panelu Właściwości lub panelu Sterowanie proporcjonalnie zmienia drugi wymiar. A live rectangle's properties show one Corner Radius field for all four corners; off, each corner has its own field. Właściwości dynamicznego prostokąta pokazują jedno pole Promień narożnika dla wszystkich czterech narożników; po wyłączeniu każdy narożnik ma własne pole. What edits in the Transform panel transform: the object, its pattern tiles or both; Default follows Transform Pattern Tiles. Co przekształcają zmiany w panelu Przekształć: obiekt, kafelki jego wzorka lub oba; Domyślne podąża za opcją Przekształcaj kafelki wzorków. @@ -4472,7 +4487,7 @@ font-technology Variable Zmienne How near, in pixels, a point must come to an anchor or ruler guide for Snap to Point to snap it; with Smart Guides on, Smart Guides' Snapping Tolerance applies instead. Jak blisko, w pikselach, punkt musi podejść do punktu kontrolnego lub linii pomocniczej linijki, aby Przyciągaj do punktów go przyciągnęło; przy włączonych inteligentnych liniach pomocniczych obowiązuje ich tolerancja przyciągania. With the Selection tool, Cmd/Ctrl-click selects the object under the selected one at the pointer; each further click goes one object deeper. Z narzędziem Zaznaczanie Cmd/Ctrl+kliknięcie zaznacza obiekt pod zaznaczonym w miejscu wskaźnika; każde kolejne kliknięcie schodzi o jeden obiekt głębiej. Zoom In and Zoom Out bring the center of the selection to the middle of the view. Powiększ i Pomniejsz przenoszą środek zaznaczenia na środek widoku. - Locked and hidden artwork inside an artboard moves, scales and is copied with the artboard, as the other artwork does. Zablokowana i ukryta grafika wewnątrz obszaru kompozycji jest przesuwana, skalowana i kopiowana razem z nim, tak jak pozostała grafika. + Locked and hidden artwork inside an artboard moves, scales and is copied with the artboard, as the other artwork does. Zablokowana i ukryta kompozycja wewnątrz obszaru kompozycji jest przesuwana, skalowana i kopiowana razem z nim, tak jak pozostała kompozycja. The size of anchor points and direction handle ends on the canvas; larger anchors can also be picked from farther away. Rozmiar punktów kontrolnych i końców uchwytów kierunkowych na obszarze roboczym; większe punkty kontrolne można chwycić także z większej odległości. Draws the ends of direction handles as solid dots, hollow dots or larger solid dots. Rysuje końce uchwytów kierunkowych jako pełne kropki, puste kropki lub większe pełne kropki. With the Direct Selection tool, the anchor under the pointer is highlighted. Z narzędziem Zaznaczanie bezpośrednie punkt kontrolny pod wskaźnikiem jest wyróżniany. @@ -4518,22 +4533,22 @@ font-technology Variable Zmienne Draws the grid as lines, or as dots along the major gridlines at each subdivision. Rysuje siatkę jako linie albo jako kropki wzdłuż głównych linii siatki przy każdym podpodziale. The distance between major gridlines, in every open document and in new ones; a VectorCraft document opens with the grid it was saved with. Odstęp między głównymi liniami siatki w każdym otwartym dokumencie i w nowych; dokument VectorCraft otwiera się z siatką, z którą został zapisany. How many parts each major grid square is divided into; Snap to Grid snaps to these parts, even when the zoom hides their lines. Na ile części dzieli się każdy główny kwadrat siatki; Przyciągaj do siatki przyciąga do tych części, nawet gdy powiększenie ukrywa ich linie. - Draws the grid behind the artwork; off, the grid is drawn over it. Rysuje siatkę za grafiką; po wyłączeniu siatka jest rysowana na niej. - In Pixel Preview at 600% zoom or more, the active view shows a line at the edge of every document pixel over the artwork. W Podglądzie pikseli przy powiększeniu 600% lub większym aktywny widok pokazuje nad grafiką linię na krawędzi każdego piksela dokumentu. + Draws the grid behind the artwork; off, the grid is drawn over it. Rysuje siatkę za kompozycją; po wyłączeniu siatka jest rysowana na niej. + In Pixel Preview at 600% zoom or more, the active view shows a line at the edge of every document pixel over the artwork. W Podglądzie pikseli przy powiększeniu 600% lub większym aktywny widok pokazuje nad kompozycją linię na krawędzi każdego piksela dokumentu. The color of the tile edge and the dashed swatch bounds shown while you edit a pattern. Kolor krawędzi kafelka i przerywanych granic próbki widocznych podczas edycji wzorka. - Snaps drawing, moving and transforming to nearby art and shows guides and labels; Pixel Preview turns them off, and Snap to Grid snaps to the grid instead. Przyciąga rysowanie, przesuwanie i przekształcanie do pobliskiej grafiki oraz pokazuje linie pomocnicze i etykiety; Podgląd pikseli je wyłącza, a Przyciągaj do siatki przyciąga zamiast nich do siatki. + Snaps drawing, moving and transforming to nearby art and shows guides and labels; Pixel Preview turns them off, and Snap to Grid snaps to the grid instead. Przyciąga rysowanie, przesuwanie i przekształcanie do pobliskiej kompozycji oraz pokazuje linie pomocnicze i etykiety; Podgląd pikseli je wyłącza, a Przyciągaj do siatki przyciąga zamiast nich do siatki. The color of Smart Guide lines and labels. Kolor linii i etykiet inteligentnych linii pomocniczych. - Shows a line along the edge or center that art lines up with; off, art still lines up without the line, and Snap to Glyph does not apply. Pokazuje linię wzdłuż krawędzi lub środka, do których wyrównuje się grafika; po wyłączeniu grafika nadal się wyrównuje bez linii, a Przyciągaj do glifów nie działa. + Shows a line along the edge or center that art lines up with; off, art still lines up without the line, and Snap to Glyph does not apply. Pokazuje linię wzdłuż krawędzi lub środka, do których wyrównuje się kompozycja; po wyłączeniu kompozycja nadal się wyrównuje bez linii, a Przyciągaj do glifów nie działa. With a selection tool, outlines the unselected object under the pointer in its layer color while you are not dragging. Przy narzędziu zaznaczania obrysowuje niezaznaczony obiekt pod wskaźnikiem kolorem jego warstwy, dopóki nie przeciągasz. - Shows the size or angle next to the pointer while you scale, rotate, shear or reflect art. Pokazuje rozmiar lub kąt obok wskaźnika podczas skalowania, obracania, pochylania lub odbijania grafiki. + Shows the size or angle next to the pointer while you scale, rotate, shear or reflect art. Pokazuje rozmiar lub kąt obok wskaźnika podczas skalowania, obracania, pochylania lub odbijania kompozycji. While you draw, points snap to lines at the chosen Angles through the point the segment or shape starts from. Podczas rysowania punkty przyciągają się do linii pod wybranymi kątami przechodzących przez punkt, od którego zaczyna się segment lub kształt. The set of angles the construction guides follow while Construction Guides is on. Zestaw kątów, wzdłuż których biegną linie konstrukcyjne, gdy Linie konstrukcyjne są włączone. Names what a point snaps to, such as an anchor, a path or an alignment; off, points snap the same way without the names. Nazywa to, do czego przyciąga się punkt, np. punkt kontrolny, ścieżkę lub wyrównanie; po wyłączeniu punkty przyciągają się tak samo, bez nazw. - Shows distances, angles and how far art has moved next to the pointer while you draw or move it. Pokazuje obok wskaźnika odległości, kąty i to, o ile przesunęła się grafika, podczas rysowania lub przesuwania. - Snaps moved or resized art to the same gap as between nearby objects, and marks the equal gaps. Przyciąga przesuniętą grafikę lub grafikę o zmienionym rozmiarze do takiego samego odstępu jak między pobliskimi obiektami i zaznacza równe odstępy. + Shows distances, angles and how far art has moved next to the pointer while you draw or move it. Pokazuje obok wskaźnika odległości, kąty i to, o ile przesunęła się kompozycja, podczas rysowania lub przesuwania. + Snaps moved or resized art to the same gap as between nearby objects, and marks the equal gaps. Przyciąga przesuniętą kompozycję lub kompozycję o zmienionym rozmiarze do takiego samego odstępu jak między pobliskimi obiektami i zaznacza równe odstępy. With something selected, holding Alt/Option over another object or an artboard shows the distances between it and the selection. Gdy coś jest zaznaczone, przytrzymanie Alt/Option nad innym obiektem lub obszarem kompozycji pokazuje odległości między nim a zaznaczeniem. A selection dragged back to within the Snapping Tolerance of where the drag began goes back to exactly that place; a copy does not. Zaznaczenie przeciągnięte z powrotem na odległość tolerancji przyciągania od miejsca, w którym zaczęło się przeciąganie, wraca dokładnie w to miejsce; kopia nie. - How near on screen the pointer or a dragged point must come to art for Smart Guides to snap to it; the distance is the same at every zoom. Jak blisko na ekranie wskaźnik lub przeciągany punkt musi znaleźć się przy grafice, aby inteligentne linie pomocnicze go przyciągnęły; odległość jest taka sama przy każdym powiększeniu. + How near on screen the pointer or a dragged point must come to art for Smart Guides to snap to it; the distance is the same at every zoom. Jak blisko na ekranie wskaźnik lub przeciągany punkt musi znaleźć się przy kompozycji, aby inteligentne linie pomocnicze go przyciągnęły; odległość jest taka sama przy każdym powiększeniu. Snaps the end of a line segment, or a circle drawn from its center, so that it touches a nearby curve. Przyciąga koniec odcinka lub okrąg rysowany od środka tak, aby dotykał pobliskiej krzywej. Snaps the end of a line segment so that it meets a nearby straight segment at a right angle. Przyciąga koniec odcinka tak, aby spotykał pobliski prosty segment pod kątem prostym. Reset all preferences to their defaults? Przywrócić domyślne wartości wszystkich preferencji? @@ -5179,12 +5194,13 @@ liquify-list-end {0}, {1} {0} i {1} @msg check an asset to export zaznacz zasób do eksportu @msg check an artboard to export zaznacz obszar kompozycji do eksportu @msg check a layer to export zaznacz warstwę do eksportu -@msg select the art to export first najpierw zaznacz grafikę do eksportu +@msg select the art to export first najpierw zaznacz kompozycję do eksportu @msg choice must be "merge" or "add", not `{choice}` wybór musi mieć wartość "merge" lub "add", nie `{choice}` @msg choose a direction to divide in wybierz kierunek podziału @msg choose a folder to export to wybierz folder docelowy eksportu @msg choose a location for the package wybierz lokalizację pakietu @msg clipboard is empty schowek jest pusty +@msg colorTable.deleted: at least one color has to stay in the color table colorTable.deleted: w tablicy kolorów musi zostać co najmniej jeden kolor @msg colorTable.{what}: `{h}` is not a colour such as "#ff8800" colorTable.{what}: `{h}` nie jest kolorem w rodzaju "#ff8800" @msg colorTable.{what}: at most {MAX_TABLE} colours colorTable.{what}: maksymalnie {MAX_TABLE} kolorów @msg command `{0}` is not available right now: {1} polecenie `{0}` jest teraz niedostępne: {1} @@ -5252,6 +5268,12 @@ liquify-list-end {0}, {1} {0} i {1} @msg no PNG encoder brak kodera PNG @msg no active document brak aktywnego dokumentu @msg no active perspective plane brak aktywnej płaszczyzny perspektywy +@msg the perspective grid is hidden siatka perspektywy jest ukryta +@msg Automatic Plane Positioning is off: turn on anchorPoint or gridlineIntersection (perspective.widget.options) Automatyczne pozycjonowanie płaszczyzny jest wyłączone: włącz anchorPoint lub gridlineIntersection (perspective.widget.options) +@msg anchorPoint must be true or false anchorPoint musi mieć wartość true lub false +@msg gridlineIntersection must be true or false gridlineIntersection musi mieć wartość true lub false +@msg tolerance must be 0 or more tolerance musi wynosić 0 lub więcej +@msg give `at` or `clear`, not both podaj `at` albo `clear`, nie oba naraz @msg no anchor points selected nie zaznaczono punktów kontrolnych @msg `points` must be two or three [x, y] pairs of numbers `points` musi zawierać dwie lub trzy pary liczb [x, y] @msg direct-select two or three anchor points, or give `points` zaznacz bezpośrednio dwa lub trzy punkty kontrolne lub podaj `points` @@ -5726,6 +5748,8 @@ variable-list-end {0}, {1} {0} i {1} @msg Reload the page to go on (changes not saved yet may be lost). Odśwież stronę, aby kontynuować (niezapisane zmiany mogą zostać utracone). @msg tool (a tool id) is required wymagane jest tool (identyfikator narzędzia) @msg {tool} isn't in a toolbar group of several tools {tool} nie należy do grupy kilku narzędzi na pasku narzędzi +@msg Presentation Mode hides the toolbars: change the screen mode to show them Tryb prezentacji ukrywa paski narzędzi: zmień tryb ekranu, aby je pokazać +@msg Tab has hidden the toolbars: press Tab to show them klawisz Tab ukrył paski narzędzi: naciśnij Tab, aby je pokazać @msg onto must name a panel floating in another group onto musi wskazywać panel pływający w innej grupie @msg below and above must name a panel floating in another group below i above muszą wskazywać panel pływający w innej grupie @msg give only one of onto, below and above podaj tylko jedno z: onto, below, above @@ -5736,7 +5760,7 @@ variable-list-end {0}, {1} {0} i {1} @msg `{what}` closes nothing `{what}` niczego nie zamyka @msg `{what}` closes something it didn't open `{what}` zamyka coś, czego nie otworzył @msg a mask that covers several layers comes in as a clipping group in each layer it covers maska obejmująca kilka warstw jest wczytywana jako grupa przycinająca w każdej obejmowanej warstwie -@msg a graph's records don't end where they should: its art was read as it is rekordy wykresu nie kończą się tam, gdzie powinny: jego grafika została wczytana tak, jak jest +@msg a graph's records don't end where they should: its art was read as it is rekordy wykresu nie kończą się tam, gdzie powinny: jego kompozycja została wczytana tak, jak jest @msg `{w}` takes no operands `{w}` nie przyjmuje operandów @msg a wraparound group is inside a compound path grupa oblewania tekstem jest wewnątrz ścieżki złożonej @msg a path has too many points ścieżka ma zbyt wiele punktów @@ -5760,7 +5784,7 @@ variable-list-end {0}, {1} {0} i {1} @msg more names that aren't UTF-8 were read as {label} ({count}) kolejne nazwy spoza UTF-8 odczytano jako {label} ({count}) @msg gradient “{name}” isn't defined in the file: a plain colour stands in for it gradient „{name}” nie jest zdefiniowany w pliku: zastąpiono go jednolitym kolorem @msg an image VectorCraft can't read was left out pominięto obraz, którego VectorCraft nie potrafi odczytać -@msg graphs come in as plain art, without their data or settings wykresy są wczytywane jako zwykła grafika, bez ich danych i ustawień +@msg graphs come in as plain art, without their data or settings wykresy są wczytywane jako zwykłe elementy kompozycji, bez ich danych i ustawień @msg an image whose data is cut short was left out pominięto obraz z uciętymi danymi @msg an embedded image of {_1} × {_2} pixels was reduced to {_3} × {_4} pixels to keep the layers osadzony obraz o wymiarach {_1} × {_2} pikseli zmniejszono do {_3} × {_4} pikseli, aby zachować warstwy @msg linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel połączone obrazy pokazują zapisany w pliku podgląd niskiej rozdzielczości, dopóki ich pliki nie zostaną znalezione: połącz je ponownie w panelu Łącza @@ -5793,7 +5817,7 @@ variable-list-end {0}, {1} {0} i {1} @msg every numbered name for {name} is taken in the document's folder wszystkie numerowane nazwy dla {name} są zajęte w folderze dokumentu @msg No linked files to look for Brak połączonych plików do wyszukania @msg The link is inside a symbol, graph design, pattern or opacity mask and has no place on the canvas Łącze znajduje się w symbolu, wzorze wykresu, wzorku lub masce krycia i nie ma miejsca na obszarze roboczym -@msg the art of a graph design in a graph series is drawn again from the design: edit the design to change it grafika wzoru wykresu w serii danych wykresu jest rysowana od nowa na podstawie wzoru: aby ją zmienić, edytuj wzór +@msg the art of a graph design in a graph series is drawn again from the design: edit the design to change it kompozycja wzoru wykresu w serii danych wykresu jest rysowana od nowa na podstawie wzoru: aby ją zmienić, edytuj wzór @msg `id` is the step reference {r}, which only `run` and `command_batch` resolve `id` to odwołanie do kroku {r}, które rozwiązują tylko `run` i `command_batch` @msg `ids` must be an array of object ids, not {v} `ids` musi być tablicą identyfikatorów obiektów, nie {v} @msg `colors` must be an array of colors, not {v} `colors` musi być tablicą kolorów, nie {v} @@ -5816,6 +5840,7 @@ variable-list-end {0}, {1} {0} i {1} @msg a linked JavaScript file is outside the read roots połączony plik JavaScript jest poza katalogami głównymi odczytu @msg a linked image file is outside the read roots połączony plik obrazu jest poza katalogami głównymi odczytu @msg a linked file's export folder is outside the read roots folder eksportu połączonego pliku jest poza katalogami głównymi odczytu +@msg a linked file's editing data can't be read to check it against the read roots nie można odczytać danych edycji połączonego pliku, aby sprawdzić je względem katalogów głównych odczytu @msg automation path rejected: outside the write root {root}: {path} odrzucono ścieżkę automatyzacji: poza katalogiem głównym zapisu {root}: {path} @msg automation path rejected: outside the write roots {roots}: {path} odrzucono ścieżkę automatyzacji: poza katalogami głównymi zapisu {roots}: {path} @msg automation path rejected: path is empty odrzucono ścieżkę automatyzacji: ścieżka jest pusta @@ -6249,6 +6274,7 @@ mark-style Japanese Japońskie Cove Wklęsłe Depth Głębokość Front Przód + Side Bok Isometric Bottom Izometryczny dół Isometric Left Izometryczny lewy Isometric Right Izometryczny prawy @@ -6321,11 +6347,11 @@ mark-style Japanese Japońskie @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 {_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 tego rysunku: jego 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}”: rysunek symbolu jest niedostępny -@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ą rysunek +@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ę @msg {_1} takes at most {MAX_MEMBERS} objects {_1} przyjmuje najwyżej {MAX_MEMBERS} obiektów -@msg {_1} can't build solids from art nested more than {MAX_DEPTH} levels deep {_1} nie może utworzyć brył z rysunku zagnieżdżonego na więcej niż {MAX_DEPTH} poziomach +@msg {_1} can't build solids from art nested more than {MAX_DEPTH} levels deep {_1} nie może utworzyć brył z kompozycji zagnieżdżonej na więcej niż {MAX_DEPTH} poziomach @msg Revolve paint is too complex for this surface; reduce Segments or simplify the gradient Farba efektu Obrót jest zbyt złożona dla tej powierzchni; zmniejsz Segmenty lub uprość gradient @msg Revolve edge must be left or right Obrót: edge musi mieć wartość left lub right @msg Revolve cap must be a boolean Obrót: cap musi być wartością logiczną @@ -6343,22 +6369,22 @@ mark-style Japanese Japońskie @msg each of `{GRAPHICS}` must be an object każdy element `{GRAPHICS}` musi być obiektem @msg `{GRAPHICS}` entries take symbol, face, x, y, scale and rotation, not `{k}` elementy `{GRAPHICS}` przyjmują symbol, face, x, y, scale i rotation, a nie `{k}` @msg each of `{GRAPHICS}` needs `symbol`, the name of a symbol każdy element `{GRAPHICS}` wymaga `symbol`, nazwy symbolu -@msg `{GRAPHICS}` face must be front or back face w `{GRAPHICS}` musi mieć wartość front lub back +@msg `{GRAPHICS}` face must be front, back or side face w `{GRAPHICS}` musi mieć wartość front, back lub side @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} {key} w `{GRAPHICS}` musi być liczbą od {lo} do {hi} @msg `{GRAPHICS}` must be an array `{GRAPHICS}` musi być tablicą @msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types Grafiki są nakładane na obiekty typu Płaszczyzna, Wyciągnięcie, Obrót i Nadmuchanie @msg Revolve maps graphics onto its side: map them onto the front Obrót nakłada grafiki na swoją powierzchnię boczną: umieść je na przedniej stronie @msg object {_1}: Inflate's back takes graphics with Both sides and Cap on obiekt {_1}: tył Nadmuchania przyjmuje grafiki tylko przy włączonych opcjach Obie strony i Zakończenie -@msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments Grafiki są zbyt złożone dla tej powierzchni: uprość rysunki symboli lub zmniejsz Segmenty +@msg The graphics are too complex for this surface: simplify the symbols' art or reduce Segments Grafiki są zbyt złożone dla tej powierzchni: uprość kompozycje symboli lub zmniejsz Segmenty @msg `{GRAPHICS}` takes at most {MAX_GRAPHICS} graphics `{GRAPHICS}` przyjmuje najwyżej {MAX_GRAPHICS} grafik @msg A plane has one face: map its graphics onto the front Płaszczyzna ma jedną stronę: umieść jej grafiki na przedniej stronie -@msg The graphics are too complex: simplify the symbols' art Grafiki są zbyt złożone: uprość rysunki symboli -@msg A graphic's art may be nested at most {MAX_LEVELS} levels deep: simplify the symbol's art Rysunek grafiki może być zagnieżdżony najwyżej na {MAX_LEVELS} poziomach: uprość rysunek symbolu -@msg A graphic's art may nest symbols at most {MAX_NESTING} levels deep: simplify the symbol's art Rysunek grafiki może zagnieżdżać symbole najwyżej na {MAX_NESTING} poziomach: uprość rysunek symbolu -@msg A graphic's art holds too many objects: simplify the symbol's art Rysunek grafiki zawiera zbyt wiele obiektów: uprość rysunek symbolu -@msg A graphic draws at most {MAX_PIECES} fills and strokes: simplify the symbol's art Grafika rysuje najwyżej {MAX_PIECES} wypełnień i obrysów: uprość rysunek symbolu +@msg The graphics are too complex: simplify the symbols' art Grafiki są zbyt złożone: uprość kompozycje symboli +@msg A graphic's art may be nested at most {MAX_LEVELS} levels deep: simplify the symbol's art Kompozycja grafiki może być zagnieżdżona najwyżej na {MAX_LEVELS} poziomach: uprość kompozycję symbolu +@msg A graphic's art may nest symbols at most {MAX_NESTING} levels deep: simplify the symbol's art Kompozycja grafiki może zagnieżdżać symbole najwyżej na {MAX_NESTING} poziomach: uprość kompozycję symbolu +@msg A graphic's art holds too many objects: simplify the symbol's art Kompozycja grafiki zawiera zbyt wiele obiektów: uprość kompozycję symbolu +@msg A graphic draws at most {MAX_PIECES} fills and strokes: simplify the symbol's art Grafika rysuje najwyżej {MAX_PIECES} wypełnień i obrysów: uprość kompozycję symbolu @msg `surface` must be one of {_1} `surface` musi mieć jedną z wartości: {_1} -@msg {label} draws the source art for this object instead of its 3D surface {label} rysuje dla tego obiektu rysunek źródłowy zamiast jego powierzchni 3D +@msg {label} draws the source art for this object instead of its 3D surface {label} rysuje dla tego obiektu kompozycję źródłową zamiast jego powierzchni 3D @msg {label} draws no faces for this object {label} nie rysuje żadnych ścian dla tego obiektu @msg the wireframe has more than {MAX_WIRE_EDGES} edges model szkieletowy ma więcej niż {MAX_WIRE_EDGES} krawędzi @msg The 3D surface is too complex; simplify the shape Powierzchnia 3D jest zbyt złożona; uprość kształt @@ -6613,8 +6639,8 @@ mark-style Japanese Japońskie @msg {id} opens another app: only the person at the keyboard can run it {id} otwiera inną aplikację: uruchomić to polecenie może tylko osoba przy klawiaturze @msg “{name}” is not a file „{name}” nie jest plikiem Enable Guides for 9-Slice Scaling Włącz linie pomocnicze skalowania 9-slice -@msg a mask has more than one art block maska ma więcej niż jeden blok grafiki -@msg mask art ends outside a mask dictionary grafika maski kończy się poza słownikiem maski +@msg a mask has more than one art block maska ma więcej niż jeden blok kompozycji +@msg mask art ends outside a mask dictionary kompozycja maski kończy się poza słownikiem maski @msg cancelled; nothing was changed anulowano; nic nie zostało zmienione @msg a linked image can't become a gradient mesh: embed it first połączony obraz nie może stać się siatką gradientu: najpierw go osadź @msg the image has no usable size or position obraz nie ma użytecznego rozmiaru ani położenia @@ -6673,7 +6699,7 @@ mark-style Japanese Japońskie Choose a filter Wybierz filtr Effect Gallery Galeria efektów Filters Filtry - Select artwork to apply effects Wybierz grafikę, aby zastosować efekty + Select artwork to apply effects Wybierz kompozycję, aby zastosować efekty @msg the file's variable bindings weren't all read (bindings skipped: {_1}): those objects aren't bound to their variables nie wszystkie powiązania zmiennych pliku zostały wczytane (pominięte powiązania: {_1}): te obiekty nie są powiązane ze swoimi zmiennymi @msg the file's variable library was partly read (entries skipped: {_1}): the Variables panel lists the rest biblioteka zmiennych pliku została wczytana tylko częściowo (pominięte wpisy: {_1}): panel Zmienne wyświetla resztę @msg the file's variable library couldn't be read: the Variables panel doesn't list it nie udało się wczytać biblioteki zmiennych pliku: panel Zmienne jej nie wyświetla @@ -7110,7 +7136,7 @@ axis Y Axis Oś Y Polar Grid Tool Options Opcje narzędzia Siatka biegunowa Fill Line Wypełnij odcinek Pathfinder Options Opcje odnajdywania ścieżek - Divide and Outline Will Remove Unpainted Artwork Podziel i Kontur usuwają niepomalowaną grafikę + Divide and Outline Will Remove Unpainted Artwork Podziel i Kontur usuwają niepomalowaną kompozycję @msg precision must be from 0.001 to 10 pt precision musi wynosić od 0,001 do 10 pt @msg `pathfinder` must be an object `pathfinder` musi być obiektem Add to Brushes Dodaj do pędzli @@ -7229,7 +7255,7 @@ anchor Points: Punkty: @msg select two open path ends, or two open paths, to average and join zaznacz dwa końce otwartych ścieżek lub dwie otwarte ścieżki do uśrednienia i połączenia # Artwork Cleanup add-on (Object › Plug-ins › Artwork Cleanup): its panel, tools, issue kinds and messages. - Artwork Cleanup Porządkowanie grafiki + Artwork Cleanup Porządkowanie kompozycji Simplify Anchors (Keep Shape)… Uprość punkty kontrolne (zachowaj kształt)… Health Check Kontrola stanu Show Issue Pokaż problem @@ -7251,7 +7277,7 @@ anchor Points: Punkty: Empty Text Paths Puste ścieżki tekstowe Zero-Opacity Objects Obiekty o zerowym kryciu Duplicate Objects Zduplikowane obiekty - Off-Artboard Art Grafika poza obszarami kompozycji + Off-Artboard Art Kompozycja poza obszarami kompozycji Duplicate Anchors Zduplikowane punkty kontrolne Tiny Handles Bardzo krótkie uchwyty Collinear Anchors Współliniowe punkty kontrolne @@ -7568,9 +7594,9 @@ breakText Glyphs Glify Dash 5 Kreska 5 Gap 5 Odstęp 5 -@msg {_1}: they came in as the page's art {_1}: zaimportowano je jako grafikę strony -@msg warped text objects that came in as drawn art, not as editable type: {_1} wypaczone obiekty tekstowe zaimportowane jako grafika, a nie jako edytowalny tekst: {_1} -@msg objects that drew differently from the file's own page came in as its art: {_1} obiekty rysowane inaczej niż własna strona pliku zaimportowano jako grafikę strony: {_1} +@msg {_1}: they came in as the page's art {_1}: zaimportowano je jako elementy kompozycji strony +@msg warped text objects that came in as drawn art, not as editable type: {_1} wypaczone obiekty tekstowe zaimportowane jako elementy kompozycji, a nie jako edytowalny tekst: {_1} +@msg objects that drew differently from the file's own page came in as its art: {_1} obiekty rysowane inaczej niż własna strona pliku zaimportowano jako elementy kompozycji strony: {_1} @msg You must choose a side pattern. Musisz wybrać wzór boczny. @msg invalid pattern tile choice nieprawidłowy wybór kafelka wzoru @@ -7608,6 +7634,14 @@ breakText Glyphs Glify Remove Gaps Usuń odstępy @msg that makes too many pieces (at most 100000): make the dashes longer to daje za dużo części (najwyżej 100000): wydłuż kreski @msg select paths, or segments, to divide zaznacz ścieżki lub segmenty do podzielenia +# Path Precision Tools add-on: Smooth Bridge. + Smooth Bridge… Gładki most… + Smooth Bridge Gładki most + Keep Originals Zachowaj oryginały +@msg select two circles to bridge zaznacz dwa okręgi do połączenia +@msg one circle is inside the other jeden okrąg jest wewnątrz drugiego +@msg the circles are too far apart for this radius: raise the radius okręgi są zbyt daleko od siebie dla tego promienia: zwiększ promień +@msg the circles are too far apart for this radius okręgi są zbyt daleko od siebie dla tego promienia # Path Precision Tools add-on: Common Tangents. Common Tangents… Wspólne styczne… Common Tangents Wspólne styczne @@ -7692,7 +7726,7 @@ breakText Glyphs Glify @msg `{name}` is a static symbol: set its Symbol Type to Dynamic first `{name}` jest symbolem statycznym: najpierw ustaw jego typ symbolu na Dynamiczny @msg Only the fill, stroke, opacity and blend of a path, compound path or type selected in a symbol instance can change W ścieżce, ścieżce złożonej lub tekście zaznaczonym w wystąpieniu symbolu można zmienić tylko wypełnienie, obrys, krycie i tryb mieszania @msg path must be a list of child indices path musi być listą indeksów elementów podrzędnych -@msg no object at path {shown} in the symbol's art brak obiektu w ścieżce {shown} w grafice symbolu +@msg no object at path {shown} in the symbol's art brak obiektu w ścieżce {shown} w kompozycji symbolu @msg give fill, stroke, opacity and/or blend podaj fill, stroke, opacity i/lub blend @msg {key} cannot be set on a guide nie można ustawić {key} dla linii pomocniczej @msg {key} cannot be set on a blend nie można ustawić {key} dla przejścia @@ -7748,7 +7782,7 @@ breakText Glyphs Glify Release Type on a Path Uwolnij tekst na ścieżce Text and Path Tekst i ścieżka Path Only Tylko ścieżka -@msg The art is too large to copy as a picture: other apps get no PNG of it Grafika jest zbyt duża, aby skopiować ją jako obraz: inne aplikacje nie otrzymają jej w formacie PNG +@msg The art is too large to copy as a picture: other apps get no PNG of it Kompozycja jest zbyt duża, aby skopiować ją jako obraz: inne aplikacje nie otrzymają jej w formacie PNG # Selection Tools add-on: Select by Artboards (Object › Plug-ins › Selection Tools, #5548). Select by Artboards Zaznacz według obszarów kompozycji @@ -7926,9 +7960,9 @@ breakText Glyphs Glify Stencil Bridges Mostki szablonu Shortest Crossing Najkrótsze przejście Direction Kierunek -@msg The selected art has no islands to bridge Zaznaczona grafika nie ma wysp do połączenia -@msg No bridge of this width fits across the selected art Żaden mostek o tej szerokości nie mieści się w zaznaczonej grafice -@msg Some islands could not be joined to the area around the art Niektórych wysp nie udało się połączyć z obszarem wokół grafiki +@msg The selected art has no islands to bridge Zaznaczona kompozycja nie ma wysp do połączenia +@msg No bridge of this width fits across the selected art Żaden mostek o tej szerokości nie mieści się w zaznaczonej kompozycji +@msg Some islands could not be joined to the area around the art Niektórych wysp nie udało się połączyć z obszarem wokół kompozycji @msg `width` must be from {lo} to {hi} pt `width` musi mieścić się w zakresie od {lo} do {hi} pt @msg `angle` must be from -180 to 180 degrees `angle` musi mieścić się w zakresie od -180 do 180 stopni @msg `roundness` must be from 0 to 100% `roundness` musi mieścić się w zakresie od 0 do 100% @@ -7971,11 +8005,11 @@ breakText Glyphs Glify @msg Object.{function} was given a value that is not an object Object.{function} otrzymało wartość, która nie jest obiektem @msg QName.prototype.toString needs a QName QName.prototype.toString wymaga obiektu QName @msg RegExp.prototype.{name} was called on a value that is not a RegExp object RegExp.prototype.{name} wywołano na wartości, która nie jest obiektem RegExp -@msg Stencil Bridges: the selected art is too large or too detailed to bridge Mostki szablonu: zaznaczona grafika jest zbyt duża lub zbyt szczegółowa, aby utworzyć mostki +@msg Stencil Bridges: the selected art is too large or too detailed to bridge Mostki szablonu: zaznaczona kompozycja jest zbyt duża lub zbyt szczegółowa, aby utworzyć mostki @msg String.prototype.toString was called on a value that is not a string String.prototype.toString wywołano na wartości, która nie jest ciągiem znaków @msg The {name} profile could not be read, so the new document has the default settings: {reason} Nie udało się odczytać profilu {name}, więc nowy dokument ma ustawienia domyślne: {reason} @msg Trap: more than {_1} pairs of objects lie close enough to trap, or too many objects share a horizontal range; trap fewer objects at a time Zalewka: ponad {_1} par obiektów leży na tyle blisko siebie, że wymaga zalewki, albo zbyt wiele obiektów ma wspólny zakres poziomy; stosuj zalewkę do mniejszej liczby obiektów naraz -@msg Weed Box and Lines: no weeding line fits outside the art, and the weed box is off Ramka i linie do wybierania: żadna linia do wybierania nie mieści się poza grafiką, a ramka do wybierania jest wyłączona +@msg Weed Box and Lines: no weeding line fits outside the art, and the weed box is off Ramka i linie do wybierania: żadna linia do wybierania nie mieści się poza kompozycją, a ramka do wybierania jest wyłączona @msg \\ at end of pattern \\ na końcu wzorca @msg `alignOn` cannot be empty `alignOn` nie może być puste @msg `alignOn` must be a string `alignOn` musi być ciągiem znaków @@ -7984,6 +8018,14 @@ breakText Glyphs Glify @msg `answers` has more than {MAX_ANSWERS} answers `answers` zawiera więcej niż {MAX_ANSWERS} odpowiedzi @msg `answers` is larger than 1 MiB `answers` ma rozmiar większy niż 1 MiB @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` służy tylko do uruchomienia, w którym nie ma kogo zapytać: w aplikacji na każde okno dialogowe odpowiada użytkownik +@msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` musi być liczbą całkowitą od 1 do {_1} +@msg `args{place}` is nested more than 64 levels deep `args{place}` jest zagnieżdżone głębiej niż na 64 poziomy +@msg `args` must be an object `args` musi być obiektem +@msg `args` is larger than 1 MiB `args` ma rozmiar większy niż 1 MiB +@msg `path` is empty `path` jest puste +@msg `installed` takes a `path`, not a `source` `installed` przyjmuje `path`, a nie `source` +@msg `path` must name a .js or .jsx file `path` musi wskazywać plik .js lub .jsx +@msg give exactly one of `path` and `source` podaj dokładnie jedno z: `path` i `source` @msg `answers` must be a list of answers `answers` musi być listą odpowiedzi @msg `artboard` must be the index of an artboard of the document `artboard` musi być indeksem obszaru kompozycji dokumentu @msg `artboardsAt` must be [x, y] `artboardsAt` musi mieć postać [x, y] @@ -8173,8 +8215,8 @@ breakText Glyphs Glify @msg it is larger than {MAX_DICTIONARY_FILE_BYTES} bytes ma rozmiar większy niż {MAX_DICTIONARY_FILE_BYTES} bajtów @msg it isn't a file to nie jest plik @msg it names {_1} plates, and at most {MAX_PLATES} are read wymienia {_1} płyt, a odczytywanych jest najwyżej {MAX_PLATES} -@msg its art is too long or too detailed for a head jego grafika jest zbyt długa lub zbyt szczegółowa na grot -@msg its art paints nothing jego grafika niczego nie maluje +@msg its art is too long or too detailed for a head jego kompozycja jest zbyt długa lub zbyt szczegółowa na grot +@msg its art paints nothing jego kompozycja niczego nie maluje @msg its image is too large to read jego obraz jest zbyt duży do odczytania @msg its plates are too large: more than {MAX_SAMPLES} pixels together jego płyty są zbyt duże: łącznie ponad {MAX_SAMPLES} pikseli @msg its plates are too large: {_1} plates of {w} × {h} pixels jego płyty są zbyt duże: {_1} płyt o wymiarach {w} × {h} pikseli @@ -8224,7 +8266,7 @@ breakText Glyphs Glify @msg operand too large operand jest zbyt duży @msg order is a whole number from 0 to {others}, not `{v}` order to liczba całkowita od 0 do {others}, a nie `{v}` @msg path chunks must share their boundary point fragmenty ścieżki muszą mieć wspólny punkt graniczny -@msg pdfCompatible: false needs the artboards to keep the editable artwork when useArtboards is false pdfCompatible: false wymaga obszarów kompozycji, aby zachować edytowalną grafikę, gdy useArtboards ma wartość false +@msg pdfCompatible: false needs the artboards to keep the editable artwork when useArtboards is false pdfCompatible: false wymaga obszarów kompozycji, aby zachować edytowalną kompozycję, gdy useArtboards ma wartość false @msg point x must be a number współrzędna x punktu musi być liczbą @msg point y must be a number współrzędna y punktu musi być liczbą @msg points must be [x,y] pairs points musi zawierać pary [x,y] @@ -8237,7 +8279,7 @@ breakText Glyphs Glify @msg select an object with a 3D effect zaznacz obiekt z efektem 3D @msg select an object with a 3D effect, or give its id in ids zaznacz obiekt z efektem 3D albo podaj jego identyfikator w ids @msg select one layer, group or object to rename zaznacz jedną warstwę, grupę lub obiekt, aby zmienić nazwę -@msg select the art to weed zaznacz grafikę do wybierania +@msg select the art to weed zaznacz kompozycję do wybierania @msg select the banner, or mark every artboard zaznacz baner albo oznacz każdy obszar kompozycji @msg select type on a path or area type zaznacz tekst na ścieżce lub tekst akapitowy @msg side is left or right, not `{v}` side ma wartość left lub right, a nie `{v}` @@ -8264,7 +8306,7 @@ breakText Glyphs Glify @msg the XPath prefix {shown} is not bound to a namespace prefiks XPath {shown} nie jest powiązany z przestrzenią nazw @msg the XPath variable ${shown} is not bound zmienna XPath ${shown} nie jest powiązana @msg the argument list is not an object lista argumentów nie jest obiektem -@msg the artwork is too large for EPS: what follows 256 MB of PostScript was left out grafika jest zbyt duża dla formatu EPS: pominięto wszystko po 256 MB kodu PostScript +@msg the artwork is too large for EPS: what follows 256 MB of PostScript was left out kompozycja jest zbyt duża dla formatu EPS: pominięto wszystko po 256 MB kodu PostScript @msg the banner has no width or height baner nie ma szerokości lub wysokości @msg the bitmaps hold more pixels than one file may bitmapy zawierają więcej pikseli, niż może mieścić jeden plik @msg the code runs past its last instruction kod wykracza poza swoją ostatnią instrukcję @@ -8298,8 +8340,8 @@ breakText Glyphs Glify @msg the rectangle or line reaches too many paths to check prostokąt lub linia sięga zbyt wielu ścieżek, aby je sprawdzić @msg the right side of 'in' is not an object prawa strona operatora 'in' nie jest obiektem @msg the right side of 'instanceof' is not a function prawa strona operatora 'instanceof' nie jest funkcją -@msg the selected art is nested more than {MAX_DEPTH} levels deep zaznaczona grafika jest zagnieżdżona głębiej niż na {MAX_DEPTH} poziomów -@msg the selected art is too large to measure zaznaczona grafika jest zbyt duża, aby ją zmierzyć +@msg the selected art is nested more than {MAX_DEPTH} levels deep zaznaczona kompozycja jest zagnieżdżona głębiej niż na {MAX_DEPTH} poziomów +@msg the selected art is too large to measure zaznaczona kompozycja jest zbyt duża, aby ją zmierzyć @msg the selection has no outlines to weed around zaznaczenie nie ma konturów, wokół których można wybierać @msg the spacing makes more than {MAX_GROMMETS} grommets odstęp daje więcej niż {MAX_GROMMETS} oczek @msg the value bind was called on is not a function wartość, na której wywołano bind, nie jest funkcją @@ -8308,7 +8350,7 @@ breakText Glyphs Glify @msg the value is not a valid XML name wartość nie jest prawidłową nazwą XML @msg the value is not an XML attribute name wartość nie jest nazwą atrybutu XML @msg the value is not an XML name wartość nie jest nazwą XML -@msg the weeding lines cross the art's outlines too many times to measure; use fewer lines linie do wybierania przecinają kontury grafiki zbyt wiele razy, aby to zmierzyć; użyj mniejszej liczby linii +@msg the weeding lines cross the art's outlines too many times to measure; use fewer lines linie do wybierania przecinają kontury kompozycji zbyt wiele razy, aby to zmierzyć; użyj mniejszej liczby linii @msg the weeding lines pass too close to too many outline segments to measure; use fewer lines or a smaller gap linie do wybierania przebiegają zbyt blisko zbyt wielu segmentów konturu, aby to zmierzyć; użyj mniejszej liczby linii lub mniejszego odstępu @msg the weeding lines would be more than {max_pieces} pieces linie do wybierania składałyby się z więcej niż {max_pieces} części @msg the {_1} plate lies outside the file płyta {_1} leży poza plikiem @@ -8378,7 +8420,7 @@ breakText Glyphs Glify @msg DXF scale must be a positive number up to {_1}, not {scale} Skala DXF musi być liczbą dodatnią nie większą niż {_1}, a nie {scale} @msg DXF {field} `{s}`: {allowed} DXF {field} `{s}`: {allowed} @msg Draw Inside needs exactly one selected path, compound path or text Rysuj wewnątrz wymaga dokładnie jednej zaznaczonej ścieżki, ścieżki złożonej lub tekstu -@msg EPS Save writes all artwork: use document.export for selected-only EPS Zapis EPS obejmuje całą grafikę: użyj document.export, aby zapisać w EPS tylko zaznaczenie +@msg EPS Save writes all artwork: use document.export for selected-only EPS Zapis EPS obejmuje całą kompozycję: użyj document.export, aby zapisać w EPS tylko zaznaczenie @msg EPS flattener: {e} Spłaszczanie EPS: {e} @msg EPS options: {e} Opcje EPS: {e} @msg EPS {field} `{s}`: {allowed} EPS {field} `{s}`: {allowed} @@ -8567,7 +8609,7 @@ breakText Glyphs Glify @msg `{_1}` is built in and always listed `{_1}` jest wbudowane i zawsze widoczne na liście @msg `{_1}` is not a font file the last text.findFontFiles search found `{_1}` nie jest plikiem czcionki znalezionym przez ostatnie wyszukiwanie text.findFontFiles @msg `{_1}` would be overwritten by the package: choose a different folder or name `{_1}` zostałoby nadpisane przez pakiet: wybierz inny folder lub inną nazwę -@msg `{file}` has no art to place `{file}` nie zawiera grafiki do umieszczenia +@msg `{file}` has no art to place `{file}` nie zawiera kompozycji do umieszczenia @msg `{file}` is over {_1} MB `{file}` ma ponad {_1} MB @msg `{f}` belongs to a VectorCraft that is running `{f}` należy do uruchomionego programu VectorCraft @msg `{f}` is the copy of a document open now `{f}` to kopia otwartego teraz dokumentu @@ -8608,7 +8650,7 @@ breakText Glyphs Glify @msg `{name}` can't be edited this way `{name}` nie można edytować w ten sposób @msg `{name}` can't be renamed nazwy `{name}` nie można zmienić @msg `{name}` can't name a folder `{name}` nie może być nazwą folderu -@msg `{name}` has no art to place `{name}` nie zawiera grafiki do umieszczenia +@msg `{name}` has no art to place `{name}` nie zawiera kompozycji do umieszczenia @msg `{name}` has no text to place `{name}` nie zawiera tekstu do umieszczenia @msg `{name}` in the Word document is not UTF-8 or UTF-16 text `{name}` w dokumencie Word nie jest tekstem UTF-8 ani UTF-16 @msg `{name}` in the Word document is not well-formed XML: {e} `{name}` w dokumencie Word nie jest poprawnie sformułowanym kodem XML: {e} @@ -8720,7 +8762,7 @@ breakText Glyphs Glify @msg artboardLayout.spacing must be 0–{MAX_SPACING} pt artboardLayout.spacing musi wynosić 0–{MAX_SPACING} pt @msg artboards must be a non-empty list artboards musi być niepustą listą @msg artboards must be a number artboards musi być liczbą -@msg asset `{_1}` has no art to export zasób `{_1}` nie zawiera grafiki do wyeksportowania +@msg asset `{_1}` has no art to export zasób `{_1}` nie zawiera kompozycji do wyeksportowania @msg at most {MAX_KEYWORDS} keywords najwyżej {MAX_KEYWORDS} słów kluczowych @msg at most {MAX_MATCHES} matches are kept zachowywanych jest najwyżej {MAX_MATCHES} dopasowań @msg at most {MAX_POINTS} points najwyżej {MAX_POINTS} punktów @@ -8995,7 +9037,7 @@ breakText Glyphs Glify @msg kind must be 1, 2 or 3, or give a preset `name` (see perspective.presets.list) kind musi wynosić 1, 2 lub 3, albo podaj `name` ustawienia (patrz perspective.presets.list) @msg kind must be graphic, fillColor, strokeColor, fillGradient, strokeGradient, fillPattern, strokePattern, charStyle or paraStyle kind musi mieć wartość graphic, fillColor, strokeColor, fillGradient, strokeGradient, fillPattern, strokePattern, charStyle lub paraStyle @msg knockout must be "on", "off", "neutral" or a bool, not {v} knockout musi mieć wartość "on", "off", "neutral" lub wartość logiczną, a nie {v} -@msg layer `{name}` has no art to export warstwa `{name}` nie zawiera grafiki do wyeksportowania +@msg layer `{name}` has no art to export warstwa `{name}` nie zawiera kompozycji do wyeksportowania @msg layer must name a layer or sublayer layer musi wskazywać warstwę lub podwarstwę @msg layers can't be intertwined: select the objects in them warstw nie można przeplatać: zaznacz znajdujące się w nich obiekty @msg layers go only at the top level or in layers, objects in layers and groups warstwy mogą się znajdować tylko na najwyższym poziomie lub w warstwach, a obiekty w warstwach i grupach @@ -9114,7 +9156,7 @@ breakText Glyphs Glify @msg no asset {id} brak zasobu {id} @msg no asset {id} (see assets.list) brak zasobu {id} (patrz assets.list) @msg no assets to export brak zasobów do wyeksportowania -@msg no assets yet: collect art for export first (assets.add) nie ma jeszcze zasobów: najpierw zbierz grafikę do eksportu (assets.add) +@msg no assets yet: collect art for export first (assets.add) nie ma jeszcze zasobów: najpierw zbierz kompozycję do eksportu (assets.add) @msg no brush named `{n}` brak pędzla o nazwie `{n}` @msg no character at byte {start} brak znaku w bajcie {start} @msg no colour brak koloru @@ -9177,7 +9219,7 @@ breakText Glyphs Glify @msg no saved views brak zapisanych widoków @msg no series {i} brak serii {i} @msg no slice {n} in the image (see slice.list) brak plasterka {n} w obrazie (patrz slice.list) -@msg no source art brak grafiki źródłowej +@msg no source art brak kompozycji źródłowej @msg no stop {i} (the gradient has {n}) brak punktu koloru {i} (gradient ma {n}) @msg no style `{name}` brak stylu `{name}` @msg no such assets (see assets.list) brak takich zasobów (patrz assets.list) @@ -9237,10 +9279,10 @@ breakText Glyphs Glify @msg nothing to change: give dx, dy, hScale, vScale or rotation nie ma czego zmienić: podaj dx, dy, hScale, vScale lub rotation @msg nothing to crop nie ma czego kadrować @msg nothing to export nie ma czego eksportować -@msg nothing to export: the document has no visible art nie ma czego eksportować: dokument nie zawiera widocznej grafiki +@msg nothing to export: the document has no visible art nie ma czego eksportować: dokument nie zawiera widocznej kompozycji @msg nothing to mark nie ma czego oznaczać @msg nothing to print: every artboard picked is blank nie ma czego drukować: każdy wybrany obszar kompozycji jest pusty -@msg nothing to print: the document has no art that prints nie ma czego drukować: dokument nie zawiera grafiki przeznaczonej do druku +@msg nothing to print: the document has no art that prints nie ma czego drukować: dokument nie zawiera kompozycji przeznaczonej do druku @msg object is not a path obiekt nie jest ścieżką @msg object transparency cannot be sampled onto highlighted characters; disable Transparency in Eyedropper Options or select the whole object przezroczystości obiektu nie można próbkować na wyróżnione znaki; wyłącz Przezroczystość w Opcjach kroplomierza albo zaznacz cały obiekt @msg object {_1} can't be set as point type obiektu {_1} nie można ustawić jako tekstu punktowego @@ -9287,12 +9329,12 @@ breakText Glyphs Glify @msg overlap: {o} pt is half a tile or more overlap: {o} pt to co najmniej połowa kafelka @msg overlapping Shaper paths must be in the same layer or group nakładające się ścieżki narzędzia Kształtowanie muszą znajdować się w tej samej warstwie lub grupie @msg overlapping edits nakładające się edycje -@msg page art conflicts with image data for {key} grafika strony jest sprzeczna z danymi obrazu dla {key} -@msg page art conflicts with pattern {name} grafika strony jest sprzeczna z wzorkiem {name} -@msg page art conflicts with swatch {name} grafika strony jest sprzeczna z próbką {name} -@msg page art is missing image data for {key} w grafice strony brakuje danych obrazu dla {key} -@msg page art is missing pattern {name} w grafice strony brakuje wzorka {name} -@msg page art is missing swatch {name} w grafice strony brakuje próbki {name} +@msg page art conflicts with image data for {key} kompozycja strony jest sprzeczna z danymi obrazu dla {key} +@msg page art conflicts with pattern {name} kompozycja strony jest sprzeczna ze wzorkiem {name} +@msg page art conflicts with swatch {name} kompozycja strony jest sprzeczna z próbką {name} +@msg page art is missing image data for {key} w kompozycji strony brakuje danych obrazu dla {key} +@msg page art is missing pattern {name} w kompozycji strony brakuje wzorka {name} +@msg page art is missing swatch {name} w kompozycji strony brakuje próbki {name} @msg page must be a whole number from 1 page musi być liczbą całkowitą od 1 @msg page thumbnail: {e} miniatura strony: {e} @msg page {page} of the PDF has no objects strona {page} pliku PDF nie zawiera obiektów @@ -9306,7 +9348,7 @@ breakText Glyphs Glify @msg passwords can have up to {MAX_PASSWORD} bytes hasła mogą mieć najwyżej {MAX_PASSWORD} bajtów @msg path has no open end ścieżka nie ma otwartego końca @msg paths must be strings paths musi zawierać ciągi znaków -@msg pdfCompatible: false needs every artboard to keep the editable artwork pdfCompatible: false wymaga wszystkich obszarów kompozycji, aby zachować edytowalną grafikę +@msg pdfCompatible: false needs every artboard to keep the editable artwork pdfCompatible: false wymaga wszystkich obszarów kompozycji, aby zachować edytowalną kompozycję @msg pdfs `{m}`: single or multiple pdfs `{m}`: single lub multiple @msg pickColorFrom is "artwork" or "swatches", not {v} pickColorFrom ma wartość "artwork" lub "swatches", a nie {v} @msg pins and moved must be non-empty lists of the same length pins i moved muszą być niepustymi listami tej samej długości @@ -9387,9 +9429,9 @@ breakText Glyphs Glify @msg select area type (text in a frame) zaznacz tekst akapitowy (tekst w ramce) @msg select area type and closed paths (at least one area type object) zaznacz tekst akapitowy i ścieżki zamknięte (co najmniej jeden obiekt tekstu akapitowego) @msg select area type whose first line can fit its frame zaznacz tekst akapitowy, którego pierwszy wiersz mieści się w ramce -@msg select artwork to add its colours zaznacz grafikę, aby dodać jej kolory -@msg select artwork to make a group of its colours zaznacz grafikę, aby utworzyć grupę z jej kolorów -@msg select artwork to recolour, or give a colour `group` zaznacz grafikę do zmiany kolorów albo podaj `group` kolorów +@msg select artwork to add its colours zaznacz kompozycję, aby dodać jej kolory +@msg select artwork to make a group of its colours zaznacz kompozycję, aby utworzyć grupę z jej kolorów +@msg select artwork to recolour, or give a colour `group` zaznacz kompozycję do zmiany kolorów albo podaj `group` kolorów @msg select exactly two path ends to join zaznacz dokładnie dwa końce ścieżek do połączenia @msg select members of a compound shape zaznacz elementy kształtu złożonego @msg select objects or give ids zaznacz obiekty albo podaj ids @@ -9402,11 +9444,11 @@ breakText Glyphs Glify @msg select something to export zaznacz coś do wyeksportowania @msg select something to export (or turn off selectedOnly) zaznacz coś do wyeksportowania (albo wyłącz selectedOnly) @msg select text to redefine the style from zaznacz tekst, na podstawie którego styl ma zostać zdefiniowany ponownie -@msg select the art and, on top of it, the mask object zaznacz grafikę oraz leżący nad nią obiekt maski -@msg select the art for the design zaznacz grafikę dla wzoru -@msg select the art for the pattern tile zaznacz grafikę dla kafelka wzorka -@msg select the art to add first najpierw zaznacz grafikę do dodania -@msg select the art to collect (or give its ids) zaznacz grafikę do zebrania (albo podaj jej identyfikatory) +@msg select the art and, on top of it, the mask object zaznacz kompozycję oraz leżący nad nią obiekt maski +@msg select the art for the design zaznacz kompozycję dla wzoru +@msg select the art for the pattern tile zaznacz kompozycję dla kafelka wzorka +@msg select the art to add first najpierw zaznacz kompozycję do dodania +@msg select the art to collect (or give its ids) zaznacz kompozycję do zebrania (albo podaj jej identyfikatory) @msg select the content and a path on top zaznacz zawartość oraz leżącą nad nią ścieżkę @msg select the images to relink, or pass ids zaznacz obrazy do ponownego połączenia albo przekaż ids @msg select the images, or pass ids zaznacz obrazy albo przekaż ids @@ -9480,7 +9522,7 @@ breakText Glyphs Glify @msg the container of the listed objects is gone kontener wymienionych obiektów już nie istnieje @msg the copy `{user_id}` can't be read as a library kopii `{user_id}` nie można odczytać jako biblioteki @msg the copy would leave the canvas kopia wykroczyłaby poza płótno -@msg the cut cannot be made on this art: {e} na tej grafice nie można wykonać cięcia: {e} +@msg the cut cannot be made on this art: {e} na tej kompozycji nie można wykonać cięcia: {e} @msg the data isn't an EMF or WMF picture dane nie są ilustracją EMF ani WMF @msg the data isn't an EPS or PostScript picture dane nie są ilustracją EPS ani PostScript @msg the deferred paste is no longer available odroczone wklejanie nie jest już dostępne @@ -9515,7 +9557,7 @@ breakText Glyphs Glify @msg the image's transparency doesn't fit it przezroczystość obrazu do niego nie pasuje @msg the job would print more than {MAX_PAGES} pages zadanie wydrukowałoby ponad {MAX_PAGES} stron @msg the job would print more than {_1} pages zadanie wydrukowałoby ponad {_1} stron -@msg the layers hold no art to mask warstwy nie zawierają grafiki do zamaskowania +@msg the layers hold no art to mask warstwy nie zawierają kompozycji do zamaskowania @msg the layout moved układ uległ przesunięciu @msg the library has a group `{name}` already biblioteka ma już grupę `{name}` @msg the library has no group `{name}` biblioteka nie ma grupy `{name}` @@ -9530,7 +9572,7 @@ breakText Glyphs Glify @msg the open and permissions passwords must differ hasło otwarcia i hasło uprawnień muszą się różnić @msg the operand stack overflowed stos operandów został przepełniony @msg the page has no area strona nie ma powierzchni -@msg the page's type in an unread object's box isn't in its page art tekstu strony w polu nieodczytanego obiektu nie ma w grafice tej strony +@msg the page's type in an unread object's box isn't in its page art tekstu strony w polu nieodczytanego obiektu nie ma w kompozycji tej strony @msg the paint behind the proxy is not a gradient malowanie wskazywane przez wskaźnik wypełnienia lub obrysu nie jest gradientem @msg the parent must be a layer or sublayer elementem nadrzędnym musi być warstwa lub podwarstwa @msg the path can't be extended ścieżki nie można przedłużyć @@ -9543,10 +9585,10 @@ breakText Glyphs Glify @msg the program uses too much memory program zużywa zbyt dużo pamięci @msg the rectangle must have a width and a height prostokąt musi mieć szerokość i wysokość @msg the rectangle needs a size and must lie on the canvas prostokąt wymaga rozmiaru i musi leżeć na płótnie -@msg the selected art has no width zaznaczona grafika nie ma szerokości +@msg the selected art has no width zaznaczona kompozycja nie ma szerokości @msg the selection draws nothing zaznaczenie niczego nie rysuje @msg the selection has no area zaznaczenie nie ma powierzchni -@msg the selection has no art to export zaznaczenie nie zawiera grafiki do wyeksportowania +@msg the selection has no art to export zaznaczenie nie zawiera kompozycji do wyeksportowania @msg the selection has no bounds zaznaczenie nie ma granic @msg the selection has no graphic style zaznaczenie nie ma stylu graficznego @msg the slice would leave the canvas plasterek wykroczyłby poza płótno @@ -9765,7 +9807,7 @@ breakText Glyphs Glify @msg {std} files are CMYK, and the file would have colours in {_1} pliki {std} są w CMYK, a plik zawierałby kolory w {_1} @msg {std} files embed their fonts, and the file would have one that isn't pliki {std} osadzają swoje czcionki, a plik zawierałby czcionkę nieosadzoną @msg {target} is the file this document was read from, and reading it left things out ({what}): writing over it would lose them for good. Write another file instead, or pass acknowledgeLoss: true to replace it anyway {target} to plik, z którego odczytano ten dokument, a przy odczycie pominięto część zawartości ({what}): nadpisanie go spowodowałoby jej trwałą utratę. Zapisz zamiast tego inny plik albo przekaż acknowledgeLoss: true, aby mimo to go zastąpić -@msg {ty} brushes need selected art (or params.{k}) pędzle {ty} wymagają zaznaczonej grafiki (lub params.{k}) +@msg {ty} brushes need selected art (or params.{k}) pędzle {ty} wymagają zaznaczonej kompozycji (lub params.{k}) @msg {v} is not an asset id {v} nie jest identyfikatorem zasobu @msg {what} can't be intertwined {what} nie można przeplatać @msg {what} doesn't fit the paper with its bleed and marks {what} nie mieści się na papierze wraz ze spadem i znacznikami @@ -9813,7 +9855,7 @@ breakText Glyphs Glify @msg Targa depth {_1}: 16, 24 or 32 bits per pixel Głębia Targa {_1}: 16, 24 lub 32 bity na piksel @msg Targa encoding failed: the pixel buffer doesn't match the image size Kodowanie Targa nie powiodło się: bufor pikseli nie odpowiada rozmiarowi obrazu @msg The 3D projection is not finite Rzut 3D nie jest skończony -@msg The 3D shadow is too complex; turn Shadows off or simplify the art Cień 3D jest zbyt złożony; wyłącz Cienie lub uprość grafikę +@msg The 3D shadow is too complex; turn Shadows off or simplify the art Cień 3D jest zbyt złożony; wyłącz Cienie lub uprość kompozycję @msg The shape contains invalid coordinates Kształt zawiera nieprawidłowe współrzędne @msg Too many Revolve faces for visibility evaluation Zbyt wiele ścian efektu Obrót do obliczenia widoczności @msg VectorCraft reads at most {ASE_MAX_ENTRIES} colors and groups from a swatch exchange file, and this library has {entries} VectorCraft odczytuje z pliku wymiany próbek najwyżej {ASE_MAX_ENTRIES} kolorów i grup, a ta biblioteka ma ich {entries} diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 23abf0dd86..4aba908498 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -147,6 +147,7 @@ Add to Selection Adicionar à Seleção Add to Swatches Adicionar às Amostras Additional Plug-ins Folder Pasta Adicional de Plug-ins + Plug-in Instruction Budget Orçamento de Instruções de Plug-ins Additional Fonts Folder Pasta Adicional de Fontes Adjust Adjoining Width Points Ajustar Pontos de Largura Adjacentes Incoming Entrada @@ -730,6 +731,8 @@ antiAlias Sharp Nítido Delete Artboard Excluir Mesa de Trabalho Delete Artboards Excluir Mesas de Trabalho Delete Brush Excluir Pincel + Delete Color Excluir Cor + Restore Generated Table Restaurar Tabela Gerada Delete Character Style Excluir Estilo de Caractere Delete Empty Artboards Excluir Mesas de Trabalho Vazias Delete Freeform Point Excluir Ponto Livre @@ -796,6 +799,7 @@ antiAlias Sharp Nítido Direct Selection Tool Ferramenta Seleção Direta Direction Handles Alças de Direção Disable Auto Add/Delete Desativar Adicionar/Excluir Automático + Interpolate Control Points When Moving Anchors Interpolar Alças de Direção ao Mover Pontos de Ancoragem Disable Opacity Mask Desativar Máscara de Opacidade Discard Descartar Discard Empty Type Descartar Texto Vazio @@ -2261,6 +2265,7 @@ antiAlias Sharp Nítido Line Properties: Propriedades da Linha: Line Length: Comprimento da Linha: Line Angle: Ângulo da Linha: + Constrain Pie Angle Restringir Ângulo da Fatia Polygon Tool Ferramenta Polígono Portrait Retrato Portuguese Português @@ -2403,6 +2408,9 @@ digits Malayalam Malaiala Real World: Mundo Real: Real-time Drawing and Editing Desenho e Edição em Tempo Real Use Monitor Profile for Canvas Usar Perfil do Monitor para a Tela + Refresh Monitor Profile Atualizar Perfil do Monitor +@msg turn on Use Monitor Profile for Canvas first ative primeiro "Usar Perfil do Monitor para a Tela" +@msg this build doesn't read display profiles esta versão não lê perfis de monitor The canvas is drawn in sRGB. A tela é desenhada em sRGB. Canvas display profile: Perfil do monitor para a tela: The system matches the window to the display's colors. O sistema ajusta a janela às cores do monitor. @@ -2639,6 +2647,7 @@ digits Malayalam Malaiala The mouse wheel with Cmd/Ctrl held scrolls the canvas sideways. A roda do mouse com Cmd/Ctrl pressionado rola a tela para os lados. Dragging sideways on a numeric field's label changes the field's value. Arrastar para os lados sobre o rótulo de um campo numérico muda o valor do campo. A two-finger rotate gesture on a trackpad rotates the canvas view. Um gesto de rotação com dois dedos no trackpad gira a visualização da tela. + When you move anchor points, each curve with one moved end keeps its shape relative to its ends. Ao mover pontos de ancoragem, cada curva com uma extremidade movida mantém sua forma em relação às extremidades. Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Manter pressionado o atalho de uma ferramenta a escolhe até você soltar, e então a ferramenta anterior é escolhida de novo. Shows the bounding box while you move the selection or draw a shape. Mostra a caixa delimitadora enquanto você move a seleção ou desenha uma forma. Create Trim Marks draws Japanese-style marks instead of Roman ones. Criar Marcas de Corte desenha marcas no estilo japonês em vez de romanas. @@ -2915,6 +2924,9 @@ digits Malayalam Malaiala Search commands, tools, panels and effects… Pesquisar comandos, ferramentas, painéis e efeitos… No commands match Nenhum comando corresponde {pos} of {total}: {name} {pos} de {total}: {name} + No menu item Nenhum item de menu + Toolbar Barra de Ferramentas + {toolbar}, in the {tool} group {toolbar}, no grupo {tool} @plural {n} result|{n} results {n} resultado|{n} resultados @plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} de {n} resultado. Continue digitando para filtrá-los.|{shown} de {n} resultados. Continue digitando para filtrá-los. Recent Commands Comandos recentes @@ -3910,6 +3922,7 @@ font-technology Variable Variáveis Scatter: Dispersão: Rotation: Rotação: Rotation relative to: Rotação relativa a: + Hue Jitter: Variação de matiz: Brush Scale Options Opções de escala do pincel Scale Proportionately Dimensionar proporcionalmente Stretch to Fit Stroke Length Esticar para ajustar ao comprimento do traço @@ -4334,6 +4347,7 @@ axis Both Ambos @msg choose a folder to export to escolha uma pasta para exportar @msg choose a location for the package escolha um local para o pacote @msg clipboard is empty a área de transferência está vazia +@msg colorTable.deleted: at least one color has to stay in the color table colorTable.deleted: pelo menos uma cor deve permanecer na tabela de cores @msg colorTable.{what}: `{h}` is not a colour such as "#ff8800" colorTable.{what}: `{h}` não é uma cor como "#ff8800" @msg colorTable.{what}: at most {MAX_TABLE} colours colorTable.{what}: no máximo {MAX_TABLE} cores @msg command `{0}` is not available right now: {1} o comando `{0}` não está disponível agora: {1} @@ -4400,6 +4414,12 @@ axis Both Ambos @msg no PNG encoder sem codificador de PNG @msg no active document nenhum documento ativo @msg no active perspective plane nenhum plano de perspectiva ativo +@msg the perspective grid is hidden a grade de perspectiva está oculta +@msg Automatic Plane Positioning is off: turn on anchorPoint or gridlineIntersection (perspective.widget.options) O posicionamento automático do plano está desativado: ative anchorPoint ou gridlineIntersection (perspective.widget.options) +@msg anchorPoint must be true or false anchorPoint deve ser true ou false +@msg gridlineIntersection must be true or false gridlineIntersection deve ser true ou false +@msg tolerance must be 0 or more tolerance deve ser 0 ou mais +@msg give `at` or `clear`, not both informe `at` ou `clear`, não ambos @msg no anchor points selected nenhum ponto de ancoragem selecionado @msg `points` must be two or three [x, y] pairs of numbers `points` deve ter dois ou três pares de números [x, y] @msg direct-select two or three anchor points, or give `points` selecione diretamente dois ou três pontos de ancoragem ou informe `points` @@ -4869,6 +4889,8 @@ variable-list-end {0}, {1} {0} e {1} @msg Reload the page to go on (changes not saved yet may be lost). Recarregue a página para continuar (alterações ainda não salvas podem ser perdidas). @msg tool (a tool id) is required tool (um id de ferramenta) é obrigatório @msg {tool} isn't in a toolbar group of several tools {tool} não está em um grupo de barra de ferramentas com várias ferramentas +@msg Presentation Mode hides the toolbars: change the screen mode to show them o Modo de Apresentação oculta as barras de ferramentas: altere o modo de tela para mostrá-las +@msg Tab has hidden the toolbars: press Tab to show them Tab ocultou as barras de ferramentas: pressione Tab para mostrá-las @msg onto must name a panel floating in another group onto deve nomear um painel flutuante em outro grupo @msg below and above must name a panel floating in another group below e above devem nomear um painel flutuante em outro grupo @msg give only one of onto, below and above informe apenas um entre onto, below e above @@ -4948,6 +4970,7 @@ variable-list-end {0}, {1} {0} e {1} @msg a linked JavaScript file is outside the read roots um arquivo JavaScript vinculado está fora das raízes de leitura @msg a linked image file is outside the read roots um arquivo de imagem vinculado está fora das raízes de leitura @msg a linked file's export folder is outside the read roots a pasta de exportação de um arquivo vinculado está fora das raízes de leitura +@msg a linked file's editing data can't be read to check it against the read roots não é possível ler os dados de edição de um arquivo vinculado para verificá-los em relação às raízes de leitura @msg automation path rejected: outside the write root {root}: {path} caminho da automação rejeitado: fora da raiz de gravação {root}: {path} @msg automation path rejected: outside the write roots {roots}: {path} caminho da automação rejeitado: fora das raízes de gravação {roots}: {path} @msg automation path rejected: path is empty caminho da automação rejeitado: o caminho está vazio @@ -5430,6 +5453,7 @@ variable-list-end {0}, {1} {0} e {1} Name 40% Nome 40% Name* @ 66.67 % (RGB/Preview) Nome* @ 66.67 % (RGB/Visualização) Name* @ 66.67% (RGB/Preview) Nome* @ 66.67% (RGB/Visualização) + Roundness Arredondamento Roundness: Arredondamento: Fixed Fixo Pressure Pressão @@ -5705,6 +5729,7 @@ variable-list-end {0}, {1} {0} e {1} [Normal Paragraph Style] [Estilo de Parágrafo Normal] Joins Junções Axis Eixo + Axis Angle Ângulo do eixo Run Executar Run Script Executar script Stop Script Parar script @@ -6375,6 +6400,7 @@ mark-style Japanese Japonesas Cove Côncavo Depth Profundidade Front Frente + Side Lateral Isometric Bottom Isométrico Inferior Isometric Left Isométrico Esquerdo Isometric Right Isométrico Direito @@ -6469,7 +6495,7 @@ mark-style Japanese Japonesas @msg each of `{GRAPHICS}` must be an object cada item de `{GRAPHICS}` deve ser um objeto @msg `{GRAPHICS}` entries take symbol, face, x, y, scale and rotation, not `{k}` as entradas de `{GRAPHICS}` aceitam symbol, face, x, y, scale e rotation, não `{k}` @msg each of `{GRAPHICS}` needs `symbol`, the name of a symbol cada item de `{GRAPHICS}` precisa de `symbol`, o nome de um símbolo -@msg `{GRAPHICS}` face must be front or back face de `{GRAPHICS}` deve ser front ou back +@msg `{GRAPHICS}` face must be front, back or side face de `{GRAPHICS}` deve ser front, back ou side @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} {key} de `{GRAPHICS}` deve ser um número de {lo} a {hi} @msg `{GRAPHICS}` must be an array `{GRAPHICS}` deve ser uma matriz @msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types Os gráficos são mapeados nos tipos de objeto Plano, Extrusão, Revolver e Inflar @@ -7772,6 +7798,14 @@ breakText Glyphs Glifos Remove Gaps Remover distâncias @msg that makes too many pieces (at most 100000): make the dashes longer isso gera peças demais (no máximo 100000): aumente os traços @msg select paths, or segments, to divide selecione demarcadores ou segmentos para dividir +# Path Precision Tools add-on: Smooth Bridge. + Smooth Bridge… Ponte suave… + Smooth Bridge Ponte suave + Keep Originals Manter originais +@msg select two circles to bridge selecione dois círculos para unir +@msg one circle is inside the other um círculo está dentro do outro +@msg the circles are too far apart for this radius: raise the radius os círculos estão muito afastados para este raio: aumente o raio +@msg the circles are too far apart for this radius os círculos estão muito afastados para este raio # Path Precision Tools add-on: Common Tangents. Common Tangents… Tangentes comuns… Common Tangents Tangentes comuns @@ -8357,6 +8391,14 @@ swatch Yellow Green Verde-amarelado @msg `answers` has more than {MAX_ANSWERS} answers `answers` tem mais de {MAX_ANSWERS} respostas @msg `answers` is larger than 1 MiB `answers` tem mais de 1 MiB @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` é só para uma execução sem ninguém a quem perguntar: no app, a pessoa responde a cada caixa de diálogo +@msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` deve ser um número inteiro de 1 a {_1} +@msg `args{place}` is nested more than 64 levels deep `args{place}` está aninhado em mais de 64 níveis +@msg `args` must be an object `args` deve ser um objeto +@msg `args` is larger than 1 MiB `args` tem mais de 1 MiB +@msg `path` is empty `path` está vazio +@msg `installed` takes a `path`, not a `source` `installed` aceita um `path`, não um `source` +@msg `path` must name a .js or .jsx file `path` deve indicar um arquivo .js ou .jsx +@msg give exactly one of `path` and `source` informe exatamente um de `path` e `source` @msg `answers` must be a list of answers `answers` deve ser uma lista de respostas @msg `artboard` must be the index of an artboard of the document `artboard` deve ser o índice de uma prancheta do documento @msg `artboardsAt` must be [x, y] `artboardsAt` deve ser [x, y] diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 735ae1f754..2e236f1827 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -139,6 +139,7 @@ Add to Swatches Добавить в образцы Add Used Colors Добавить использованные цвета Additional Plug-ins Folder Папка дополнительных модулей + Plug-in Instruction Budget Бюджет инструкций модулей Additional Fonts Folder Папка дополнительных шрифтов Adjust Adjoining Width Points Настроить смежные точки ширины Incoming Входящая @@ -814,6 +815,8 @@ font-technology Variable Вариативные Delete Artboard Удалить монтажную область Delete Artboards Удалить монтажные области Delete Brush Удалить кисть + Delete Color Удалить цвет + Restore Generated Table Восстановить созданную таблицу Delete Character Style Удалить стиль символа Delete Empty Artboards Удалить пустые монтажные области Delete Freeform Point Удалить произвольную точку @@ -882,6 +885,7 @@ font-technology Variable Вариативные Direct Selection Tool Инструмент «Прямое выделение» Direction Handles Маркеры направления Disable Auto Add/Delete Отключить авто-добавление/удаление + Interpolate Control Points When Moving Anchors Интерполировать маркеры направления при перемещении опорных точек Disable Opacity Mask Отключить непрозрачную маску Discard Отменить Discard Empty Type Отменить пустой текст @@ -2283,6 +2287,7 @@ file-filter Templates Шаблоны Scatter: Рассеивание: Rotation: Поворот: Rotation relative to: Поворот относительно: + Hue Jitter: Разброс тона: Brush Scale Options Параметры масштабирования кисти Scale Proportionately Масштабировать пропорционально Stretch to Fit Stroke Length Растянуть по длине обводки @@ -2319,6 +2324,7 @@ file-filter Templates Шаблоны Black becomes the stroke color and white stays white. Other colors become tints of the stroke color by their lightness. Чёрный становится цветом обводки, а белый остаётся белым. Остальные цвета становятся оттенками цвета обводки, и чем светлее цвет, тем светлее его оттенок. Black and white stay as they are. Dark colors become shades of the stroke color and light colors become tints of it. Чёрный остаётся чёрным, а белый остаётся белым. Остальные цвета становятся тенями цвета обводки, если они тёмные, и его оттенками, если они светлые. The key color becomes the stroke color. The other colors shift their hue by the same amount and keep their saturation and brightness. Ключевой цвет становится цветом обводки. Остальные цвета сдвигаются по цветовому кругу на столько же, на сколько ключевой цвет, и сохраняют насыщенность и яркость. + Roundness Округлость Roundness: Округлость: Fixed Фиксированный Pressure Нажим @@ -2759,6 +2765,7 @@ diagnostics ui интерфейс Line Properties: Свойства линии: Line Length: Длина линии: Line Angle: Угол линии: + Constrain Pie Angle Сохранять угол сектора Polygon Tool Инструмент «Многоугольник» Portrait Книжная Power Saving (integrated) Энергосбережение (встроенная) @@ -2920,6 +2927,9 @@ digits Malayalam Малаялам Real World: Реальный мир: Real-time Drawing and Editing Рисование и редактирование в реальном времени Use Monitor Profile for Canvas Использовать профиль монитора для холста + Refresh Monitor Profile Обновить профиль монитора +@msg turn on Use Monitor Profile for Canvas first сначала включите «Использовать профиль монитора для холста» +@msg this build doesn't read display profiles эта сборка не читает профили дисплеев The canvas is drawn in sRGB. Холст отображается в sRGB. Canvas display profile: Профиль дисплея для холста: The system matches the window to the display's colors. Система согласует цвета окна с дисплеем. @@ -3182,6 +3192,7 @@ digits Malayalam Малаялам The mouse wheel with Cmd/Ctrl held scrolls the canvas sideways. Колесо мыши с нажатой Cmd/Ctrl прокручивает холст по горизонтали. Dragging sideways on a numeric field's label changes the field's value. Перетаскивание по подписи числового поля в сторону меняет значение поля. A two-finger rotate gesture on a trackpad rotates the canvas view. Жест поворота двумя пальцами на трекпаде поворачивает вид холста. + When you move anchor points, each curve with one moved end keeps its shape relative to its ends. При перемещении опорных точек каждая кривая с одним перемещённым концом сохраняет форму относительно своих концов. Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Пока вы удерживаете клавишу инструмента, он остаётся выбранным, а после отпускания снова выбирается предыдущий инструмент. Shows the bounding box while you move the selection or draw a shape. Показывает ограничивающую рамку, пока вы перемещаете выделение или рисуете фигуру. Create Trim Marks draws Japanese-style marks instead of Roman ones. «Создать метки подрезки» рисует метки в японском стиле вместо западных. @@ -3493,6 +3504,9 @@ digits Malayalam Малаялам Search commands, tools, panels and effects… Поиск команд, инструментов, панелей и эффектов… No commands match Нет подходящих команд {pos} of {total}: {name} {pos} из {total}: {name} + No menu item Нет пункта меню + Toolbar Панель инструментов + {toolbar}, in the {tool} group {toolbar}, в группе «{tool}» @plural {n} result|{n} results {n} результат|{n} результата|{n} результатов @plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} из {n} результата. Продолжайте вводить, чтобы сузить их.|{shown} из {n} результатов. Продолжайте вводить, чтобы сузить их.|{shown} из {n} результатов. Продолжайте вводить, чтобы сузить их. Recent Commands Недавние команды @@ -4586,6 +4600,7 @@ imageTrace Outline Контур Bevel Скос Offset Смещение Axis Ось + Axis Angle Угол оси axis Horizontal Горизонтально axis Vertical Вертикально axis Both Оба @@ -4824,6 +4839,14 @@ liquify-list-end {0}, {1} {0} и {1} @msg is a prompt's answer, whose `value` must be a string or null является ответом на prompt, поэтому его `value` должно быть строкой или null @msg must have `kind` alert, confirm or prompt должен иметь `kind` alert, confirm или prompt @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` предназначен только для запуска, в котором некого спросить: в приложении человек сам отвечает на каждое диалоговое окно +@msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` должен быть целым числом от 1 до {_1} +@msg `args{place}` is nested more than 64 levels deep `args{place}` вложен глубже 64 уровней +@msg `args` must be an object `args` должен быть объектом +@msg `args` is larger than 1 MiB `args` больше 1 МиБ +@msg `path` is empty параметр `path` пуст +@msg `installed` takes a `path`, not a `source` `installed` принимает `path`, а не `source` +@msg `path` must name a .js or .jsx file `path` должен указывать на файл .js или .jsx +@msg give exactly one of `path` and `source` укажите ровно одно из: `path` и `source` @msg Running a script Выполняется скрипт @msg Copied the script report Отчёт о сценарии скопирован @msg Script file access denied: {path} Доступ скрипта к файлам запрещён: {path} @@ -5088,6 +5111,7 @@ liquify-list-end {0}, {1} {0} и {1} @msg choose a folder to export to выберите папку для экспорта @msg choose a location for the package выберите расположение для пакета @msg clipboard is empty буфер обмена пуст +@msg colorTable.deleted: at least one color has to stay in the color table colorTable.deleted: в цветовой таблице должен остаться хотя бы один цвет @msg colorTable.{what}: `{h}` is not a colour such as "#ff8800" colorTable.{what}: `{h}` не является цветом, например "#ff8800" @msg colorTable.{what}: at most {MAX_TABLE} colours colorTable.{what}: не более {MAX_TABLE} цветов @msg command `{0}` is not available right now: {1} команда `{0}` сейчас недоступна: {1} @@ -5155,6 +5179,12 @@ liquify-list-end {0}, {1} {0} и {1} @msg no PNG encoder нет кодера PNG @msg no active document нет активного документа @msg no active perspective plane нет активной плоскости перспективы +@msg the perspective grid is hidden сетка перспективы скрыта +@msg Automatic Plane Positioning is off: turn on anchorPoint or gridlineIntersection (perspective.widget.options) Автоматическое размещение плоскости выключено: включите anchorPoint или gridlineIntersection (perspective.widget.options) +@msg anchorPoint must be true or false anchorPoint должно быть true или false +@msg gridlineIntersection must be true or false gridlineIntersection должно быть true или false +@msg tolerance must be 0 or more tolerance должно быть 0 или больше +@msg give `at` or `clear`, not both укажите `at` или `clear`, но не оба @msg no anchor points selected опорные точки не выделены @msg `points` must be two or three [x, y] pairs of numbers `points` должен содержать две или три пары чисел [x, y] @msg direct-select two or three anchor points, or give `points` выделите прямым выделением две или три опорные точки или задайте `points` @@ -5629,6 +5659,8 @@ variable-list-end {0}, {1} {0} и {1} @msg Reload the page to go on (changes not saved yet may be lost). Перезагрузите страницу, чтобы продолжить (ещё не сохранённые изменения могут быть потеряны). @msg tool (a tool id) is required требуется tool (идентификатор инструмента) @msg {tool} isn't in a toolbar group of several tools {tool} не входит в группу панели инструментов из нескольких инструментов +@msg Presentation Mode hides the toolbars: change the screen mode to show them Режим презентации скрывает панели инструментов: чтобы показать их, смените режим экрана +@msg Tab has hidden the toolbars: press Tab to show them клавиша Tab скрыла панели инструментов: чтобы показать их, нажмите Tab @msg onto must name a panel floating in another group onto должен называть панель, плавающую в другой группе @msg below and above must name a panel floating in another group below и above должны называть панель, плавающую в другой группе @msg give only one of onto, below and above укажите только один из onto, below и above @@ -5747,6 +5779,7 @@ variable-list-end {0}, {1} {0} и {1} @msg a linked JavaScript file is outside the read roots связанный файл JavaScript находится вне корневых папок для чтения @msg a linked image file is outside the read roots связанный файл изображения находится вне корневых папок для чтения @msg a linked file's export folder is outside the read roots папка экспорта связанного файла находится вне корневых папок для чтения +@msg a linked file's editing data can't be read to check it against the read roots не удаётся прочитать данные редактирования связанного файла, чтобы сверить их с корневыми папками для чтения @msg automation path rejected: outside the write root {root}: {path} путь автоматизации отклонён: вне корневой папки для записи {root}: {path} @msg automation path rejected: outside the write roots {roots}: {path} путь автоматизации отклонён: вне корневых папок для записи {roots}: {path} @msg automation path rejected: path is empty путь автоматизации отклонён: путь пуст @@ -6029,6 +6062,7 @@ lighting Light Свет Cove Выкружка Depth Глубина Front Спереди + Side Сбоку Isometric Bottom Изометрия снизу Isometric Left Изометрия слева Isometric Right Изометрия справа @@ -6123,7 +6157,7 @@ lighting Light Свет @msg each of `{GRAPHICS}` must be an object каждый элемент `{GRAPHICS}` должен быть объектом @msg `{GRAPHICS}` entries take symbol, face, x, y, scale and rotation, not `{k}` элементы `{GRAPHICS}` принимают symbol, face, x, y, scale и rotation, а не `{k}` @msg each of `{GRAPHICS}` needs `symbol`, the name of a symbol каждому элементу `{GRAPHICS}` нужен `symbol`, имя символа -@msg `{GRAPHICS}` face must be front or back face в `{GRAPHICS}` должен быть front или back +@msg `{GRAPHICS}` face must be front, back or side face в `{GRAPHICS}` должен быть front, back или side @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} {key} в `{GRAPHICS}` должен быть числом от {lo} до {hi} @msg `{GRAPHICS}` must be an array `{GRAPHICS}` должен быть массивом @msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types Графика наносится на объекты типов «Плоскость», «Выдавливание», «Вращение» и «Надувание» @@ -7735,6 +7769,14 @@ breakText Glyphs Глифы Remove Gaps Убрать зазоры @msg that makes too many pieces (at most 100000): make the dashes longer так получится слишком много частей (не более 100000): удлините штрихи @msg select paths, or segments, to divide выделите контуры или сегменты для разделения +# Path Precision Tools add-on: Smooth Bridge. + Smooth Bridge… Плавный мост… + Smooth Bridge Плавный мост + Keep Originals Сохранить оригиналы +@msg select two circles to bridge выделите две окружности для соединения +@msg one circle is inside the other одна окружность находится внутри другой +@msg the circles are too far apart for this radius: raise the radius окружности слишком далеко друг от друга для этого радиуса: увеличьте радиус +@msg the circles are too far apart for this radius окружности слишком далеко друг от друга для этого радиуса # Path Precision Tools add-on: Common Tangents. Common Tangents… Общие касательные… Common Tangents Общие касательные diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 78bdbdf41b..0a0ebced8f 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -129,6 +129,7 @@ Add to Swatches Lägg till i färgrutor Add Used Colors Lägg till använda färger Additional Plug-ins Folder Mapp för ytterligare plugins + Plug-in Instruction Budget Instruktionsbudget för plugins Additional Fonts Folder Mapp för ytterligare typsnitt Adjust Adjoining Width Points Justera angränsande breddpunkter Incoming Inkommande @@ -804,6 +805,8 @@ font-technology Variable Variabla Delete Artboard Radera rityta Delete Artboards Radera ritytor Delete Brush Radera pensel + Delete Color Radera färg + Restore Generated Table Återställ genererad tabell Delete Character Style Radera teckenstil Delete Empty Artboards Radera tomma ritytor Delete Freeform Point Radera fri punkt @@ -872,6 +875,7 @@ font-technology Variable Variabla Direct Selection Tool Direktmarkeringsverktyg Direction Handles Riktningshandtag Disable Auto Add/Delete Inaktivera Lägg till/radera automatiskt + Interpolate Control Points When Moving Anchors Interpolera riktningshandtag vid flyttning av ankarpunkter Disable Opacity Mask Inaktivera opacitetsmask Discard Släng Discard Empty Type Släng tom text @@ -2190,6 +2194,7 @@ font-technology Variable Variabla Scatter: Spridning: Rotation: Rotation: Rotation relative to: Rotation i förhållande till: + Hue Jitter: Nyansvariation: Brush Scale Options Alternativ för penselskala Scale Proportionately Skala proportionellt Stretch to Fit Stroke Length Sträck för att passa konturlängden @@ -2226,6 +2231,7 @@ font-technology Variable Variabla Black becomes the stroke color and white stays white. Other colors become tints of the stroke color by their lightness. Svart blir konturfärgen och vitt förblir vitt. Andra färger blir ljusare toner av konturfärgen, och ju ljusare en färg är, desto ljusare är dess ton. Black and white stay as they are. Dark colors become shades of the stroke color and light colors become tints of it. Svart förblir svart och vitt förblir vitt. Andra färger blir mörkare toner av konturfärgen när de är mörka och ljusare toner av den när de är ljusa. The key color becomes the stroke color. The other colors shift their hue by the same amount and keep their saturation and brightness. Nyckelfärgen blir konturfärgen. De andra färgerna flyttas lika långt runt färghjulet som nyckelfärgen och behåller sin mättnad och ljusstyrka. + Roundness Rundhet Roundness: Rundhet: Fixed Fast Pressure Tryck @@ -2657,6 +2663,7 @@ font-technology Variable Variabla Line Properties: Linjeegenskaper: Line Length: Linjelängd: Line Angle: Linjevinkel: + Constrain Pie Angle Behåll cirkeldiagrammets vinkel Polygon Tool Polygonverktyg Portrait Stående Power Saving (integrated) Energisparläge (integrerad) @@ -2816,6 +2823,9 @@ digits Malayalam Malayalam Real World: Verkligt mått: Real-time Drawing and Editing Ritning och redigering i realtid Use Monitor Profile for Canvas Använd skärmprofil för arbetsytan + Refresh Monitor Profile Uppdatera skärmprofil +@msg turn on Use Monitor Profile for Canvas first slå först på ”Använd skärmprofil för arbetsytan” +@msg this build doesn't read display profiles den här versionen läser inte skärmprofiler The canvas is drawn in sRGB. Arbetsytan ritas i sRGB. Canvas display profile: Arbetsytans skärmprofil: The system matches the window to the display's colors. Systemet anpassar fönstret till skärmens färger. @@ -3076,6 +3086,7 @@ digits Malayalam Malayalam The mouse wheel with Cmd/Ctrl held scrolls the canvas sideways. Mushjulet med Cmd/Ctrl nedtryckt rullar arbetsytan i sidled. Dragging sideways on a numeric field's label changes the field's value. Att dra i sidled på ett sifferfälts etikett ändrar fältets värde. A two-finger rotate gesture on a trackpad rotates the canvas view. En rotationsgest med två fingrar på en styrplatta roterar arbetsytans vy. + When you move anchor points, each curve with one moved end keeps its shape relative to its ends. När du flyttar ankarpunkter behåller varje kurva med en flyttad ände sin form i förhållande till sina ändar. Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. När du håller ned ett verktygs kortkommando är verktyget valt tills du släpper, och sedan väljs det föregående verktyget igen. Shows the bounding box while you move the selection or draw a shape. Visar avgränsningsramen medan du flyttar markeringen eller ritar en form. Create Trim Marks draws Japanese-style marks instead of Roman ones. Skapa skärmärken ritar märken i japansk stil i stället för romerska. @@ -3373,6 +3384,9 @@ digits Malayalam Malayalam Search commands, tools, panels and effects… Sök kommandon, verktyg, paneler och effekter… No commands match Inga kommandon matchar {pos} of {total}: {name} {pos} av {total}: {name} + No menu item Inget menyalternativ + Toolbar Verktygsfält + {toolbar}, in the {tool} group {toolbar}, i gruppen {tool} @plural {n} result|{n} results {n} resultat|{n} resultat @plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} av {n} resultat. Fortsätt skriva för att begränsa dem.|{shown} av {n} resultat. Fortsätt skriva för att begränsa dem. Recent Commands Senaste kommandon @@ -4459,6 +4473,7 @@ imageTrace Outline Kontur Bevel Fasning Offset Förskjutning Axis Axel + Axis Angle Axelvinkel axis Horizontal Horisontell axis Vertical Vertikal axis Both Båda @@ -4705,6 +4720,14 @@ liquify-list-end {0}, {1} {0} och {1} @msg is a prompt's answer, whose `value` must be a string or null är svaret på en prompt, vars `value` måste vara en sträng eller null @msg must have `kind` alert, confirm or prompt måste ha `kind` alert, confirm eller prompt @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` är bara för en körning utan någon att fråga: i appen svarar personen på varje dialogruta +@msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` måste vara ett heltal från 1 till {_1} +@msg `args{place}` is nested more than 64 levels deep `args{place}` är kapslat mer än 64 nivåer djupt +@msg `args` must be an object `args` måste vara ett objekt +@msg `args` is larger than 1 MiB `args` är större än 1 MiB +@msg `path` is empty `path` är tomt +@msg `installed` takes a `path`, not a `source` `installed` tar en `path`, inte en `source` +@msg `path` must name a .js or .jsx file `path` måste ange en .js- eller .jsx-fil +@msg give exactly one of `path` and `source` ange exakt en av `path` och `source` @msg Running a script Kör ett skript @msg Copied the script report Kopierade skriptrapporten @msg Script file access denied: {path} Skriptets filåtkomst nekades: {path} @@ -4957,6 +4980,7 @@ liquify-list-end {0}, {1} {0} och {1} @msg choose a folder to export to välj en mapp att exportera till @msg choose a location for the package välj en plats för paketet @msg clipboard is empty urklippet är tomt +@msg colorTable.deleted: at least one color has to stay in the color table colorTable.deleted: minst en färg måste finnas kvar i färgtabellen @msg colorTable.{what}: `{h}` is not a colour such as "#ff8800" colorTable.{what}: `{h}` är inte en färg som "#ff8800" @msg colorTable.{what}: at most {MAX_TABLE} colours colorTable.{what}: högst {MAX_TABLE} färger @msg command `{0}` is not available right now: {1} kommandot `{0}` är inte tillgängligt just nu: {1} @@ -5024,6 +5048,12 @@ liquify-list-end {0}, {1} {0} och {1} @msg no PNG encoder ingen PNG-kodare @msg no active document inget aktivt dokument @msg no active perspective plane inget aktivt perspektivplan +@msg the perspective grid is hidden perspektivrutnätet är dolt +@msg Automatic Plane Positioning is off: turn on anchorPoint or gridlineIntersection (perspective.widget.options) Automatisk planplacering är avstängd: slå på anchorPoint eller gridlineIntersection (perspective.widget.options) +@msg anchorPoint must be true or false anchorPoint måste vara true eller false +@msg gridlineIntersection must be true or false gridlineIntersection måste vara true eller false +@msg tolerance must be 0 or more tolerance måste vara 0 eller mer +@msg give `at` or `clear`, not both ange `at` eller `clear`, inte båda @msg no anchor points selected inga ankarpunkter är markerade @msg `points` must be two or three [x, y] pairs of numbers `points` måste vara två eller tre talpar [x, y] @msg direct-select two or three anchor points, or give `points` direktmarkera två eller tre ankarpunkter eller ange `points` @@ -5489,6 +5519,8 @@ variable-list-end {0}, {1} {0} och {1} @msg Reload the page to go on (changes not saved yet may be lost). Läs in sidan igen för att fortsätta (ändringar som inte sparats än kan gå förlorade). @msg tool (a tool id) is required tool (ett verktygs-id) krävs @msg {tool} isn't in a toolbar group of several tools {tool} ingår inte i en verktygsgrupp med flera verktyg +@msg Presentation Mode hides the toolbars: change the screen mode to show them Presentationsläge döljer verktygsfälten: byt skärmläge för att visa dem +@msg Tab has hidden the toolbars: press Tab to show them Tab har dolt verktygsfälten: tryck på Tab för att visa dem @msg onto must name a panel floating in another group onto måste ange en panel som flyter i en annan grupp @msg below and above must name a panel floating in another group below och above måste ange en panel som flyter i en annan grupp @msg give only one of onto, below and above ange bara en av onto, below och above @@ -5625,6 +5657,7 @@ variable-list-end {0}, {1} {0} och {1} @msg automation path rejected: outside the read roots {roots}: {path} automatiseringssökvägen avvisades: utanför läsrötterna {roots}: {path} @msg a linked image file is outside the read roots en länkad bildfil ligger utanför läsrötterna @msg a linked file's export folder is outside the read roots exportmappen för en länkad fil ligger utanför läsrötterna +@msg a linked file's editing data can't be read to check it against the read roots redigeringsdata för en länkad fil kan inte läsas för att kontrolleras mot läsrötterna @msg automation path rejected: outside the write root {root}: {path} automatiseringssökvägen avvisades: utanför skrivroten {root}: {path} @msg automation path rejected: outside the write roots {roots}: {path} automatiseringssökvägen avvisades: utanför skrivrötterna {roots}: {path} @msg automation path rejected: path is empty automatiseringssökvägen avvisades: sökvägen är tom @@ -5901,6 +5934,7 @@ lighting Light Ljus Cove Hålkäl Depth Djup Front Framifrån + Side Från sidan Isometric Bottom Isometrisk underifrån Isometric Left Isometrisk vänster Isometric Right Isometrisk höger @@ -5996,7 +6030,7 @@ lighting Light Ljus @msg each of `{GRAPHICS}` must be an object varje post i `{GRAPHICS}` måste vara ett objekt @msg `{GRAPHICS}` entries take symbol, face, x, y, scale and rotation, not `{k}` posterna i `{GRAPHICS}` tar symbol, face, x, y, scale och rotation, inte `{k}` @msg each of `{GRAPHICS}` needs `symbol`, the name of a symbol varje post i `{GRAPHICS}` behöver `symbol`, namnet på en symbol -@msg `{GRAPHICS}` face must be front or back face i `{GRAPHICS}` måste vara front eller back +@msg `{GRAPHICS}` face must be front, back or side face i `{GRAPHICS}` måste vara front, back eller side @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} {key} i `{GRAPHICS}` måste vara ett tal från {lo} till {hi} @msg `{GRAPHICS}` must be an array `{GRAPHICS}` måste vara en matris @msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types Grafik placeras på objekttyperna Plan, Extrudera, Rotera runt axel och Blås upp @@ -7779,6 +7813,14 @@ breakText Glyphs Glyfer Remove Gaps Ta bort mellanrum @msg that makes too many pieces (at most 100000): make the dashes longer det blir för många delar (högst 100000): gör strecken längre @msg select paths, or segments, to divide markera banor eller segment att dela upp +# Path Precision Tools add-on: Smooth Bridge. + Smooth Bridge… Mjuk brygga… + Smooth Bridge Mjuk brygga + Keep Originals Behåll original +@msg select two circles to bridge markera två cirklar att förbinda +@msg one circle is inside the other den ena cirkeln ligger inuti den andra +@msg the circles are too far apart for this radius: raise the radius cirklarna ligger för långt ifrån varandra för den här radien: öka radien +@msg the circles are too far apart for this radius cirklarna ligger för långt ifrån varandra för den här radien # Path Precision Tools add-on: Common Tangents. Common Tangents… Gemensamma tangenter… Common Tangents Gemensamma tangenter diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 907cf2e7ef..4a21fc7037 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -373,6 +373,33 @@ fn turkish_draw_labels_use_the_drawing_verb() { assert_eq!(message(tr_lang, "Scale must be drawing:real, for example 1:10"), "Ölçek çizim:gerçek biçiminde olmalıdır, örneğin 1:10"); } +/// Turkish rows that name the Revolve or Extrude & Bevel effect use the catalog's label for that +/// effect, so a message about Revolve does not read as Rotate. `Revolve angle` names a control, +/// not the effect, and keeps its own wording. +#[test] +fn turkish_three_d_rows_use_the_effect_labels() { + let tr_lang = Lang::from_code("tr").expect("tr registered"); + let revolve = message(tr_lang, "Revolve"); + let extrude = message(tr_lang, "Extrude & Bevel"); + assert_eq!(revolve, "Eksen Etrafında Döndür"); + assert_eq!(extrude, "Ekstrüzyon ve Eğim"); + let (entries, _) = parse_entries(tr_lang.0.source); + let mut wrong = Vec::new(); + for (_, src, t) in &entries { + let names_revolve = src.split(|c: char| !c.is_alphanumeric()).any(|w| w == "Revolve") && src != "Revolve angle"; + if (names_revolve && (!t.contains(revolve.as_str()) || t.contains("Revolve"))) + || (src.contains("Extrude & Bevel") && !t.contains(extrude.as_str())) + { + wrong.push(format!("{src:?} -> {t:?}")); + } + } + assert!(wrong.is_empty(), "Turkish rows that do not use the effect label:\n{}", wrong.join("\n")); + assert_eq!( + message(tr_lang, "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)" + ); +} + /// The Catalan catalog registers under `ca`, claims complete menus and messages, and passes /// locale resolution, vocabulary and count formatting checks. #[test] @@ -610,6 +637,7 @@ fn monitor_profile_labels_are_in_complete_catalogs() { for lang in LANGUAGES.iter().filter(|lang| lang.complete_menus) { for label in [ "Use Monitor Profile for Canvas", + "Refresh Monitor Profile", "The canvas is drawn in sRGB.", "Canvas display profile:", "The system matches the window to the display's colors.", @@ -779,6 +807,21 @@ fn anti_aliasing_method_labels_are_in_complete_catalogs() { } } +/// Each row in the `search` context, which adds a language's words to a group of words with the same +/// meaning for the command palette, names a group and adds single words of no other group. No +/// catalog has to have these rows. +#[test] +fn search_rows_name_a_group_and_add_single_words() { + let mut bad = Vec::new(); + for l in LANGUAGES.iter().filter(|l| !l.source.is_empty()) { + let (entries, _) = parse_entries(l.source); + for (_, src, tr) in entries.iter().filter(|(ctx, _, _)| ctx == crate::palette::words::CONTEXT) { + bad.extend(crate::palette::words::row_problems(src, tr).into_iter().map(|p| format!("{}: {p}", l.code))); + } + } + assert!(bad.is_empty(), "{bad:#?}"); +} + /// The Painted and Sketched graphic style library's name and its styles' names have a row in every /// bundled catalog. #[test] @@ -3580,9 +3623,9 @@ fn three_d_refusals_translate_with_their_values() { vec!["0", "100"], ), ( - refuse(vectorcraft_effects::validate_three_d(&rect, EXTRUDE, &json!({"graphics": [{"symbol": "S", "face": "side"}]}))), - "must be front or back", - vec!["`graphics`", "front", "back"], + refuse(vectorcraft_effects::validate_three_d(&rect, EXTRUDE, &json!({"graphics": [{"symbol": "S", "face": "top"}]}))), + "must be front, back or side", + vec!["`graphics`", "front", "back", "side"], ), (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"]), @@ -5134,6 +5177,55 @@ fn dataset_import_repeated_column_error_is_translated() { } } +/// The errors of Automatic Plane Positioning (`perspective.plane.infer`) and of its two options +/// (`perspective.widget.options`) have their own row in every language that translates every +/// message, and the status bar shows them translated with the parameter names kept. +#[test] +fn automatic_plane_positioning_errors_are_translated() { + use serde_json::json; + use vectorcraft_engine::{EngineError, Session}; + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let mut errors = vec![]; + for (cmd, p, want, kept) in [ + ("perspective.plane.infer", json!({"at": [0, 0], "tolerance": -1}), "tolerance must be 0 or more", &["tolerance"][..]), + ("perspective.plane.infer", json!({"at": [0, 0], "clear": true}), "give `at` or `clear`, not both", &["`at`", "`clear`"][..]), + ("perspective.widget.options", json!({"anchorPoint": "yes"}), "anchorPoint must be true or false", &["anchorPoint"][..]), + ( + "perspective.widget.options", + json!({"gridlineIntersection": 1}), + "gridlineIntersection must be true or false", + &["gridlineIntersection"][..], + ), + ] { + let e = s.execute(cmd, &p).unwrap_err(); + assert!(matches!(&e, EngineError::BadParams { msg, .. } if msg == want), "{cmd} {p}: {e}"); + errors.push((e.to_string(), want, kept)); + } + s.execute("perspective.grid.show", &json!({"visible": false})).unwrap(); + let hidden = "the perspective grid is hidden"; + let e = s.execute("perspective.plane.infer", &json!({"at": [0, 0]})).unwrap_err(); + assert!(matches!(&e, EngineError::Other(msg) if msg == hidden), "{e}"); + errors.push((e.to_string(), hidden, &[][..])); + s.execute("perspective.grid.show", &json!({"visible": true})).unwrap(); + s.execute("perspective.plane.set", &json!({"plane": "ground"})).unwrap(); + s.execute("perspective.widget.options", &json!({"anchorPoint": false, "gridlineIntersection": false})).unwrap(); + let off = "Automatic Plane Positioning is off: turn on anchorPoint or gridlineIntersection (perspective.widget.options)"; + let e = s.execute("perspective.plane.infer", &json!({"at": [0, 0]})).unwrap_err(); + assert!(matches!(&e, EngineError::Other(msg) if msg == off), "{e}"); + errors.push((e.to_string(), off, &["anchorPoint", "gridlineIntersection", "(perspective.widget.options)"][..])); + let literals = message_literals(); + for (e, want, kept) in &errors { + assert!(literals.contains(*want), "{want}"); + for code in COMPLETE_MESSAGES { + let lang = Lang::from_code(code).expect("registered"); + assert!(lang.catalog().exact_message(want).is_some(), "{code} has no row for {want}"); + let shown = message(lang, e); + assert!(!shown.contains(want) && kept.iter().all(|k| shown.contains(k)), "{code}: {shown}"); + } + } +} + /// The scan reads the refusals `script.run`'s `param(msg)` gives, and not the arguments of a type's /// own function of that name. #[test] @@ -5224,6 +5316,85 @@ fn script_answers_errors_are_translated() { } } +/// `script.run`'s other refusals of its parameters (`maxFuel`, `args`, `path`, `source`, +/// `installed`, `name`) and its errors for a script it cannot read are translated in every language +/// that translates every message, with the code names, the place in `args`, the file suffixes, the +/// limits and the file's path kept. The command's error stays in English. +#[test] +fn script_run_param_errors_are_translated() { + use serde_json::{Value, json}; + use vectorcraft_engine::{EngineError, Session}; + let refusals = [ + "`maxFuel` must be a whole number from 1 to {_1}", + "`args{place}` is nested more than 64 levels deep", + "`args` must be an object", + "`args` is larger than 1 MiB", + "`path` is empty", + "`installed` takes a `path`, not a `source`", + "`path` must name a .js or .jsx file", + "give exactly one of `path` and `source`", + ]; + let scanned = message_literals(); + for template in refusals { + assert!(scanned.contains(template), "{template}"); + } + let dir = vectorcraft_testkit::TempDir::new("i18n-script-run-params"); + let not_text = dir.join("not-text.js"); + std::fs::write(¬_text, [0x66, 0xff, 0xfe]).expect("write"); + let folder = dir.join("folder.js"); + std::fs::create_dir(&folder).expect("folder"); + let (not_text, folder) = (not_text.to_string_lossy().into_owned(), folder.to_string_lossy().into_owned()); + let mut deep = json!(1); + for _ in 0..70 { + deep = json!([deep]); + } + let fuel = vectorcraft_engine::script::MAX_FUEL; + // Each call, with the English message its parameter refusal gives, or `None` for an error that + // is not one. + let bad: Vec<(Value, Option)> = vec![ + (json!({"source": "1", "maxFuel": 0}), Some(format!("`maxFuel` must be a whole number from 1 to {fuel}"))), + (json!({"source": "1", "maxFuel": fuel + 1}), Some(format!("`maxFuel` must be a whole number from 1 to {fuel}"))), + (json!({"source": "1", "args": {"a": deep}}), Some(format!("`args.a{}` is nested more than 64 levels deep", "[0]".repeat(64)))), + (json!({"source": "1", "args": [1]}), Some("`args` must be an object".into())), + (json!({"source": "1", "args": {"x": "x".repeat(1 << 20)}}), Some("`args` is larger than 1 MiB".into())), + (json!({"path": ""}), Some("`path` is empty".into())), + (json!({"source": "1", "installed": true}), Some("`installed` takes a `path`, not a `source`".into())), + (json!({"path": "notes.txt"}), Some("`path` must name a .js or .jsx file".into())), + (json!({}), Some("give exactly one of `path` and `source`".into())), + (json!({"path": "a.js", "source": "1"}), Some("give exactly one of `path` and `source`".into())), + (json!({"path": 1}), Some("`path` must be a string".into())), + (json!({"source": "1", "name": false}), Some("`name` must be a string".into())), + (json!({"source": "1", "installed": "yes"}), Some("`installed` must be true or false".into())), + (json!({"path": "built.jsxbin"}), None), + (json!({"source": "x".repeat(vectorcraft_engine::script::MAX_SOURCE_BYTES + 1)}), None), + (json!({"path": "listed.js", "installed": true}), None), + (json!({"path": not_text}), None), + (json!({"path": folder}), None), + ]; + let mut s = Session::new(); + for (params, want) in bad { + let e = s.execute("script.run", ¶ms).unwrap_err(); + let line = e.to_string(); + let inner = match (&e, &want) { + (EngineError::BadParams { cmd, msg }, Some(want)) if cmd == "script.run" && msg == want => want.clone(), + (EngineError::Other(msg), None) => msg.clone(), + _ => panic!("{params:.80}: {e}"), + }; + // The code names and the place in `args`, the numbers, the file suffixes and the path. + let mut kept: Vec<&str> = inner.split('`').skip(1).step_by(2).collect(); + kept.extend(inner.split(|c: char| !c.is_ascii_digit()).filter(|n| !n.is_empty())); + kept.extend([".jsx", ".js", not_text.as_str(), folder.as_str()].into_iter().filter(|k| inner.contains(*k))); + for code in COMPLETE_MESSAGES { + let lang = Lang::from_code(code).expect("registered"); + let shown = message(lang, &line); + let translated = message(lang, &inner); + assert_ne!(translated, inner, "{code}"); + assert!(shown.contains(&translated) && !shown.contains("invalid parameters"), "{code}: {shown}"); + assert!(kept.iter().all(|k| shown.contains(k)), "{code}: {shown}"); + } + } +} + /// The errors of a command's parameter schema are translated in every language that translates /// every message, with the parameter's path and the refused value kept. #[test] @@ -5975,7 +6146,7 @@ const NAMED_KEYS: &[(&str, &[&str])] = &[ ("`dither` applies to gradient fills (stroke: false)", &["stroke"]), ("`strokeMode` applies to strokes (stroke: true)", &["stroke"]), ("`{GRAPHICS}` entries take symbol, face, x, y, scale and rotation, not `{k}`", &["symbol", "face", "x", "y", "scale", "rotation"]), - ("`{GRAPHICS}` face must be front or back", &["face", "front", "back"]), + ("`{GRAPHICS}` face must be front, back or side", &["face", "front", "back", "side"]), ("`{name}`: give the kanji part", &["kanji"]), ("`{name}`: parts must be an object", &["parts"]), ( @@ -6181,7 +6352,8 @@ const MESSAGE_MARKERS: &[&str] = &[".status(", "ui.status = ", "status = ", "Oth /// a plug-in returned), and the script interpreter's methods that throw an error at a script: /// `.type_error(msg)`, `.throw(kind, msg)` and the XPath evaluator's `.error(msg)`, with the reasons /// it gives for a property it cannot define or assign (`.reject_bool(throw, key, why)` and -/// `.reject(throw, key, why)`). A helper that starts with `.` is a method of any receiver; any other +/// `.reject(throw, key, why)`), and the interface's `unavailable(tool, reason)` (a tool's place that +/// no toolbar can show, which Help puts in the status bar). A helper that starts with `.` is a method of any receiver; any other /// is a function, not a type's own function of the same name (`Grays::param(C, p)`). const ERROR_HELPERS: &[(&str, &str, usize)] = &[ ("engine", "bad(", 1), @@ -6204,6 +6376,7 @@ const ERROR_HELPERS: &[(&str, &str, usize)] = &[ ("js", ".error(", 0), ("js", ".reject_bool(", 2), ("js", ".reject(", 2), + ("ui-egui", "unavailable(", 1), ]; /// Error variants whose first argument is a name, not a message: a command id @@ -6803,6 +6976,40 @@ fn polish_plurals_have_three_forms() { assert!(count >= 13, "Polish plural rows missing"); } +/// Every Polish row whose English names art or artwork calls it kompozycja, the catalog's term, and +/// never grafika (kept for what the English calls a graphic) or rysunek. An artboard's obszar +/// kompozycji does not count as the term. Line art, the art brush and its class, Art Ribbons, +/// Art & Illustration, Art Optimized and the literal values `art` and `artwork` are other terms. +#[test] +fn polish_rows_call_artwork_kompozycja() { + let (entries, _) = parse_entries(pl().0.source); + let mut wrong = Vec::new(); + for (_, src, translation) in &entries { + let english = src.to_lowercase(); + let words: Vec<&str> = english.split(|c: char| !c.is_ascii_alphabetic()).collect(); + let names = |list: &[&str]| words.iter().any(|w| list.contains(w)); + let polish = translation.to_lowercase(); + let polish_words: Vec<&str> = polish.split(|c: char| !c.is_alphabetic()).filter(|w| !w.is_empty()).collect(); + let other_term = ["line art", "art brush", "art ribbons", "art & illustration", "art optimized"].iter().any(|t| english.contains(t)); + let literal = polish_words.iter().any(|w| ["art", "artwork"].contains(w)); + if !names(&["art", "artwork"]) || other_term || literal || english == "art" { + continue; + } + let term = polish_words.iter().enumerate().any(|(i, w)| w.starts_with("kompozyc") && !(i > 0 && polish_words[i - 1].starts_with("obszar"))); + let graphic = polish.contains("graf") && !names(&["graphic", "graphics"]); + if !term || graphic || polish.contains("rysun") { + wrong.push(format!("{src:?} -> {translation:?}")); + } + } + assert!(wrong.is_empty(), "{} Polish rows name artwork with another word:\n{}", wrong.len(), wrong.join("\n")); + assert_eq!(tr(pl(), "Artwork"), "Kompozycja"); + assert_eq!(tr(pl(), "Off-Artboard Art"), "Kompozycja poza obszarami kompozycji"); + assert_eq!(message(pl(), "select the art to export first"), "najpierw zaznacz kompozycję do eksportu"); + assert_eq!(message(pl(), "the selected art has no width"), "zaznaczona kompozycja nie ma szerokości"); + assert_eq!(tr(pl(), "Line Art and Text Resolution:"), "Rozdzielczość grafiki liniowej i tekstu:"); + assert_eq!(tr(pl(), "Art Brush"), "Pędzel artystyczny"); +} + /// Every catalog names each numeral system of Character panel menu › Digits, in the `digits` /// context (where the language's name would read wrong) or with its plain row (#4942). #[test] diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index cddec65cf2..d5e33ac203 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -126,6 +126,7 @@ Add to Swatches Renk Örneklerine Ekle Add Used Colors Kullanılan Renkleri Ekle Additional Plug-ins Folder Ek Eklentiler Klasörü + Plug-in Instruction Budget Eklenti Talimat Bütçesi Additional Fonts Folder Ek Yazı Tipleri Klasörü Adjust Adjoining Width Points Bitişik Genişlik Noktalarını Ayarlayın Incoming Gelen @@ -795,6 +796,8 @@ font-technology Variable Değişken Delete Artboard Çalışma Yüzeyini Sil Delete Artboards Çalışma Yüzeylerini Sil Delete Brush Fırçayı Sil + Delete Color Rengi Sil + Restore Generated Table Oluşturulan Tabloyu Geri Yükle Delete Character Style Karakter Stilini Sil Delete Empty Artboards Boş Çalışma Yüzeylerini Sil Delete Freeform Point Serbest Biçim Noktasını Sil @@ -863,6 +866,7 @@ font-technology Variable Değişken Direct Selection Tool Doğrudan Seçim Aracı Direction Handles Yön Kolları Disable Auto Add/Delete Otomatik Ekleme/Silmeyi Devre Dışı Bırak + Interpolate Control Points When Moving Anchors Bağlantı Noktalarını Taşırken Yön Kollarını Enterpole Et Disable Opacity Mask Opaklık Maskesini Devre Dışı Bırak Discard At Discard Empty Type Boş Türü At @@ -2071,6 +2075,7 @@ font-technology Variable Değişken Scatter: Dağılım: Rotation: Rotasyon: Rotation relative to: Şuna göre rotasyon: + Hue Jitter: Renk tonu değişimi: Brush Scale Options Fırça Ölçeği Seçenekleri Scale Proportionately Orantılı Olarak Ölçeklendirin Stretch to Fit Stroke Length Kontur Uzunluğuna Sığacak Şekilde Esnetin @@ -2100,6 +2105,7 @@ font-technology Variable Değişken Tints and Shades Renk Tonları ve Gölgeler Hue Shift Ton Değiştirme Key Color: Anahtar Rengi: + Roundness Yuvarlaklık Roundness: Yuvarlaklık: Fixed Sabit Pressure Basınç @@ -2504,6 +2510,7 @@ shape Open Açık Line Properties: Çizgi Özellikleri: Line Length: Çizgi Uzunluğu: Line Angle: Çizgi Açısı: + Constrain Pie Angle Pasta Açısını Sınırla Polygon Tool Çokgen Aracı Portrait Portre Power Saving (integrated) Güç Tasarrufu (entegre) @@ -2662,6 +2669,9 @@ digits Malayalam Malayalam Real World: Gerçek Dünya: Real-time Drawing and Editing Gerçek Zamanlı Çizim ve Düzenleme Use Monitor Profile for Canvas Tuval için Monitör Profilini Kullan + Refresh Monitor Profile Monitör Profilini Yenile +@msg turn on Use Monitor Profile for Canvas first önce "Tuval için Monitör Profilini Kullan" seçeneğini açın +@msg this build doesn't read display profiles bu sürüm ekran profillerini okumaz The canvas is drawn in sRGB. Tuval sRGB olarak çizilir. Canvas display profile: Tuvalin ekran profili: The system matches the window to the display's colors. Sistem pencereyi ekranın renklerine uyarlar. @@ -2919,6 +2929,7 @@ digits Malayalam Malayalam The mouse wheel with Cmd/Ctrl held scrolls the canvas sideways. Cmd/Ctrl basılıyken fare tekerleği tuvali yana kaydırır. Dragging sideways on a numeric field's label changes the field's value. Sayısal bir alanın etiketi üzerinde yana sürüklemek alanın değerini değiştirir. A two-finger rotate gesture on a trackpad rotates the canvas view. İzleme dörtgeninde iki parmakla döndürme hareketi tuvalin görünümünü döndürür. + When you move anchor points, each curve with one moved end keeps its shape relative to its ends. Bağlantı noktalarını taşıdığınızda, bir ucu taşınan her eğri uçlarına göre şeklini korur. Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Bir aracın kısayol tuşunu basılı tutmak, tuşu bırakana kadar o aracı seçer, ardından önceki araç yeniden seçilir. Shows the bounding box while you move the selection or draw a shape. Seçimi taşırken veya bir şekil çizerken sınırlayıcı kutuyu gösterir. Create Trim Marks draws Japanese-style marks instead of Roman ones. Kesim İşaretleri Oluşturun, Roma tarzı yerine Japon tarzı işaretler çizer. @@ -3251,6 +3262,9 @@ digits Malayalam Malayalam Search commands, tools, panels and effects… Komutları, araçları, panelleri ve efektleri arayın… No commands match Eşleşen komut yok {pos} of {total}: {name} {pos}/{total}: {name} + No menu item Menü öğesi yok + Toolbar Araç Çubuğu + {toolbar}, in the {tool} group {toolbar}, {tool} grubunda @plural {n} result|{n} results {n} sonuç @plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {n} sonuçtan {shown} tanesi. Daraltmak için yazmaya devam edin. Recent Commands Son komutlar @@ -4313,6 +4327,7 @@ imageTrace Outline Kontur Bevel Eğim Offset Ofset Axis Eksen + Axis Angle Eksen açısı axis Horizontal Yatay axis Vertical Dikey axis Both Her İkisi @@ -4539,6 +4554,14 @@ liquify-list-end {0}, {1} {0} ve {1} @msg the main script engine is new for each run and is never kept, so it cannot be dropped ana betik motoru her çalıştırmada yenidir ve hiç saklanmaz, bu yüzden bırakılamaz @msg there is no script engine named {name} {name} adlı bir betik motoru yok @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` yalnızca sorulacak kimsenin olmadığı bir çalıştırma içindir: uygulamada her iletişim kutusunu kişi yanıtlar +@msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` 1 ile {_1} arasında bir tam sayı olmalıdır +@msg `args{place}` is nested more than 64 levels deep `args{place}` 64 düzeyden daha derin iç içe geçmiş +@msg `args` must be an object `args` bir nesne olmalıdır +@msg `args` is larger than 1 MiB `args` 1 MiB'tan büyük +@msg `path` is empty `path` boş +@msg `installed` takes a `path`, not a `source` `installed` bir `path` alır, `source` almaz +@msg `path` must name a .js or .jsx file `path` bir .js veya .jsx dosyasını adlandırmalıdır +@msg give exactly one of `path` and `source` `path` ve `source` değerlerinden tam olarak birini verin @msg Running a script Betik çalıştırılıyor @msg Copied the script report Komut dosyası raporu kopyalandı @msg Script file access denied: {path} Betiğin dosya erişimi reddedildi: {path} @@ -4774,6 +4797,7 @@ liquify-list-end {0}, {1} {0} ve {1} @msg choose a folder to export to dışa aktarılacak bir klasör seçin @msg choose a location for the package paket için bir yer seçin @msg clipboard is empty pano boş +@msg colorTable.deleted: at least one color has to stay in the color table colorTable.deleted: renk tablosunda en az bir renk kalmalı @msg colorTable.{what}: `{h}` is not a colour such as "#ff8800" colorTable.{what}: `{h}`, "#ff8800" gibi bir renk değil @msg colorTable.{what}: at most {MAX_TABLE} colours colorTable.{what}: en fazla {MAX_TABLE} renginde @msg command `{0}` is not available right now: {1} `{0}` komutu şu anda kullanılamıyor: {1} @@ -4848,6 +4872,12 @@ liquify-list-end {0}, {1} {0} ve {1} @msg no PNG encoder PNG kodlayıcı yok @msg no active document etkin belge yok @msg no active perspective plane aktif perspektif düzlemi yok +@msg the perspective grid is hidden perspektif ızgarası gizli +@msg Automatic Plane Positioning is off: turn on anchorPoint or gridlineIntersection (perspective.widget.options) Otomatik düzlem konumlandırma kapalı: anchorPoint veya gridlineIntersection seçeneğini açın (perspective.widget.options) +@msg anchorPoint must be true or false anchorPoint true veya false olmalıdır +@msg gridlineIntersection must be true or false gridlineIntersection true veya false olmalıdır +@msg tolerance must be 0 or more tolerance 0 veya daha büyük olmalıdır +@msg give `at` or `clear`, not both `at` veya `clear` verin, ikisini birden değil @msg no anchor points selected bağlantı noktası seçilmedi @msg `points` must be two or three [x, y] pairs of numbers `points` iki veya üç [x, y] sayı çifti olmalıdır @msg direct-select two or three anchor points, or give `points` iki veya üç bağlantı noktasını doğrudan seçin veya `points` verin @@ -5315,6 +5345,8 @@ liquify-list-end {0}, {1} {0} ve {1} @msg Reload the page to go on (changes not saved yet may be lost). Devam etmek için sayfayı yeniden yükleyin (henüz kaydedilmemiş değişiklikler kaybolabilir). @msg tool (a tool id) is required tool (bir araç kimliği) gerekli @msg {tool} isn't in a toolbar group of several tools {tool} çeşitli araçlardan oluşan bir araç çubuğu grubunda değil +@msg Presentation Mode hides the toolbars: change the screen mode to show them Sunum Modu araç çubuklarını gizler: göstermek için ekran modunu değiştirin +@msg Tab has hidden the toolbars: press Tab to show them Tab araç çubuklarını gizledi: göstermek için Tab tuşuna basın @msg onto must name a panel floating in another group onto başka bir grupta yüzen bir paneli adlandırmalıdır @msg below and above must name a panel floating in another group below ve above başka bir grupta yüzen bir paneli adlandırmalıdır @msg give only one of onto, below and above onto, below ve above değerlerinden yalnızca birini verin @@ -5657,7 +5689,7 @@ effect Soft Yumuşak Show axis Ekseni göster Reset all Tümünü sıfırla Reset to default Varsayılana sıfırla - Reset all Revolve settings to their defaults. Tüm Revolve ayarlarını varsayılan değerlerine sıfırlayın. + Reset all Revolve settings to their defaults. Tüm Eksen Etrafında Döndür ayarlarını varsayılan değerlerine sıfırlayın. Drag values or labels. Double-click a value to type. Değerleri veya etiketleri sürükleyin. Yazmak için bir değeri çift tıklayın. Drag rings to rotate. Shift snaps to 15°. Döndürmek için halkaları sürükleyin. Kaydırma 15°'ye sabitlenir. Track cube Döndürme küpü @@ -5728,6 +5760,7 @@ lighting Light Işık Cove Koy Depth Derinlik Front Ön + Side Yan Isometric Bottom İzometrik Alt Isometric Left İzometrik Sol Isometric Right İzometrik Sağ @@ -5822,7 +5855,7 @@ lighting Light Işık @msg each of `{GRAPHICS}` must be an object `{GRAPHICS}` içindeki her öğe bir nesne olmalıdır @msg `{GRAPHICS}` entries take symbol, face, x, y, scale and rotation, not `{k}` `{GRAPHICS}` girdileri symbol, face, x, y, scale ve rotation alır, `{k}` almaz @msg each of `{GRAPHICS}` needs `symbol`, the name of a symbol `{GRAPHICS}` içindeki her öğe, bir sembolün adı olan `symbol` gerektirir -@msg `{GRAPHICS}` face must be front or back `{GRAPHICS}` face değeri front veya back olmalıdır +@msg `{GRAPHICS}` face must be front, back or side `{GRAPHICS}` face değeri front, back veya side olmalıdır @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} `{GRAPHICS}` {key} değeri {lo} ile {hi} arasında bir sayı olmalıdır @msg `{GRAPHICS}` must be an array `{GRAPHICS}` bir dizi olmalıdır @msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types Grafikler Düzlem, Ekstrüzyon, Eksen Etrafında Döndür ve Şişir nesne türlerine eşlenir @@ -5846,22 +5879,22 @@ lighting Light Işık @msg The 3D projection is not finite 3D izdüşümü sonlu değil @msg The 3D shadow is too complex; turn Shadows off or simplify the art 3D gölgesi çok karmaşık; Gölgeler'i kapatın veya resmi basitleştirin @msg The shape contains invalid coordinates Şekil geçersiz koordinatlar içeriyor -@msg Revolve profile contains invalid coordinates Döndür profili geçersiz koordinatlar içeriyor -@msg Revolve profile is too complex Döndür profili çok karmaşık -@msg Revolve projection is not finite Döndür izdüşümü sonlu değil -@msg Revolve requires finite profile coordinates within 100 million points Döndür, 100 milyon pt sınırı içinde sonlu profil koordinatları gerektirir -@msg Revolve surface is too complex; reduce Segments or simplify the profile Döndür yüzeyi çok karmaşık; Segmentler değerini azaltın veya profili basitleştirin -@msg Revolve surface is too complex; simplify the profile Döndür yüzeyi çok karmaşık; profili basitleştirin -@msg Revolve visibility cannot split the projected boundary Döndür görünürlüğü izdüşümü alınan sınırı bölemiyor -@msg Revolve visibility creates too many fragments Döndür görünürlüğü çok fazla parça oluşturuyor -@msg Revolve visibility creates too many vector anchors Döndür görünürlüğü çok fazla vektör bağlantı noktası oluşturuyor -@msg Revolve visibility exceeds its geometry work limit Döndür görünürlüğü geometri işlem sınırını aşıyor -@msg Revolve visibility exceeds its spatial index limit Döndür görünürlüğü uzamsal dizin sınırını aşıyor -@msg Revolve visibility has too many boundary crossings Döndür görünürlüğünde çok fazla sınır kesişimi var -@msg Revolve visibility has too many input anchors Döndür görünürlüğünde çok fazla girdi bağlantı noktası var -@msg Revolve visibility requires convex cap sectors Döndür görünürlüğü dışbükey kapak dilimleri gerektirir -@msg Revolve visibility requires finite projected faces Döndür görünürlüğü sonlu izdüşüm yüzleri gerektirir -@msg Too many Revolve faces for visibility evaluation Görünürlük değerlendirmesi için çok fazla Döndür yüzü var +@msg Revolve profile contains invalid coordinates Eksen Etrafında Döndür profili geçersiz koordinatlar içeriyor +@msg Revolve profile is too complex Eksen Etrafında Döndür profili çok karmaşık +@msg Revolve projection is not finite Eksen Etrafında Döndür izdüşümü sonlu değil +@msg Revolve requires finite profile coordinates within 100 million points Eksen Etrafında Döndür, 100 milyon pt sınırı içinde sonlu profil koordinatları gerektirir +@msg Revolve surface is too complex; reduce Segments or simplify the profile Eksen Etrafında Döndür yüzeyi çok karmaşık; Segmentler değerini azaltın veya profili basitleştirin +@msg Revolve surface is too complex; simplify the profile Eksen Etrafında Döndür yüzeyi çok karmaşık; profili basitleştirin +@msg Revolve visibility cannot split the projected boundary Eksen Etrafında Döndür görünürlüğü izdüşümü alınan sınırı bölemiyor +@msg Revolve visibility creates too many fragments Eksen Etrafında Döndür görünürlüğü çok fazla parça oluşturuyor +@msg Revolve visibility creates too many vector anchors Eksen Etrafında Döndür görünürlüğü çok fazla vektör bağlantı noktası oluşturuyor +@msg Revolve visibility exceeds its geometry work limit Eksen Etrafında Döndür görünürlüğü geometri işlem sınırını aşıyor +@msg Revolve visibility exceeds its spatial index limit Eksen Etrafında Döndür görünürlüğü uzamsal dizin sınırını aşıyor +@msg Revolve visibility has too many boundary crossings Eksen Etrafında Döndür görünürlüğünde çok fazla sınır kesişimi var +@msg Revolve visibility has too many input anchors Eksen Etrafında Döndür görünürlüğünde çok fazla girdi bağlantı noktası var +@msg Revolve visibility requires convex cap sectors Eksen Etrafında Döndür görünürlüğü dışbükey kapak dilimleri gerektirir +@msg Revolve visibility requires finite projected faces Eksen Etrafında Döndür görünürlüğü sonlu izdüşüm yüzleri gerektirir +@msg Too many Revolve faces for visibility evaluation Görünürlük değerlendirmesi için çok fazla Eksen Etrafında Döndür yüzü var @msg input contains NaN or infinite coordinates girdi NaN veya sonsuz koordinatlar içeriyor @msg input path could not be closed girdi yolu kapatılamadı @msg the shapes are too degenerate to combine şekiller birleştirilemeyecek kadar yozlaşmış @@ -7501,7 +7534,7 @@ axis Y Axis Y ekseni @msg nothing to repeat yinelenecek bir şey yok @msg numbers out of order in {{}} quantifier {{}} niceleyicisinde sayılar sırasız @msg object {_1} needs a 3D effect {_1} nesnesinde bir 3D efekti olmalıdır -@msg object {_1}: a hollow Extrude & Bevel has no caps: turn on Cap to map a graphic nesne {_1}: içi boş bir Kalıp Çıkarma ve Eğim efektinin kapakları yoktur: bir grafik eşlemek için Kapak seçeneğini açın +@msg object {_1}: a hollow Extrude & Bevel has no caps: turn on Cap to map a graphic nesne {_1}: içi boş bir Ekstrüzyon ve Eğim efektinin kapakları yoktur: bir grafik eşlemek için Kapak seçeneğini açın @msg object {_1}: with a depth of 0 the object has one face: map its graphics onto the front nesne {_1}: derinlik 0 olduğunda nesnenin tek yüzü vardır: grafiklerini ön yüze eşleyin @msg object {_1}: {_2} nesne {_1}: {_2} @msg object {_1}: {e} nesne {_1}: {e} @@ -7570,6 +7603,7 @@ axis Y Axis Y ekseni @msg a linked JavaScript file is outside the read roots bağlantılı bir JavaScript dosyası okuma köklerinin dışında @msg a linked image file is outside the read roots bağlantılı bir görüntü dosyası okuma köklerinin dışında @msg a linked file's export folder is outside the read roots bağlantılı bir dosyanın dışa aktarma klasörü okuma köklerinin dışında +@msg a linked file's editing data can't be read to check it against the read roots bağlantılı bir dosyanın düzenleme verileri okuma köklerine göre denetlemek için okunamıyor @msg the line is too long, or the paths it passes too many, to check çizgi denetlenemeyecek kadar uzun veya geçtiği yollar çok fazla @msg the method needs an XML value yöntem için bir XML değeri gerekir @msg the paint is not a freeform gradient (apply one with paint.editGradient {{kind: "freeform"}}) boya bir serbest biçimli degrade değil (paint.editGradient {{kind: "freeform"}} ile bir tane uygulayın) @@ -7642,7 +7676,7 @@ axis Y Axis Y ekseni @msg {what} is not a function {what} bir işlev değil @msg {what} would print more than {MAX_COPIES_PER_SHEET} copies on a sheet: scale it up {what} bir yaprağa {MAX_COPIES_PER_SHEET} taneden fazla kopya yazdırırdı: ölçeğini büyütün @msg {what} {i} out of range {what} {i} aralık dışında -@msg A profile supports one Revolve effect. Edit the existing effect's options instead. Bir profil tek bir Döndürme efektini destekler. Bunun yerine mevcut efektin seçeneklerini düzenleyin. +@msg A profile supports one Revolve effect. Edit the existing effect's options instead. Bir profil tek bir Eksen Etrafında Döndür efektini destekler. Bunun yerine mevcut efektin seçeneklerini düzenleyin. @msg Add Points at Crossings: a path went missing Kesişimlere Nokta Ekle: bir yol kayboldu @msg CSS options: {e} CSS seçenekleri: {e} @msg CSV has a header but no data rows CSV'de bir başlık var ama veri satırı yok @@ -9635,6 +9669,14 @@ breakText Glyphs Glifler Remove Gaps Boşlukları Kaldır @msg that makes too many pieces (at most 100000): make the dashes longer bu çok fazla parça oluşturur (en fazla 100000): tireleri uzatın @msg select paths, or segments, to divide bölünecek yolları veya bölümleri seçin +# Path Precision Tools add-on: Smooth Bridge. + Smooth Bridge… Yumuşak Köprü… + Smooth Bridge Yumuşak Köprü + Keep Originals Orijinalleri Koru +@msg select two circles to bridge köprüyle birleştirilecek iki daire seçin +@msg one circle is inside the other bir daire diğerinin içinde +@msg the circles are too far apart for this radius: raise the radius daireler bu yarıçap için birbirinden çok uzak: yarıçapı artırın +@msg the circles are too far apart for this radius daireler bu yarıçap için birbirinden çok uzak # Path Precision Tools add-on: Common Tangents. Common Tangents… Ortak Teğetler… Common Tangents Ortak Teğetler diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 4294467405..bfc0e4bb75 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -135,6 +135,7 @@ Add to Swatches Додати до зразків Add Used Colors Додати використані кольори Additional Plug-ins Folder Папка додаткових модулів + Plug-in Instruction Budget Бюджет інструкцій модулів Additional Fonts Folder Папка додаткових шрифтів Adjust Adjoining Width Points Налаштувати суміжні точки ширини Incoming Вхідна @@ -812,6 +813,8 @@ font-technology Variable Варіативні Delete Artboard Видалити монтажну область Delete Artboards Видалити монтажні області Delete Brush Видалити пензель + Delete Color Видалити колір + Restore Generated Table Відновити створену таблицю Delete Character Style Видалити стиль символу Delete Empty Artboards Видалити порожні монтажні області Delete Freeform Point Видалити довільну точку @@ -880,6 +883,7 @@ font-technology Variable Варіативні Direct Selection Tool Інструмент «Пряме виділення» Direction Handles Маркери напряму Disable Auto Add/Delete Вимкнути авто-додавання/видалення + Interpolate Control Points When Moving Anchors Інтерполювати маркери напряму під час переміщення опорних точок Disable Opacity Mask Вимкнути маску непрозорості Discard Відкинути Preserve Зберігати @@ -2291,6 +2295,7 @@ file-filter Templates Шаблони Scatter: Розсіювання: Rotation: Поворот: Rotation relative to: Поворот відносно: + Hue Jitter: Розкид відтінку: Brush Scale Options Параметри масштабування пензля Scale Proportionately Масштабувати пропорційно Stretch to Fit Stroke Length Розтягнути за довжиною обведення @@ -2327,6 +2332,7 @@ file-filter Templates Шаблони Black becomes the stroke color and white stays white. Other colors become tints of the stroke color by their lightness. Чорний стає кольором обведення, а білий залишається білим. Інші кольори стають відтінками кольору обведення, і що світліший колір, то світліший його відтінок. Black and white stay as they are. Dark colors become shades of the stroke color and light colors become tints of it. Чорний залишається чорним, а білий залишається білим. Інші кольори стають тінями кольору обведення, якщо вони темні, і його відтінками, якщо вони світлі. The key color becomes the stroke color. The other colors shift their hue by the same amount and keep their saturation and brightness. Ключовий колір стає кольором обведення. Інші кольори зсуваються по колірному колу на стільки ж, на скільки ключовий колір, і зберігають насиченість та яскравість. + Roundness Округлість Roundness: Округлість: Fixed Фіксований Pressure Натиск @@ -2769,6 +2775,7 @@ diagnostics ui інтерфейс Line Properties: Властивості лінії: Line Length: Довжина лінії: Line Angle: Кут лінії: + Constrain Pie Angle Зберігати кут сектора Polygon Tool Інструмент «Багатокутник» Portrait Книжкова Power Saving (integrated) Енергозбереження (вбудована) @@ -2930,6 +2937,9 @@ digits Malayalam Малаялам Real World: Реальний світ: Real-time Drawing and Editing Малювання та редагування у реальному часі Use Monitor Profile for Canvas Використовувати профіль монітора для полотна + Refresh Monitor Profile Оновити профіль монітора +@msg turn on Use Monitor Profile for Canvas first спочатку увімкніть «Використовувати профіль монітора для полотна» +@msg this build doesn't read display profiles ця збірка не читає профілі дисплеїв The canvas is drawn in sRGB. Полотно відображається в sRGB. Canvas display profile: Профіль дисплея для полотна: The system matches the window to the display's colors. Система узгоджує кольори вікна з дисплеєм. @@ -3192,6 +3202,7 @@ digits Malayalam Малаялам The mouse wheel with Cmd/Ctrl held scrolls the canvas sideways. Колесо миші з натиснутою Cmd/Ctrl прокручує полотно по горизонталі. Dragging sideways on a numeric field's label changes the field's value. Перетягування вбік по підпису числового поля змінює значення поля. A two-finger rotate gesture on a trackpad rotates the canvas view. Жест обертання двома пальцями на трекпаді обертає вигляд полотна. + When you move anchor points, each curve with one moved end keeps its shape relative to its ends. Коли ви переміщуєте опорні точки, кожна крива з одним переміщеним кінцем зберігає форму відносно своїх кінців. Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Поки ви утримуєте клавішу інструмента, його вибрано, а після відпускання знову вибирається попередній інструмент. Shows the bounding box while you move the selection or draw a shape. Показує обмежувальну рамку, поки ви переміщуєте виділення або малюєте фігуру. Create Trim Marks draws Japanese-style marks instead of Roman ones. «Створити мітки підрізування» малює мітки в японському стилі замість західних. @@ -3503,6 +3514,11 @@ digits Malayalam Малаялам Search commands, tools, panels and effects… Пошук команд, інструментів, панелей та ефектів… No commands match Немає відповідних команд {pos} of {total}: {name} {pos} з {total}: {name} + No menu item Немає пункту меню + Toolbar Панель інструментів + {toolbar}, in the {tool} group {toolbar}, у групі «{tool}» + Tool Інструмент + Command Команда @plural {n} result|{n} results {n} результат|{n} результати|{n} результатів @plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} з {n} результату. Продовжуйте вводити, щоб звузити їх.|{shown} з {n} результатів. Продовжуйте вводити, щоб звузити їх.|{shown} з {n} результатів. Продовжуйте вводити, щоб звузити їх. Recent Commands Нещодавні команди @@ -4597,6 +4613,7 @@ imageTrace Outline Контур Bevel Скіс Offset Зміщення Axis Вісь + Axis Angle Кут осі axis Horizontal Горизонтальна axis Vertical Вертикальна axis Both Обидві @@ -5083,6 +5100,7 @@ liquify-list-end {0}, {1} {0} і {1} @msg choose a folder to export to виберіть папку для експорту @msg choose a location for the package виберіть розташування для пакета @msg clipboard is empty буфер обміну порожній +@msg colorTable.deleted: at least one color has to stay in the color table colorTable.deleted: у колірній таблиці має залишитися принаймні один колір @msg colorTable.{what}: `{h}` is not a colour such as "#ff8800" colorTable.{what}: `{h}` не є кольором, наприклад "#ff8800" @msg colorTable.{what}: at most {MAX_TABLE} colours colorTable.{what}: не більше {MAX_TABLE} кольорів @msg command `{0}` is not available right now: {1} команда `{0}` зараз недоступна: {1} @@ -5150,6 +5168,12 @@ liquify-list-end {0}, {1} {0} і {1} @msg no PNG encoder немає кодера PNG @msg no active document немає активного документа @msg no active perspective plane немає активної площини перспективи +@msg the perspective grid is hidden сітку перспективи приховано +@msg Automatic Plane Positioning is off: turn on anchorPoint or gridlineIntersection (perspective.widget.options) Автоматичне розміщення площини вимкнено: увімкніть anchorPoint або gridlineIntersection (perspective.widget.options) +@msg anchorPoint must be true or false anchorPoint має бути true або false +@msg gridlineIntersection must be true or false gridlineIntersection має бути true або false +@msg tolerance must be 0 or more tolerance має бути 0 або більше +@msg give `at` or `clear`, not both укажіть `at` або `clear`, але не обидва @msg no anchor points selected опорні точки не виділені @msg `points` must be two or three [x, y] pairs of numbers `points` має містити дві або три пари чисел [x, y] @msg direct-select two or three anchor points, or give `points` виділіть дві або три опорні точки прямим виділенням або задайте `points` @@ -5622,6 +5646,8 @@ variable-list-end {0}, {1} {0} і {1} @msg Reload the page to go on (changes not saved yet may be lost). Перезавантажте сторінку, щоб продовжити (незбережені зміни можуть бути втрачені). @msg tool (a tool id) is required потрібно tool (ідентифікатор інструменту) @msg {tool} isn't in a toolbar group of several tools {tool} не входить до групи панелі інструментів з кількох інструментів +@msg Presentation Mode hides the toolbars: change the screen mode to show them Режим презентації приховує панелі інструментів: щоб показати їх, змініть режим екрану +@msg Tab has hidden the toolbars: press Tab to show them клавіша Tab приховала панелі інструментів: щоб показати їх, натисніть Tab @msg onto must name a panel floating in another group onto має називати панель, що плаває в іншій групі @msg below and above must name a panel floating in another group below і above мають називати панель, що плаває в іншій групі @msg give only one of onto, below and above вкажіть лише один із onto, below і above @@ -5738,6 +5764,7 @@ variable-list-end {0}, {1} {0} і {1} @msg a linked JavaScript file is outside the read roots зв’язаний файл JavaScript перебуває поза кореневими папками для читання @msg a linked image file is outside the read roots зв’язаний файл зображення перебуває поза кореневими папками для читання @msg a linked file's export folder is outside the read roots папка експорту зв’язаного файлу перебуває поза кореневими папками для читання +@msg a linked file's editing data can't be read to check it against the read roots не вдається прочитати дані редагування зв’язаного файлу, щоб звірити їх із кореневими папками для читання @msg automation path rejected: outside the write root {root}: {path} шлях автоматизації відхилено: поза кореневою папкою для запису {root}: {path} @msg automation path rejected: outside the write roots {roots}: {path} шлях автоматизації відхилено: поза кореневими папками для запису {roots}: {path} @msg automation path rejected: path is empty шлях автоматизації відхилено: шлях порожній @@ -6018,6 +6045,7 @@ lighting Light Світло Cove Викружка Depth Глибина Front Спереду + Side Збоку Isometric Bottom Ізометрія знизу Isometric Left Ізометрія ліворуч Isometric Right Ізометрія праворуч @@ -6112,7 +6140,7 @@ lighting Light Світло @msg each of `{GRAPHICS}` must be an object кожен елемент `{GRAPHICS}` має бути об’єктом @msg `{GRAPHICS}` entries take symbol, face, x, y, scale and rotation, not `{k}` елементи `{GRAPHICS}` приймають symbol, face, x, y, scale і rotation, а не `{k}` @msg each of `{GRAPHICS}` needs `symbol`, the name of a symbol кожному елементу `{GRAPHICS}` потрібен `symbol`, назва символу -@msg `{GRAPHICS}` face must be front or back face у `{GRAPHICS}` має бути front або back +@msg `{GRAPHICS}` face must be front, back or side face у `{GRAPHICS}` має бути front, back або side @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} {key} у `{GRAPHICS}` має бути числом від {lo} до {hi} @msg `{GRAPHICS}` must be an array `{GRAPHICS}` має бути масивом @msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types Графіка наноситься на об’єкти типів «Площина», «Видавлювання», «Обертання» та «Надування» @@ -7360,6 +7388,14 @@ breakText Glyphs Гліфи Remove Gaps Прибрати проміжки @msg that makes too many pieces (at most 100000): make the dashes longer так вийде забагато частин (не більше 100000): подовжте штрихи @msg select paths, or segments, to divide виділіть контури або сегменти для розділення +# Path Precision Tools add-on: Smooth Bridge. + Smooth Bridge… Плавний міст… + Smooth Bridge Плавний міст + Keep Originals Зберегти оригінали +@msg select two circles to bridge виділіть два кола для з’єднання +@msg one circle is inside the other одне коло всередині іншого +@msg the circles are too far apart for this radius: raise the radius кола надто далеко одне від одного для цього радіуса: збільште радіус +@msg the circles are too far apart for this radius кола надто далеко одне від одного для цього радіуса # Path Precision Tools add-on: Common Tangents. Common Tangents… Спільні дотичні… Common Tangents Спільні дотичні @@ -7906,6 +7942,14 @@ breakText Glyphs Гліфи @msg `answers` has more than {MAX_ANSWERS} answers `answers` містить понад {MAX_ANSWERS} відповідей @msg `answers` is larger than 1 MiB `answers` більший за 1 МіБ @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` призначений лише для запуску, у якому немає кого запитати: у застосунку людина сама відповідає на кожне діалогове вікно +@msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` має бути цілим числом від 1 до {_1} +@msg `args{place}` is nested more than 64 levels deep `args{place}` має вкладеність понад 64 рівні +@msg `args` must be an object `args` має бути об’єктом +@msg `args` is larger than 1 MiB `args` більший за 1 МіБ +@msg `path` is empty параметр `path` порожній +@msg `installed` takes a `path`, not a `source` `installed` приймає `path`, а не `source` +@msg `path` must name a .js or .jsx file `path` має вказувати на файл .js або .jsx +@msg give exactly one of `path` and `source` укажіть рівно одне з: `path`, `source` @msg `answers` must be a list of answers `answers` має бути списком відповідей @msg `artboard` must be the index of an artboard of the document `artboard` має бути індексом монтажної області документа @msg `artboardsAt` must be [x, y] `artboardsAt` має бути [x, y] diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 3fc1d43619..5b84157a6c 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -157,6 +157,7 @@ Add Used Colors Thêm các màu đã dùng Additional Fonts Folder Thư mục phông bổ sung Additional Plug-ins Folder Thư mục plug-in bổ sung + Plug-in Instruction Budget Ngân sách lệnh của plug-in Adjust Adjoining Width Points Điều chỉnh các điểm chiều rộng kề nhau Incoming Phía vào Outgoing Phía ra @@ -317,6 +318,7 @@ font-technology Variable Biến thiên Average Trung bình Average… Trung bình… Axis Trục + Axis Angle Góc trục Axis side Mặt trục Axis: Trục: Back Sau @@ -941,6 +943,8 @@ font-technology Variable Biến thiên Delete Artboard Xóa bảng vẽ Delete Artboards Xóa các bảng vẽ Delete Brush Xóa cọ + Delete Color Xóa màu + Restore Generated Table Khôi phục bảng đã tạo Delete Character Style Xóa kiểu ký tự Delete Data Set Xóa tập dữ liệu Delete Design Xóa thiết kế @@ -1026,6 +1030,7 @@ font-technology Variable Biến thiên Direction Handles Tay nắm hướng Direction: Hướng: Disable Auto Add/Delete Tắt tự động thêm/xóa + Interpolate Control Points When Moving Anchors Nội suy tay nắm hướng khi di chuyển điểm neo Disable Opacity Mask Tắt mặt nạ độ mờ Discard Loại bỏ Preserve Bảo lưu @@ -1661,6 +1666,7 @@ file-filter Templates Mẫu Frequencies and angles are the output device's to apply. Tần số và góc do thiết bị đầu ra quyết định. Frequency Tần số Front Trước + Side Bên cạnh Frosted Sương mờ Full Document Toàn bộ tài liệu Full Screen Mode Chế độ toàn màn hình @@ -3087,6 +3093,7 @@ diagnostics ui giao diện Line Properties: Thuộc tính đường thẳng: Line Length: Độ dài đường thẳng: Line Angle: Góc đường thẳng: + Constrain Pie Angle Ràng buộc góc hình quạt Polygon Tool Công cụ Đa giác Portrait Đứng Portuguese Tiếng Bồ Đào Nha @@ -3254,6 +3261,9 @@ mark-style Japanese Kiểu Nhật Real World: Thực tế: Real-time Drawing and Editing Vẽ và chỉnh sửa theo thời gian thực Use Monitor Profile for Canvas Dùng hồ sơ màn hình cho vùng vẽ + Refresh Monitor Profile Làm mới hồ sơ màn hình +@msg turn on Use Monitor Profile for Canvas first hãy bật "Dùng hồ sơ màn hình cho vùng vẽ" trước +@msg this build doesn't read display profiles bản dựng này không đọc hồ sơ màn hình The canvas is drawn in sRGB. Vùng vẽ được hiển thị ở sRGB. Canvas display profile: Hồ sơ màn hình của vùng vẽ: The system matches the window to the display's colors. Hệ thống điều chỉnh cửa sổ theo màu của màn hình. @@ -3508,6 +3518,7 @@ mark-style Japanese Kiểu Nhật The mouse wheel with Cmd/Ctrl held scrolls the canvas sideways. Con lăn chuột kèm giữ Cmd/Ctrl cuộn khung vẽ sang ngang. Dragging sideways on a numeric field's label changes the field's value. Kéo sang ngang trên nhãn của một trường số sẽ thay đổi giá trị của trường. A two-finger rotate gesture on a trackpad rotates the canvas view. Cử chỉ xoay bằng hai ngón trên bàn di chuột sẽ xoay khung nhìn của khung vẽ. + When you move anchor points, each curve with one moved end keeps its shape relative to its ends. Khi bạn di chuyển điểm neo, mỗi đường cong có một đầu bị di chuyển sẽ giữ hình dạng so với các đầu của nó. Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. Giữ phím tắt của một công cụ sẽ chọn công cụ đó cho đến khi bạn thả ra, rồi công cụ trước đó được chọn lại. Shows the bounding box while you move the selection or draw a shape. Hiển thị hộp giới hạn khi bạn di chuyển vùng chọn hoặc vẽ một hình. Create Trim Marks draws Japanese-style marks instead of Roman ones. Tạo dấu cắt xén vẽ dấu kiểu Nhật thay cho kiểu La Mã. @@ -3640,6 +3651,7 @@ mark-style Japanese Kiểu Nhật Rotate… Xoay… Rotation Góc xoay Rotation relative to: Xoay tương đối với: + Hue Jitter: Biến thiên sắc độ: Rotation X Xoay X Rotation Y Xoay Y Rotation Z Xoay Z @@ -3658,6 +3670,7 @@ mark-style Japanese Kiểu Nhật Rounded Rectangle Hình chữ nhật bo góc Rounded Rectangle Tool Công cụ Hình chữ nhật bo góc Rounded Rectangle… Hình chữ nhật bo góc… + Roundness Độ tròn Roundness: Độ tròn: Row Size: Kích thước hàng: Rows Hàng @@ -3847,6 +3860,11 @@ mark-style Japanese Kiểu Nhật Search commands, tools, panels and effects… Tìm kiếm lệnh, công cụ, bảng và hiệu ứng… No commands match Không có lệnh nào khớp {pos} of {total}: {name} {pos} trên {total}: {name} + No menu item Không có mục menu + Toolbar Thanh công cụ + {toolbar}, in the {tool} group {toolbar}, trong nhóm {tool} + Tool Công cụ + Command Lệnh @plural {n} result|{n} results {n} kết quả @plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. {shown} trên {n} kết quả. Tiếp tục gõ để thu hẹp. Recent Commands Lệnh gần đây @@ -5051,6 +5069,7 @@ theme Appearance Giao diện @msg a linked JavaScript file is outside the read roots một tệp JavaScript được liên kết nằm ngoài các thư mục gốc đọc @msg a linked image file is outside the read roots một tệp hình ảnh được liên kết nằm ngoài các thư mục gốc đọc @msg a linked file's export folder is outside the read roots thư mục xuất của một tệp được liên kết nằm ngoài các thư mục gốc đọc +@msg a linked file's editing data can't be read to check it against the read roots không thể đọc dữ liệu chỉnh sửa của một tệp được liên kết để kiểm tra với các thư mục gốc đọc @msg the library's file is outside the read roots tệp của thư viện nằm ngoài các thư mục gốc đọc @msg {file} names more than one linked JavaScript file {file} khớp với nhiều hơn một tệp JavaScript được liên kết @msg automation path rejected: outside the write root {root}: {path} đường dẫn tự động bị từ chối: ngoài thư mục gốc ghi {root}: {path} @@ -5102,6 +5121,7 @@ theme Appearance Giao diện @msg choose the font files to add hãy chọn các tệp phông chữ để thêm @msg clipboard is empty khay nhớ tạm trống @msg closing needs three anchors đóng đường dẫn cần ba điểm neo +@msg colorTable.deleted: at least one color has to stay in the color table colorTable.deleted: phải giữ lại ít nhất một màu trong bảng màu @msg colorTable.{what}: `{h}` is not a colour such as "#ff8800" colorTable.{what}: `{h}` không phải là màu như "#ff8800" @msg colorTable.{what}: at most {MAX_TABLE} colours colorTable.{what}: tối đa {MAX_TABLE} màu @msg column must be true or a number from 1 column phải là true hoặc số từ 1 @@ -5293,6 +5313,14 @@ liquify-list-end {0}, {1} {0} và {1} @msg is a prompt's answer, whose `value` must be a string or null là câu trả lời cho prompt, nên `value` phải là chuỗi hoặc null @msg must have `kind` alert, confirm or prompt phải có `kind` là alert, confirm hoặc prompt @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` chỉ dành cho lần chạy không có ai để hỏi: trong ứng dụng, người dùng trả lời từng hộp thoại +@msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` phải là số nguyên từ 1 đến {_1} +@msg `args{place}` is nested more than 64 levels deep `args{place}` lồng sâu hơn 64 cấp +@msg `args` must be an object `args` phải là một đối tượng +@msg `args` is larger than 1 MiB `args` lớn hơn 1 MiB +@msg `path` is empty `path` trống +@msg `installed` takes a `path`, not a `source` `installed` nhận `path`, không nhận `source` +@msg `path` must name a .js or .jsx file `path` phải chỉ đến tệp .js hoặc .jsx +@msg give exactly one of `path` and `source` hãy cung cấp đúng một trong `path` và `source` @msg Running a script Đang chạy tập lệnh @msg Copied the script report Đã sao chép báo cáo script @msg Script file access denied: {path} Quyền truy cập tệp của tập lệnh bị từ chối: {path} @@ -5487,6 +5515,12 @@ liquify-list-end {0}, {1} {0} và {1} @msg name the file hãy đặt tên tệp @msg no active document không có tài liệu đang hoạt động @msg no active perspective plane không có mặt phẳng phối cảnh đang hoạt động +@msg the perspective grid is hidden lưới phối cảnh đang ẩn +@msg Automatic Plane Positioning is off: turn on anchorPoint or gridlineIntersection (perspective.widget.options) Tự động định vị mặt phẳng đang tắt: hãy bật anchorPoint hoặc gridlineIntersection (perspective.widget.options) +@msg anchorPoint must be true or false anchorPoint phải là true hoặc false +@msg gridlineIntersection must be true or false gridlineIntersection phải là true hoặc false +@msg tolerance must be 0 or more tolerance phải từ 0 trở lên +@msg give `at` or `clear`, not both hãy cung cấp `at` hoặc `clear`, không phải cả hai @msg no anchor points selected chưa chọn điểm neo @msg `points` must be two or three [x, y] pairs of numbers `points` phải là hai hoặc ba cặp số [x, y] @msg direct-select two or three anchor points, or give `points` hãy chọn trực tiếp hai hoặc ba điểm neo hoặc cung cấp `points` @@ -5919,7 +5953,7 @@ liquify-list-end {0}, {1} {0} và {1} @msg each of `{GRAPHICS}` must be an object mỗi mục của `{GRAPHICS}` phải là một đối tượng @msg `{GRAPHICS}` entries take symbol, face, x, y, scale and rotation, not `{k}` các mục của `{GRAPHICS}` nhận symbol, face, x, y, scale và rotation, không nhận `{k}` @msg each of `{GRAPHICS}` needs `symbol`, the name of a symbol mỗi mục của `{GRAPHICS}` cần `symbol`, tên của một ký hiệu -@msg `{GRAPHICS}` face must be front or back face của `{GRAPHICS}` phải là front hoặc back +@msg `{GRAPHICS}` face must be front, back or side face của `{GRAPHICS}` phải là front, back hoặc side @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} {key} của `{GRAPHICS}` phải là số từ {lo} đến {hi} @msg `{GRAPHICS}` must be an array `{GRAPHICS}` phải là một mảng @msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types Đồ họa được đặt lên các loại đối tượng Mặt phẳng, Kéo dài, Xoay tròn và Phình @@ -6192,6 +6226,8 @@ variable-list-end {0}, {1} {0} và {1} @msg {path}: {e} {path}: {e} @msg {status} ({e}) {status} ({e}) @msg {tool} isn't in a toolbar group of several tools {tool} không nằm trong nhóm thanh công cụ có nhiều công cụ +@msg Presentation Mode hides the toolbars: change the screen mode to show them Chế độ trình bày ẩn các thanh công cụ: hãy đổi chế độ màn hình để hiện chúng +@msg Tab has hidden the toolbars: press Tab to show them phím Tab đã ẩn các thanh công cụ: nhấn Tab để hiện chúng Load EPS into Clipboard Tải EPS vào bảng tạm @msg an image of {w} × {h} pixels is too large to draw ảnh {w} × {h} điểm ảnh quá lớn nên không thể vẽ @msg {path}: not a PNG, JPEG, WebP, TIFF or BMP image {path}: không phải ảnh PNG, JPEG, WebP, TIFF hay BMP @@ -7396,6 +7432,14 @@ breakText Glyphs Glyph Remove Gaps Gỡ các khoảng hở @msg that makes too many pieces (at most 100000): make the dashes longer như vậy tạo ra quá nhiều mảnh (tối đa 100000): hãy kéo dài nét @msg select paths, or segments, to divide chọn các đường dẫn hoặc đoạn để chia +# Path Precision Tools add-on: Smooth Bridge. + Smooth Bridge… Cầu nối mượt… + Smooth Bridge Cầu nối mượt + Keep Originals Giữ bản gốc +@msg select two circles to bridge chọn hai hình tròn để nối +@msg one circle is inside the other một hình tròn nằm bên trong hình tròn kia +@msg the circles are too far apart for this radius: raise the radius các hình tròn cách nhau quá xa so với bán kính này: hãy tăng bán kính +@msg the circles are too far apart for this radius các hình tròn cách nhau quá xa so với bán kính này # Path Precision Tools add-on: Common Tangents. Common Tangents… Tiếp tuyến chung… Common Tangents Tiếp tuyến chung diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 981f16d4a9..d28e8a698f 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -90,6 +90,7 @@ Add to Swatches 添加到色板 Add Used Colors 添加已用颜色 Additional Plug-ins Folder 附加增效工具文件夹 + Plug-in Instruction Budget 增效工具指令预算 Additional Fonts Folder 附加字体文件夹 Adjust Adjoining Width Points 调整相邻宽度点 Incoming 入侧 @@ -760,6 +761,8 @@ antiAlias Sharp 锐利 Delete Artboard 删除画板 Delete Artboards 删除画板 Delete Brush 删除画笔 + Delete Color 删除颜色 + Restore Generated Table 恢复生成的颜色表 Delete Character Style 删除字符样式 Delete Empty Artboards 删除空白画板 Delete Freeform Point 删除自由点 @@ -827,6 +830,7 @@ antiAlias Sharp 锐利 Direct Selection Tool 直接选择工具 Direction Handles 方向手柄 Disable Auto Add/Delete 禁用自动添加/删除锚点 + Interpolate Control Points When Moving Anchors 移动锚点时插值方向手柄 Disable Opacity Mask 禁用不透明度蒙版 Discard 不存储 Discard Empty Type 丢弃空文字 @@ -2164,6 +2168,7 @@ file-filter Templates 模板 Scatter: 散布: Rotation: 旋转: Rotation relative to: 旋转相对于: + Hue Jitter: 色相抖动: Brush Scale Options 画笔缩放选项 Scale Proportionately 等比缩放 Stretch to Fit Stroke Length 伸展以适合描边长度 @@ -2190,6 +2195,7 @@ file-filter Templates 模板 Approximate path 近似路径 Colorization 着色 Key Color: 主色: + Roundness 圆度 Roundness: 圆度: Fixed 固定 Pressure 压力 @@ -2628,6 +2634,7 @@ diagnostics ui 界面 Line Properties: 直线属性: Line Length: 直线长度: Line Angle: 直线角度: + Constrain Pie Angle 约束扇形角度 Polygon Tool 多边形工具 Portrait 纵向 Portuguese 葡萄牙语 @@ -2790,6 +2797,9 @@ digits Malayalam 马拉雅拉姆数字 Real World: 真实世界: Real-time Drawing and Editing 实时绘图和编辑 Use Monitor Profile for Canvas 画布使用显示器配置文件 + Refresh Monitor Profile 刷新显示器配置文件 +@msg turn on Use Monitor Profile for Canvas first 请先打开“画布使用显示器配置文件” +@msg this build doesn't read display profiles 此版本不读取显示器配置文件 The canvas is drawn in sRGB. 画布以 sRGB 绘制。 Canvas display profile: 画布显示配置文件: The system matches the window to the display's colors. 系统会使窗口匹配显示器的颜色。 @@ -3049,6 +3059,7 @@ digits Malayalam 马拉雅拉姆数字 The mouse wheel with Cmd/Ctrl held scrolls the canvas sideways. 按住 Cmd/Ctrl 滚动鼠标滚轮会横向滚动画布。 Dragging sideways on a numeric field's label changes the field's value. 在数值字段的标签上横向拖动可更改字段的值。 A two-finger rotate gesture on a trackpad rotates the canvas view. 在触控板上用双指旋转手势可旋转画布视图。 + When you move anchor points, each curve with one moved end keeps its shape relative to its ends. 移动锚点时,只有一端移动的每条曲线都会保持其相对于两端的形状。 Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. 按住工具的快捷键时选择该工具,松开后重新选择之前的工具。 Shows the bounding box while you move the selection or draw a shape. 移动所选对象或绘制形状时显示定界框。 Create Trim Marks draws Japanese-style marks instead of Roman ones. 创建裁切标记绘制日式标记,而不是西式标记。 @@ -3328,6 +3339,9 @@ digits Malayalam 马拉雅拉姆数字 Search commands, tools, panels and effects… 搜索命令、工具、面板和效果… No commands match 没有匹配的命令 {pos} of {total}: {name} 第 {pos} 个,共 {total} 个:{name} + No menu item 无菜单项 + Toolbar 工具栏 + {toolbar}, in the {tool} group {toolbar},位于 {tool} 组中 @plural {n} result|{n} results {n} 个结果 @plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. 共 {n} 个结果,显示 {shown} 个。继续输入以缩小范围。 Recent Commands 最近使用的命令 @@ -4754,6 +4768,7 @@ imageTrace Outline 轮廓 @msg Create Outlines: select text objects 创建轮廓:请选择文本对象 @msg paste unavailable 无法粘贴 @msg Save for Web: the image is empty 存储为 Web 所用格式:图像为空 +@msg colorTable.deleted: at least one color has to stay in the color table colorTable.deleted:颜色表中至少要保留一种颜色 @msg colorTable.{what}: `{h}` is not a colour such as "#ff8800" colorTable.{what}:`{h}` 不是颜色,例如 "#ff8800" @msg colorTable.{what}: at most {MAX_TABLE} colours colorTable.{what}:最多 {MAX_TABLE} 种颜色 @msg no artboard {i} (0-based; the document has {_1}) 没有画板 {i} (从 0 开始计数;文档有 {_1} 个) @@ -4990,6 +5005,12 @@ imageTrace Outline 轮廓 @msg no preset editor 没有预设编辑器 @msg no perspective grid preset named `{name}` 没有名为 `{name}` 的透视网格预设 @msg no active perspective plane 没有活动的透视平面 +@msg the perspective grid is hidden 透视网格已隐藏 +@msg Automatic Plane Positioning is off: turn on anchorPoint or gridlineIntersection (perspective.widget.options) 自动平面定位已关闭:请打开 anchorPoint 或 gridlineIntersection (perspective.widget.options) +@msg anchorPoint must be true or false anchorPoint 必须为 true 或 false +@msg gridlineIntersection must be true or false gridlineIntersection 必须为 true 或 false +@msg tolerance must be 0 or more tolerance 必须大于或等于 0 +@msg give `at` or `clear`, not both 请给出 `at` 或 `clear`,不能两者都给 @msg plane must be left, right or ground plane 必须是 left、right 或 ground @msg missing `id` (see plugin.list) 缺少 `id` (请参阅 plugin.list) @msg no plug-in {id} is installed 未安装增效工具 {id} @@ -5419,6 +5440,8 @@ liquify-list-end {0}, {1} {0}和{1} @msg the {tool} tool has no options {tool} 工具没有选项 @msg unknown tool `{tool}` 未知工具 `{tool}` @msg {tool} isn't in a toolbar group of several tools {tool} 不在包含多个工具的工具栏组中 +@msg Presentation Mode hides the toolbars: change the screen mode to show them 演示模式会隐藏工具栏:请更改屏幕模式以显示工具栏 +@msg Tab has hidden the toolbars: press Tab to show them Tab 已隐藏工具栏:请按 Tab 以显示工具栏 @msg no such document 没有此文档 @msg {_1}: not saved, so not closed {_1}:未保存,因此未关闭 @msg `{name}` is a built-in workspace; choose another name `{name}` 是内置工作区;请选择其他名称 @@ -5468,6 +5491,7 @@ liquify-list-end {0}, {1} {0}和{1} @msg a linked JavaScript file is outside the read roots 链接的 JavaScript 文件位于所有读取根目录之外 @msg a linked image file is outside the read roots 链接的图像文件位于所有读取根目录之外 @msg a linked file's export folder is outside the read roots 链接文件的导出文件夹位于所有读取根目录之外 +@msg a linked file's editing data can't be read to check it against the read roots 无法读取链接文件的编辑数据,因此无法对照读取根目录进行检查 @msg automation path rejected: outside the write root {root}: {path} 已拒绝自动化路径:位于写入根目录 {root} 之外:{path} @msg automation path rejected: outside the write roots {roots}: {path} 已拒绝自动化路径:位于所有写入根目录 {roots} 之外:{path} @msg automation path rejected: path is empty 已拒绝自动化路径:路径为空 @@ -5977,6 +6001,7 @@ font-technology Variable 可变 Bevel 斜角 Offset 偏移 Axis 轴 + Axis Angle 轴角度 axis Horizontal 水平 axis Vertical 垂直 axis Both 两者 @@ -6290,6 +6315,7 @@ lighting Light 光源 Cove 凹圆 Depth 深度 Front 正面 + Side 侧面 Isometric Bottom 等角底部 Isometric Left 等角左侧 Isometric Right 等角右侧 @@ -6384,7 +6410,7 @@ lighting Light 光源 @msg each of `{GRAPHICS}` must be an object `{GRAPHICS}` 的每个条目必须是对象 @msg `{GRAPHICS}` entries take symbol, face, x, y, scale and rotation, not `{k}` `{GRAPHICS}` 的条目接受 symbol、face、x、y、scale 和 rotation,不接受 `{k}` @msg each of `{GRAPHICS}` needs `symbol`, the name of a symbol `{GRAPHICS}` 的每个条目都需要 `symbol`,即符号的名称 -@msg `{GRAPHICS}` face must be front or back `{GRAPHICS}` 的 face 必须是 front 或 back +@msg `{GRAPHICS}` face must be front, back or side `{GRAPHICS}` 的 face 必须是 front、back 或 side @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} `{GRAPHICS}` 的 {key} 必须是 {lo} 到 {hi} 之间的数字 @msg `{GRAPHICS}` must be an array `{GRAPHICS}` 必须是数组 @msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types 图形映射到平面、突出、回转和膨胀对象类型上 @@ -7590,6 +7616,14 @@ breakText Glyphs 字形 Remove Gaps 移除间隙 @msg that makes too many pieces (at most 100000): make the dashes longer 这会产生过多片段(最多 100000 个):请加长短划线 @msg select paths, or segments, to divide 请选择要分割的路径或线段 +# Path Precision Tools add-on: Smooth Bridge. + Smooth Bridge… 平滑桥接… + Smooth Bridge 平滑桥接 + Keep Originals 保留原稿 +@msg select two circles to bridge 请选择两个要桥接的圆 +@msg one circle is inside the other 一个圆位于另一个圆内部 +@msg the circles are too far apart for this radius: raise the radius 对于此半径,两个圆相距太远:请增大半径 +@msg the circles are too far apart for this radius 对于此半径,两个圆相距太远 # Path Precision Tools add-on: Common Tangents. Common Tangents… 公切线… Common Tangents 公切线 @@ -7962,6 +7996,14 @@ breakText Glyphs 字形 @msg `answers` has more than {MAX_ANSWERS} answers `answers` 中的回答超过 {MAX_ANSWERS} 个 @msg `answers` is larger than 1 MiB `answers` 大于 1 MiB @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` 仅用于无人可问的运行:在应用中,由用户回答每个对话框 +@msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` 必须是 1 到 {_1} 之间的整数 +@msg `args{place}` is nested more than 64 levels deep `args{place}` 的嵌套超过 64 层 +@msg `args` must be an object `args` 必须是对象 +@msg `args` is larger than 1 MiB `args` 大于 1 MiB +@msg `path` is empty `path` 为空 +@msg `installed` takes a `path`, not a `source` `installed` 需要 `path`,而不是 `source` +@msg `path` must name a .js or .jsx file `path` 必须指向 .js 或 .jsx 文件 +@msg give exactly one of `path` and `source` `path` 和 `source` 中必须且只能给出一个 @msg `answers` must be a list of answers `answers` 必须是回答的列表 @msg `artboard` must be the index of an artboard of the document `artboard` 必须是文档中某个画板的索引 @msg `artboardsAt` must be [x, y] `artboardsAt` 必须是 [x, y] diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index cfff314fe9..9627f43344 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -99,6 +99,7 @@ Add to Swatches 新增至色票 Add Used Colors 新增使用中的顏色 Additional Plug-ins Folder 額外的增效模組資料夾 + Plug-in Instruction Budget 增效模組指令預算 Additional Fonts Folder 額外的字體資料夾 Adjust Adjoining Width Points 調整相鄰寬度點 Incoming 入側 @@ -780,6 +781,8 @@ font-technology Variable 可變 Delete Artboard 刪除工作區域 Delete Artboards 刪除工作區域 Delete Brush 刪除筆刷 + Delete Color 刪除顏色 + Restore Generated Table 還原產生的色彩表 Delete Character Style 刪除字元樣式 Delete Empty Artboards 刪除空白工作區域 Delete Freeform Point 刪除任意形狀錨點 @@ -848,6 +851,7 @@ font-technology Variable 可變 Direct Selection Tool 直接選取工具 Direction Handles 控制把手 Disable Auto Add/Delete 停用自動增加/刪除 + Interpolate Control Points When Moving Anchors 移動錨點時內插控制把手 Disable Opacity Mask 停用不透明度遮色片 Discard 捨棄 Preserve 保留 @@ -2230,6 +2234,7 @@ file-filter Templates 範本 @msg Create Outlines: select text objects 建立外框:請選取文字物件 @msg paste unavailable 無法貼上 @msg Save for Web: the image is empty 儲存為網頁用:影像是空的 +@msg colorTable.deleted: at least one color has to stay in the color table colorTable.deleted:色彩表中至少要保留一種顏色 @msg colorTable.{what}: `{h}` is not a colour such as "#ff8800" colorTable.{what}:`{h}` 不是像 "#ff8800" 這樣的顏色 @msg colorTable.{what}: at most {MAX_TABLE} colours colorTable.{what}:最多 {MAX_TABLE} 種顏色 @msg no artboard {i} (0-based; the document has {_1}) 沒有工作區域 {i} (從 0 起算;文件有 {_1} 個) @@ -2469,6 +2474,12 @@ file-filter Templates 範本 @msg no preset editor 沒有預設集編輯器 @msg no perspective grid preset named `{name}` 沒有名為 `{name}` 的透視格點預設集 @msg no active perspective plane 沒有作用中的透視平面 +@msg the perspective grid is hidden 透視格點已隱藏 +@msg Automatic Plane Positioning is off: turn on anchorPoint or gridlineIntersection (perspective.widget.options) 「自動平面定位」已關閉:請開啟 anchorPoint 或 gridlineIntersection (perspective.widget.options) +@msg anchorPoint must be true or false anchorPoint 必須是 true 或 false +@msg gridlineIntersection must be true or false gridlineIntersection 必須是 true 或 false +@msg tolerance must be 0 or more tolerance 必須大於或等於 0 +@msg give `at` or `clear`, not both 請提供 `at` 或 `clear`,不能同時提供兩者 @msg plane must be left, right or ground plane 必須是 left、right 或 ground @msg missing `id` (see plugin.list) 未提供 `id` (請參閱 plugin.list) @msg no plug-in {id} is installed 未安裝增效模組 {id} @@ -2783,6 +2794,14 @@ liquify-list-end {0}, {1} {0}和{1} @msg the main script engine is new for each run and is never kept, so it cannot be dropped 主指令碼引擎在每次執行時都是新的,從不保留,因此無法捨棄 @msg there is no script engine named {name} 沒有名為 {name} 的指令碼引擎 @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` 僅適用於沒有人可詢問的執行:在應用程式中,由使用者回答每個對話框 +@msg `maxFuel` must be a whole number from 1 to {_1} `maxFuel` 必須是 1 到 {_1} 之間的整數 +@msg `args{place}` is nested more than 64 levels deep `args{place}` 的巢狀層次超過 64 層 +@msg `args` must be an object `args` 必須是物件 +@msg `args` is larger than 1 MiB `args` 大於 1 MiB +@msg `path` is empty `path` 為空 +@msg `installed` takes a `path`, not a `source` `installed` 需要 `path`,而不是 `source` +@msg `path` must name a .js or .jsx file `path` 必須指向 .js 或 .jsx 檔案 +@msg give exactly one of `path` and `source` `path` 和 `source` 請只提供其中一個 @msg Running a script 正在執行指令碼 @msg Copied the script report 已複製指令碼報告 @msg Script file access denied: {path} 指令碼的檔案存取遭拒:{path} @@ -2899,6 +2918,8 @@ liquify-list-end {0}, {1} {0}和{1} @msg the {tool} tool has no options {tool} 工具沒有選項 @msg unknown tool `{tool}` 未知的工具 `{tool}` @msg {tool} isn't in a toolbar group of several tools {tool} 不在包含多個工具的工具列群組中 +@msg Presentation Mode hides the toolbars: change the screen mode to show them 簡報模式會隱藏工具列:請變更螢幕模式以顯示工具列 +@msg Tab has hidden the toolbars: press Tab to show them Tab 已隱藏工具列:請按 Tab 以顯示工具列 @msg no such document 沒有這個文件 @msg {_1}: not saved, so not closed {_1}:未儲存,因此未關閉 @msg `{name}` is a built-in workspace; choose another name `{name}` 是內建工作區;請選擇其他名稱 @@ -2940,6 +2961,7 @@ liquify-list-end {0}, {1} {0}和{1} @msg a linked JavaScript file is outside the read roots 連結的 JavaScript 檔案位於所有讀取根目錄之外 @msg a linked image file is outside the read roots 連結的影像檔案位於所有讀取根目錄之外 @msg a linked file's export folder is outside the read roots 連結檔案的匯出資料夾位於所有讀取根目錄之外 +@msg a linked file's editing data can't be read to check it against the read roots 無法讀取連結檔案的編輯資料,因此無法對照讀取根目錄進行檢查 @msg automation path rejected: outside the write root {root}: {path} 已拒絕自動化路徑:位於寫入根目錄 {root} 之外:{path} @msg automation path rejected: outside the write roots {roots}: {path} 已拒絕自動化路徑:位於所有寫入根目錄 {roots} 之外:{path} @msg automation path rejected: path is empty 已拒絕自動化路徑:路徑是空的 @@ -3473,6 +3495,7 @@ liquify-list-end {0}, {1} {0}和{1} Scatter: 散佈: Rotation: 旋轉: Rotation relative to: 旋轉相對於: + Hue Jitter: 色相抖動: Brush Scale Options 筆刷縮放選項 Scale Proportionately 等比例縮放 Stretch to Fit Stroke Length 延伸以符合筆畫長度 @@ -3509,6 +3532,7 @@ liquify-list-end {0}, {1} {0}和{1} Black becomes the stroke color and white stays white. Other colors become tints of the stroke color by their lightness. 黑色變為筆畫顏色,白色維持白色。其他顏色變為筆畫顏色的淺色,顏色越淺,淺色就越淺。 Black and white stay as they are. Dark colors become shades of the stroke color and light colors become tints of it. 黑色維持黑色,白色維持白色。其他顏色較暗時變為筆畫顏色的暗色,較亮時變為筆畫顏色的淺色。 The key color becomes the stroke color. The other colors shift their hue by the same amount and keep their saturation and brightness. 主要顏色變為筆畫顏色。其他顏色在色輪上移動與主要顏色相同的距離,並保留其飽和度和亮度。 + Roundness 圓度 Roundness: 圓度: Fixed 固定 Pressure 壓力 @@ -3953,6 +3977,7 @@ diagnostics ui 介面 Line Properties: 直線內容: Line Length: 直線長度: Line Angle: 直線角度: + Constrain Pie Angle 強制扇形角度 Polygon Tool 多邊形工具 Portrait 直向 Power Saving (integrated) 節能 (內建顯示晶片) @@ -4117,6 +4142,9 @@ digits Malayalam 馬來亞拉姆數字 Real World: 真實世界: Real-time Drawing and Editing 即時繪圖與編輯 Use Monitor Profile for Canvas 畫布使用顯示器描述檔 + Refresh Monitor Profile 重新整理顯示器描述檔 +@msg turn on Use Monitor Profile for Canvas first 請先開啟「畫布使用顯示器描述檔」 +@msg this build doesn't read display profiles 此版本不讀取顯示器描述檔 The canvas is drawn in sRGB. 畫布以 sRGB 繪製。 Canvas display profile: 畫布顯示描述檔: The system matches the window to the display's colors. 系統會讓視窗符合顯示器的色彩。 @@ -4379,6 +4407,7 @@ digits Malayalam 馬來亞拉姆數字 The mouse wheel with Cmd/Ctrl held scrolls the canvas sideways. 按住 Cmd/Ctrl 捲動滑鼠滾輪會橫向捲動畫布。 Dragging sideways on a numeric field's label changes the field's value. 在數值欄位的標籤上橫向拖曳可變更欄位的值。 A two-finger rotate gesture on a trackpad rotates the canvas view. 在觸控式軌跡板上以雙指旋轉手勢可旋轉畫布檢視。 + When you move anchor points, each curve with one moved end keeps its shape relative to its ends. 移動錨點時,只有一端移動的每條曲線都會保持其相對於兩端的形狀。 Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again. 按住工具的快速鍵時選擇該工具,放開後重新選擇之前的工具。 Shows the bounding box while you move the selection or draw a shape. 移動選取範圍或繪製形狀時顯示邊框。 Create Trim Marks draws Japanese-style marks instead of Roman ones. 建立剪裁標記繪製日式標記,而不是西式標記。 @@ -4688,6 +4717,11 @@ digits Malayalam 馬來亞拉姆數字 Search commands, tools, panels and effects… 搜尋指令、工具、面板與效果… No commands match 沒有符合的指令 {pos} of {total}: {name} 第 {pos} 個,共 {total} 個:{name} + No menu item 無選單項目 + Toolbar 工具列 + {toolbar}, in the {tool} group {toolbar},位於 {tool} 群組中 + Tool 工具 + Command 指令 @plural {n} result|{n} results {n} 個結果 @plural {shown} of {n} result. Keep typing to narrow them.|{shown} of {n} results. Keep typing to narrow them. 共 {n} 個結果,顯示 {shown} 個。繼續輸入以縮小範圍。 Recent Commands 最近使用的指令 @@ -5807,6 +5841,7 @@ imageTrace Outline 輪廓 Bevel 斜角 Offset 位移 Axis 軸 + Axis Angle 軸角度 axis Horizontal 水平 axis Vertical 垂直 axis Both 兩者 @@ -6128,6 +6163,7 @@ lighting Light 光源 Cove 凹圓 Depth 深度 Front 正面 + Side 側面 Isometric Bottom 等角底部 Isometric Left 等角左側 Isometric Right 等角右側 @@ -6222,7 +6258,7 @@ lighting Light 光源 @msg each of `{GRAPHICS}` must be an object `{GRAPHICS}` 的每個項目都必須是物件 @msg `{GRAPHICS}` entries take symbol, face, x, y, scale and rotation, not `{k}` `{GRAPHICS}` 的項目接受 symbol、face、x、y、scale 和 rotation,不接受 `{k}` @msg each of `{GRAPHICS}` needs `symbol`, the name of a symbol `{GRAPHICS}` 的每個項目都需要 `symbol`,也就是符號的名稱 -@msg `{GRAPHICS}` face must be front or back `{GRAPHICS}` 的 face 必須是 front 或 back +@msg `{GRAPHICS}` face must be front, back or side `{GRAPHICS}` 的 face 必須是 front、back 或 side @msg `{GRAPHICS}` {key} must be a number from {lo} to {hi} `{GRAPHICS}` 的 {key} 必須是介於 {lo} 到 {hi} 之間的數字 @msg `{GRAPHICS}` must be an array `{GRAPHICS}` 必須是陣列 @msg Graphics map onto the Plane, Extrude, Revolve and Inflate object types 圖形會對應到「平面」、「突出」、「迴轉」與「膨脹」物件類型 @@ -7401,6 +7437,14 @@ breakText Glyphs 字符 Remove Gaps 移除間隙 @msg that makes too many pieces (at most 100000): make the dashes longer 這會產生過多片段(最多 100000 個):請加長短破折號 @msg select paths, or segments, to divide 請選取要分割的路徑或線段 +# Path Precision Tools add-on: Smooth Bridge. + Smooth Bridge… 平滑橋接… + Smooth Bridge 平滑橋接 + Keep Originals 保留原始物件 +@msg select two circles to bridge 請選取兩個要橋接的圓形 +@msg one circle is inside the other 一個圓形位於另一個圓形內 +@msg the circles are too far apart for this radius: raise the radius 就此半徑而言,兩個圓形相距太遠:請增加半徑 +@msg the circles are too far apart for this radius 就此半徑而言,兩個圓形相距太遠 # Path Precision Tools add-on: Common Tangents. Common Tangents… 公切線… Common Tangents 公切線 diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index d94c4082e6..6adb103f1f 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -37,9 +37,6 @@ fn cp(label: &'static str, id: &'static str, p: Value) -> Item { fn todo(label: &'static str) -> Item { Item::Todo(label, "") } -fn todos(label: &'static str, sc: &'static str) -> Item { - Item::Todo(label, sc) -} fn sub(label: &'static str, items: Vec) -> Item { Item::Sub(label, items) } @@ -64,8 +61,11 @@ pub(crate) use bar::{home_key, home_showing}; #[cfg(test)] use bar::{menu_body, pointer_reaches_title}; pub use context::{context_items, context_menu_body, ruler_menu_body, ruler_unit_items}; +#[cfg(test)] +use entries::flatten; pub use entries::{ - InsertableItem, MenuEntry, Row, context_entries, entry, insertable, insertable_items, menu_entries, plays_in_app, pretty_shortcut, shown_shortcut, + InsertableItem, MenuEntry, Row, context_entries, entry, insertable, insertable_items, menu_entries, plays_in_app, pretty_shortcut, shown_label, + shown_shortcut, }; pub(crate) use invoke::graph_dialog; #[cfg(test)] diff --git a/crates/ui-egui/src/menus/entries.rs b/crates/ui-egui/src/menus/entries.rs index 953b5b58f4..8c92fbc071 100644 --- a/crates/ui-egui/src/menus/entries.rs +++ b/crates/ui-egui/src/menus/entries.rs @@ -53,11 +53,7 @@ pub fn entry<'a>(app: &VectorcraftApp, it: &'a Item) -> Option> { Entry::Item(Row { command: Some((id, p)), source: label, - label: effect_item_label(id, p) - .or_else(|| unlock_item_label(app, id, p, crate::i18n::current())) - .or_else(|| spelling_item_label(id, p)) - .unwrap_or_else(|| display_label(app, id, label)) - .into(), + label: shown_label(app, id, p, label).into(), shortcut: item_shortcut(id, p), enabled, checked, @@ -66,6 +62,16 @@ pub fn entry<'a>(app: &VectorcraftApp, it: &'a Item) -> Option> { }) } +/// The label of the menu item that runs `id` with `p` and reads `label` in English, as the menus +/// draw it in the UI language: an effect's own name (Pathfinder › Add), an object's name, a +/// spelling suggestion, or [`display_label`]. +pub fn shown_label(app: &VectorcraftApp, id: &str, p: &Value, label: &str) -> String { + effect_item_label(id, p) + .or_else(|| unlock_item_label(app, id, p, crate::i18n::current())) + .or_else(|| spelling_item_label(id, p)) + .unwrap_or_else(|| display_label(app, id, label)) +} + /// `Cmd+Shift+]` → `⇧⌘]` on macOS, `Ctrl+Shift+]` elsewhere. pub fn pretty_shortcut(s: &str) -> String { if s.is_empty() { @@ -109,13 +115,17 @@ pub struct MenuEntry { pub params: Value, pub enabled: bool, pub shortcut: String, + /// `path` as the menus draw it in the UI language: a plug-in's submenu and a Scripts folder + /// keep their names. + #[serde(skip)] + pub shown_path: Vec, } /// Flattened menu for `ui.menu.list`. pub fn menu_entries(app: &VectorcraftApp) -> Vec { let mut out = vec![]; for (title, items) in menu_tree_named(app.session.prefs.font_names_in_english) { - flatten(app, vec![title.to_string()], &items, &mut out); + flatten(app, vec![title.to_string()], vec![crate::i18n::t(title).to_string()], &items, &mut out); } out } @@ -123,7 +133,7 @@ pub fn menu_entries(app: &VectorcraftApp) -> Vec { /// Flattened canvas context menu for `ui.contextMenu.list` (paths are its submenus). pub fn context_entries(app: &VectorcraftApp) -> Vec { let mut out = vec![]; - flatten(app, vec![], &context_items(app), &mut out); + flatten(app, vec![], vec![], &context_items(app), &mut out); out } @@ -245,7 +255,7 @@ pub fn insertable_items(english_names: bool) -> Vec { out } -fn flatten(app: &VectorcraftApp, path: Vec, items: &[Item], out: &mut Vec) { +pub(super) fn flatten(app: &VectorcraftApp, path: Vec, shown: Vec, items: &[Item], out: &mut Vec) { for it in items { match it { Item::Cmd(l, id, p) => { @@ -266,6 +276,7 @@ fn flatten(app: &VectorcraftApp, path: Vec, items: &[Item], out: &mut Ve params: p.clone(), enabled, shortcut: item_shortcut(id, p).or_else(|| shortcut_of(id)).unwrap_or("").to_string(), + shown_path: shown.clone(), }) } Item::Todo(l, sc) => out.push(MenuEntry { @@ -275,11 +286,16 @@ fn flatten(app: &VectorcraftApp, path: Vec, items: &[Item], out: &mut Ve params: Value::Null, enabled: false, shortcut: sc.to_string(), + shown_path: shown.clone(), }), Item::Sub(l, ch) => { let mut p = path.clone(); p.push(l.to_string()); - flatten(app, p, ch, out); + // The menus draw a plug-in's submenu and a Scripts folder by their own names ([`entry`]). + let mut s = shown.clone(); + let own = super::labels::holds_plugin_commands(ch) || crate::scripts_menu::is_folder(ch); + s.push(if own { l.to_string() } else { crate::i18n::t(l).to_string() }); + flatten(app, p, s, ch, out); } _ => {} } diff --git a/crates/ui-egui/src/menus/invoke.rs b/crates/ui-egui/src/menus/invoke.rs index 996622040a..29cb15df0b 100644 --- a/crates/ui-egui/src/menus/invoke.rs +++ b/crates/ui-egui/src/menus/invoke.rs @@ -55,7 +55,7 @@ pub(super) fn menu_dialog(app: &VectorcraftApp, id: &str) -> Option<(&'static st // Transform Each opens on the values it was last confirmed with (#1732). "object.transformEach" => (crate::dialogs::transform_each::KIND, crate::dialogs::transform_each::open_fields(app)), "object.reflect" => ("reflect", json!({"axis": "vertical", "angle": 90})), - "object.shear" => ("shear", json!({"angle": 0, "axis": "horizontal"})), + "object.shear" => ("shear", json!({"angle": 0, "axis": "horizontal", "axisAngle": 0})), "path.average" => ("average", json!({"axis": "both"})), // Average & Join opens on the joined anchor chosen last (Corner the first time). "path.averageJoin" if app.ui.average_join.is_object() => ("averageJoin", app.ui.average_join.clone()), @@ -79,6 +79,7 @@ pub(super) fn menu_dialog(app: &VectorcraftApp, id: &str) -> Option<(&'static st (crate::addons::pathtools::set_corners::KIND, crate::addons::pathtools::set_corners::fields(app)) } crate::addons::pathtools::dashes::COMMAND => (crate::addons::pathtools::dashes::KIND, crate::addons::pathtools::dashes::fields()), + crate::addons::pathtools::bridge::COMMAND => (crate::addons::pathtools::bridge::KIND, crate::addons::pathtools::bridge::fields()), crate::addons::pathtools::tangent_circle::COMMAND => { (crate::addons::pathtools::tangent_circle::KIND, crate::addons::pathtools::tangent_circle::fields(app)) } diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index f21524ddf6..d5ec92b934 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -115,6 +115,7 @@ pub fn run_ui_command(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option Option app.display_profile.request_read(app.session.prefs.monitor_profile_display).map(|()| { + if let Some(ctx) = &app.ui_ctx { + ctx.request_repaint(); + } + json!({ "requested": true }) + }), // Outline or Preview is a setting of the active document's view. "view.outline" => match app.view_mut() { Some(v) => flag(&mut v.outline), @@ -787,10 +795,17 @@ fn run_ui_part7(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option edit.unwrap_or(false), Err(e) => return Some(Err(e)), }; + let keep_art = match opt_bool(p, "keepArt") { + Ok(keep) => keep.unwrap_or(false), + Err(e) => return Some(Err(e)), + }; if edit || name.is_some() { + if keep_art { + return Some(Err("`keepArt` applies only to a new symbol".into())); + } crate::dialogs::symbol_options::open_edit(app, name.as_deref()) } else { - crate::dialogs::symbol_options::open(app) + crate::dialogs::symbol_options::open(app, keep_art) } } "ui.newBrush" => crate::dialogs::new_brush::open(app, p.get("ids").cloned()), diff --git a/crates/ui-egui/src/menus/state.rs b/crates/ui-egui/src/menus/state.rs index 2bb28300df..36dcdfc1d4 100644 --- a/crates/ui-egui/src/menus/state.rs +++ b/crates/ui-egui/src/menus/state.rs @@ -324,6 +324,7 @@ pub fn enabled(app: &VectorcraftApp, id: &str) -> bool { "file.exportSelection" => app.session.active().is_some_and(|d| !d.selection.is_empty()), "css.copy" | "css.exportFile" => app.session.active().is_some(), "print.printerSetup" => app.services.print.as_ref().is_some_and(|s| s.has_setup()), + "view.refreshMonitorProfile" => app.session.prefs.monitor_profile_display && app.display_profile.has_reader(), "plugin.dialog" => app.session.active().is_some(), "ui.perspectiveGridDialog" | "ui.savePerspectivePreset" => app.session.active().is_some(), id if id.starts_with(crate::dialogs::perspective_presets::SLOT) => { diff --git a/crates/ui-egui/src/menus/tests.rs b/crates/ui-egui/src/menus/tests.rs index 676e34e1a1..4cc93d02ca 100644 --- a/crates/ui-egui/src/menus/tests.rs +++ b/crates/ui-egui/src/menus/tests.rs @@ -1,6 +1,290 @@ use super::*; use crate::theme; +#[test] +fn help_f1_opens_discover_without_a_document() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + let (_, help) = menu_tree().into_iter().find(|(title, _)| *title == "Help").unwrap(); + assert!(help.iter().any(|item| matches!(item, Item::Cmd("VectorCraft Help…", "help.discover", _)))); + assert_eq!(shortcut_of("help.discover"), Some("F1")); + assert!(enabled(&app, "help.discover")); + let ctx = egui::Context::default(); + theme::install_fonts(&ctx); + let key = |key| egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }; + ctx.run_ui(egui::RawInput { events: vec![key(egui::Key::F1)], ..Default::default() }, |ui| { + crate::shortcuts::handle(&mut app, ui.ctx()); + }) + .textures_delta + .clear(); + assert!(crate::panel_docking::showing(&app.ui, "discover")); + assert!(app.session.active().is_none()); + app.run("help.discover", json!({})).unwrap(); + assert!(crate::panel_docking::showing(&app.ui, "discover")); + + let tools = app.run("help.discover.search", json!({"query": "rectangle"})).unwrap(); + let tool = tools["results"].as_array().unwrap().iter().position(|hit| hit["kind"] == "tool" && hit["id"] == "rectangle").unwrap(); + let active_tool = app.session.tool_id(); + let picked = app.run("help.discover.choose", json!({"index": tool})).unwrap(); + assert_eq!(picked["result"]["id"], "rectangle"); + assert!(app.ui.learn_locate.is_some()); + assert_eq!(app.session.tool_id(), active_tool); + for _ in 0..2 { + ctx.run_ui(egui::RawInput::default(), |ui| crate::panels::discover::show(&mut app, ui)).textures_delta.clear(); + } + ctx.run_ui(egui::RawInput { events: vec![key(egui::Key::Escape)], ..Default::default() }, |ui| { + crate::shortcuts::handle(&mut app, ui.ctx()); + crate::panels::discover::show(&mut app, ui); + }) + .textures_delta + .clear(); + assert!(!crate::panel_docking::showing(&app.ui, "discover")); + app.run("help.discover", json!({})).unwrap(); + app.run("help.discover.back", json!({})).unwrap(); + assert_eq!(app.ui.discover.query, "rectangle"); + assert!(app.ui.discover.selected.is_none()); + crate::keymap::set_override(&mut app.ui.shortcut_overrides, "tool:rectangle", "Shift+9"); + crate::shortcut_editor::sync(&app.ui); + let tools = app.run("help.discover.search", json!({"query": "rectangle"})).unwrap(); + assert!(tools["results"].as_array().unwrap().iter().any(|hit| hit["kind"] == "tool" && hit["id"] == "rectangle" && hit["shortcut"] == "Shift+9")); + crate::shortcut_editor::sync(&crate::state::UiState::default()); + + let commands = app.run("help.discover.search", json!({"query": "file.newDialog"})).unwrap(); + let command = commands["results"].as_array().unwrap().iter().position(|hit| hit["id"] == "file.newDialog").unwrap(); + app.run("help.discover.choose", json!({"index": command})).unwrap(); + assert!(app.ui.dialog.is_none()); + assert!(app.session.active().is_none()); + + let tutorial = crate::panels::learn::catalog::SKILLS[0].tutorials.first().unwrap(); + let found = app.run("help.discover.search", json!({"query": tutorial.title})).unwrap(); + let index = found["results"].as_array().unwrap().iter().position(|hit| hit["kind"] == "tutorial" && hit["id"] == tutorial.id).unwrap(); + app.run("help.discover.choose", json!({"index": index})).unwrap(); + assert!(app.session.active().is_none()); + let text = crate::tests_labels::painted_text(&mut app, crate::panels::discover::show); + assert!(text.contains(tutorial.title), "{text}"); + app.ui.discover.focus = true; + ctx.run_ui(egui::RawInput::default(), |ui| crate::panels::discover::show(&mut app, ui)).textures_delta.clear(); + ctx.run_ui(egui::RawInput { events: vec![key(egui::Key::Escape)], ..Default::default() }, |ui| { + crate::shortcuts::handle(&mut app, ui.ctx()); + crate::panels::discover::show(&mut app, ui); + }) + .textures_delta + .clear(); + assert!(!crate::panel_docking::showing(&app.ui, "discover")); + + app.run("file.new", json!({})).unwrap(); + app.run("help.discover", json!({})).unwrap(); + app.select_tool(vectorcraft_tools::addons::polygonal_lasso::ID); + let view = app.view_info(); + for (x, y) in [(40.0, 40.0), (80.0, 40.0)] { + let down = vectorcraft_tools::PointerEvent::new(vectorcraft_tools::PointerKind::Down, x, y); + let up = vectorcraft_tools::PointerEvent::new(vectorcraft_tools::PointerKind::Up, x, y); + app.session.pointer(&down, view).unwrap(); + app.session.pointer(&up, view).unwrap(); + } + assert!(app.session.tool_ends_on_escape(view)); + let canvas_ctx = egui::Context::default(); + canvas_ctx + .run_ui(egui::RawInput { events: vec![key(egui::Key::Escape)], ..Default::default() }, |ui| { + crate::shortcuts::handle(&mut app, ui.ctx()); + }) + .textures_delta + .clear(); + assert!(!app.session.tool_ends_on_escape(view)); + assert!(crate::panel_docking::showing(&app.ui, "discover")); +} + +/// With the toolbars hidden by Tab, choosing a tool in Help, or a tool's link in a tutorial Help +/// shows, marks nothing and the status bar says why. +#[test] +fn discover_says_why_a_tool_cannot_be_marked() { + fn texts(ctx: &egui::Context, app: &mut VectorcraftApp, events: Vec) -> Vec<(String, egui::Rect)> { + let mut out = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| crate::panels::discover::show(app, ui)); + out.textures_delta.clear(); + fn collect(s: &egui::Shape, out: &mut Vec<(String, egui::Rect)>) { + match s { + egui::Shape::Text(t) => out.push((t.galley.text().to_string(), t.visual_bounding_rect())), + egui::Shape::Vec(v) => v.iter().for_each(|s| collect(s, out)), + _ => {} + } + } + let mut texts = vec![]; + for c in &out.shapes { + collect(&c.shape, &mut texts); + } + texts + } + fn click(ctx: &egui::Context, app: &mut VectorcraftApp, label: &str) { + texts(ctx, app, vec![]); + let drawn = texts(ctx, app, vec![]); + let pos = drawn.iter().find(|(t, _)| t == label).unwrap_or_else(|| panic!("`{label}` not drawn: {drawn:?}")).1.center(); + let button = |pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + for e in [egui::Event::PointerMoved(pos), button(true), button(false)] { + texts(ctx, app, vec![e]); + } + } + crate::i18n::set_current(crate::i18n::Lang::EN); + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + app.run("window.dock", json!({})).unwrap(); + assert!(app.ui.tab_hid.is_some() && !app.ui.toolbar); + let reason = app.run("learn.locateTool", json!({"tool": "rectangle"})).unwrap()["reason"].as_str().unwrap().to_string(); + let ctx = egui::Context::default(); + theme::install_fonts(&ctx); + + let found = app.run("help.discover.search", json!({"query": "rectangle"})).unwrap(); + let hit = found["results"].as_array().unwrap().iter().find(|hit| hit["kind"] == "tool" && hit["id"] == "rectangle").unwrap().clone(); + app.status(""); + click(&ctx, &mut app, hit["label"].as_str().unwrap()); + assert_eq!(app.ui.discover.selected.map(|i| app.ui.discover.results[i].id.as_str()), Some("rectangle")); + assert!(app.ui.learn_locate.is_none()); + assert_eq!(app.ui.status, reason); + + let (tutorial, tool) = crate::panels::learn::catalog::SKILLS + .iter() + .flat_map(|skill| skill.tutorials.iter()) + .find_map(|t| t.steps.iter().find_map(|s| s.tool).map(|tool| (t, tool))) + .unwrap(); + let found = app.run("help.discover.search", json!({"query": tutorial.title})).unwrap(); + let index = found["results"].as_array().unwrap().iter().position(|hit| hit["kind"] == "tutorial" && hit["id"] == tutorial.id).unwrap(); + app.run("help.discover.choose", json!({"index": index})).unwrap(); + app.status(""); + click(&ctx, &mut app, vectorcraft_tools::tool_info(tool).unwrap().label); + assert!(app.ui.learn_locate.is_none()); + assert_eq!(app.ui.status, reason); +} + +#[test] +fn discover_rejects_invalid_search_and_selection_parameters() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + app.run("help.discover.search", json!({"query": "rectangle"})).unwrap(); + let before = app.ui.discover.query.clone(); + for params in + [json!({}), json!({"query": null}), json!({"query": false}), json!({"query": "rectangle", "unknown": 1}), json!({"query": "a".repeat(1025)})] + { + assert!(app.run("help.discover.search", params).is_err()); + assert_eq!(app.ui.discover.query, before); + } + for index in [json!(-1), json!(1.5), json!(1000000), json!("0"), Value::Null] { + assert!(app.run("help.discover.choose", json!({"index": index})).is_err()); + } + for params in [json!(5), json!("rectangle"), json!([1]), json!(true)] { + for id in ["help.discover", "help.discover.search", "help.discover.choose", "help.discover.back"] { + assert!(app.run(id, params.clone()).is_err(), "{id} {params}"); + } + assert_eq!(app.ui.discover.query, before); + } + app.run("help.discover.search", json!({"query": " "})).unwrap(); + assert!(app.ui.discover.results.is_empty()); + assert!(app.run("help.discover.choose", json!({"index": 0})).is_err()); +} + +/// A kept command result follows its menu item: Show Grid reads Hide Grid once the grid shows. +#[test] +fn discover_command_results_follow_their_menu_label() { + crate::i18n::set_current(crate::i18n::Lang::EN); + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let found = app.run("help.discover.search", json!({"query": "view.grid"})).unwrap(); + let index = found["results"].as_array().unwrap().iter().position(|hit| hit["id"] == "view.grid" && hit["path"][0] == "View").unwrap(); + assert_eq!(found["results"][index]["label"], "Show Grid"); + app.run("help.discover.choose", json!({"index": index})).unwrap(); + app.run("view.grid", json!({})).unwrap(); + let back = app.run("help.discover", json!({})).unwrap(); + assert_eq!(back["selected"], index); + assert_eq!(back["results"][index]["label"], "Hide Grid"); +} + +/// A menu entry's shown path translates the menus' own names and keeps a Scripts folder's name, as +/// the menus draw it; Help shows that path. +#[test] +fn menu_entry_shown_paths_keep_script_folder_names() { + let app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + let de = crate::i18n::Lang::from_code("de").unwrap(); + assert_ne!(crate::i18n::tr(de, "File"), "File"); + let script = json!({"path": "File/a.jsx"}); + let folder = vec![Item::Cmd("a", crate::scripts_menu::COMMAND, script)]; + let items = vec![Item::Sub("Scripts", vec![Item::Sub("File", folder), Item::Cmd("Other Script…", "ui.runScript", Value::Null)])]; + let mut out = vec![]; + crate::i18n::set_current(de); + flatten(&app, vec!["File".into()], vec![crate::i18n::t("File").into()], &items, &mut out); + crate::i18n::set_current(crate::i18n::Lang::EN); + let script = out.iter().find(|e| e.command.as_deref() == Some(crate::scripts_menu::COMMAND)).unwrap(); + assert_eq!(script.path, ["File", "Scripts", "File"]); + assert_eq!(script.shown_path, [crate::i18n::tr(de, "File"), crate::i18n::tr(de, "Scripts"), "File"]); +} + +/// Outside macOS the window's menu bar has no VectorCraft menu, so Help lists no command under it. +#[test] +fn discover_leaves_out_menus_the_window_does_not_show() { + crate::i18n::set_current(crate::i18n::Lang::EN); + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + let app_menu: Vec = + menu_entries(&app).into_iter().filter(|e| e.path.first().is_some_and(|t| t == "VectorCraft")).filter_map(|e| e.command).collect(); + assert!(!app_menu.is_empty()); + for id in app_menu { + let found = app.run("help.discover.search", json!({"query": id})).unwrap(); + let listed = found["results"].as_array().unwrap().iter().any(|hit| hit["path"][0] == "VectorCraft"); + assert_eq!(listed, cfg!(target_os = "macos"), "{id}: {found}"); + } +} + +/// Help finds a command by the label its menu shows in the UI language, also where the menu names +/// an effect by its own id (Effect › Pathfinder › Add reads Réunion in French). +#[test] +fn discover_finds_commands_by_their_shown_menu_label() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + let fr = crate::i18n::Lang::from_code("fr").unwrap(); + let shown = crate::i18n::tr_id(fr, "pathfinder.add", "Add"); + assert_ne!(shown, crate::i18n::tr(fr, "Add")); + crate::i18n::set_current(fr); + let found = app.run("help.discover.search", json!({"query": shown})); + let effect = crate::i18n::tr(fr, "Effect").to_string(); + crate::i18n::set_current(crate::i18n::Lang::EN); + let found = found.unwrap(); + let hits = found["results"].as_array().unwrap(); + assert!( + hits.iter().any(|hit| hit["kind"] == "command" + && hit["id"].as_str().is_some_and(|id| id.starts_with("effect.")) + && hit["label"] == shown + && hit["path"][0] == effect), + "{found}" + ); +} + +#[test] +fn discover_results_show_the_current_shortcut_and_language_after_a_change() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + let found = app.run("help.discover.search", json!({"query": "file.newDialog"})).unwrap(); + let index = found["results"].as_array().unwrap().iter().position(|hit| hit["id"] == "file.newDialog").unwrap(); + assert_eq!(found["results"][index]["shortcut"], "Cmd+N"); + app.run("help.discover.choose", json!({"index": index})).unwrap(); + app.run("window.panel.close", json!({"panel": "discover"})).unwrap(); + app.run("shortcuts.set", json!({"id": "file.newDialog", "shortcut": "Cmd+Alt+Shift+F9"})).unwrap(); + + let reopened = app.run("help.discover", json!({})).unwrap(); + assert_eq!(reopened["query"], "file.newDialog"); + assert_eq!(reopened["selected"], index); + assert_eq!(reopened["results"][index]["id"], "file.newDialog"); + assert_eq!(reopened["results"][index]["shortcut"], "Cmd+Alt+Shift+F9"); + let picked = app.run("help.discover.choose", json!({"index": index})).unwrap(); + assert_eq!(picked["result"]["shortcut"], "Cmd+Alt+Shift+F9"); + assert_eq!(picked["location"]["shortcut"], "Cmd+Alt+Shift+F9"); + + app.run("shortcuts.set", json!({"id": "file.newDialog", "shortcut": "Cmd+Alt+Shift+F8"})).unwrap(); + let text = crate::tests_labels::painted_text(&mut app, crate::panels::discover::show); + assert!(text.contains(&pretty_shortcut("Cmd+Alt+Shift+F8")), "{text}"); + assert!(!text.contains(&pretty_shortcut("Cmd+Alt+Shift+F9")), "{text}"); + + let de = crate::i18n::Lang::from_code("de").unwrap(); + assert_ne!(crate::i18n::tr(de, "New…"), "New…"); + crate::i18n::set_current(de); + let back = app.run("help.discover.back", json!({})).unwrap(); + crate::i18n::set_current(crate::i18n::Lang::EN); + assert_eq!(back["query"], "file.newDialog"); + assert_eq!(back["results"][index]["label"], crate::i18n::tr(de, "New…")); + assert_eq!(back["results"][index]["path"][0], crate::i18n::tr(de, "File")); + crate::shortcut_editor::sync(&crate::state::UiState::default()); +} + #[test] fn help_bar_toggle_is_independent_and_saved_in_workspaces() { let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); @@ -605,6 +889,30 @@ fn color_settings_and_assign_profile_show_the_separations_panel() { } } +/// Edit › Refresh Monitor Profile, after Assign Profile…, asks the desktop app's next frame to read +/// the display's profile; it is off and refused with the preference off or nothing to read it. +#[test] +fn refresh_monitor_profile_asks_for_a_reading_of_the_display_profile() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + let entries = menu_entries(&app); + let at = |label: &str| entries.iter().position(|e| e.label == label && e.path == ["Edit"]); + assert_eq!(at("Refresh Monitor Profile"), at("Assign Profile…").map(|i| i + 1)); + let e = &entries[at("Refresh Monitor Profile").unwrap()]; + assert_eq!((e.command.as_deref(), e.shortcut.as_str()), (Some("view.refreshMonitorProfile"), "")); + // Nothing reads the display's profile (the web build, tests). + assert!(!enabled(&app, "view.refreshMonitorProfile")); + assert_eq!(app.run("view.refreshMonitorProfile", json!({})).unwrap_err(), "this build doesn't read display profiles"); + app.display_profile.attach_reader(); + assert!(enabled(&app, "view.refreshMonitorProfile")); + assert_eq!(app.run("view.refreshMonitorProfile", json!({})).unwrap(), json!({"requested": true})); + assert!(app.display_profile.take_request()); + // With the preference off nothing is asked for. + app.session.prefs.monitor_profile_display = false; + assert!(!enabled(&app, "view.refreshMonitorProfile")); + assert_eq!(app.run("view.refreshMonitorProfile", json!({})).unwrap_err(), "turn on Use Monitor Profile for Canvas first"); + assert!(!app.display_profile.read_requested()); +} + #[test] fn saved_views_store_and_restore_the_view() { let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); diff --git a/crates/ui-egui/src/menus/tree.rs b/crates/ui-egui/src/menus/tree.rs index 19088a259a..137c3b5758 100644 --- a/crates/ui-egui/src/menus/tree.rs +++ b/crates/ui-egui/src/menus/tree.rs @@ -1,6 +1,6 @@ use super::slots::{PERSPECTIVE_SLOTS, RECENT_FONT_IDS, RECENT_IDS, SAVED_SELECTION_IDS, SAVED_VIEW_IDS}; use super::submenus::{INSERT_BREAK, INSERT_SPECIAL, INSERT_WHITESPACE, PATH_EFFECTS, TYPE_SIZES, effect_menu, font_items, insert_items}; -use super::{Item, Sep, c, cp, json, sub, todos}; +use super::{Item, Sep, c, cp, json, sub}; /// The in-window and native menu tree. The in-window bar skips the VectorCraft menu (see /// `menu_bar`); the native Mac bar is composed from the whole tree (see `native_menu`). @@ -141,6 +141,7 @@ pub fn menu_tree_named(english_names: bool) -> Vec<(&'static str, Vec)> { Sep, c("Color Settings…", "edit.colorSettings"), c("Assign Profile…", "edit.assignProfile"), + c("Refresh Monitor Profile", "view.refreshMonitorProfile"), Sep, c("Keyboard Shortcuts…", "edit.keyboardShortcuts"), c("Preferences…", "edit.preferences"), @@ -752,7 +753,7 @@ pub fn menu_tree_named(english_names: bool) -> Vec<(&'static str, Vec)> { c("VectorCraft on getartcraft.com", "help.appPage"), c("VectorCraft on GitHub", "help.github"), Sep, - todos("VectorCraft Help…", "F1"), + c("VectorCraft Help…", "help.discover"), c("Safe Mode…", "help.safeMode"), c("Copy Troubleshooting Info", "help.copyTroubleshootingInfo"), Sep, diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 6b178c3537..87091ef8a9 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -167,6 +167,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ ("app.home", "Home", "", "{} shows the Home screen (new file presets, Open) over the open documents; choosing a document tab returns to it"), ("edit.preferences", "Preferences…", "Cmd+K", "{category?} open Preferences (engine: prefs.get / prefs.set / prefs.list)"), ("edit.keyboardShortcuts", "Keyboard Shortcuts…", "Cmd+Alt+Shift+K", "{}"), + ( + "view.refreshMonitorProfile", + "Refresh Monitor Profile", + "", + "{} read the display's profile for Use Monitor Profile for Canvas (monitorProfileDisplay) again on the next frame, without waiting for the 10-second reading or the 1-second display check; while a reading runs, the request waits for it to end → {requested: true}, before the profile is read (ui.inspect › displayProfile reports the reading, and readRequested while it waits); an error while the preference is off, and where nothing reads the display's profile (the web build)", + ), ( "edit.autoSpellCheck", "Auto Spell Check", @@ -895,6 +901,25 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ ("help.about", "About VectorCraft", "", "{}"), ("help.checkForUpdates", "Check for Updates…", "", "{}"), ("help.commandPalette", "Search Commands…", "Cmd+Shift+/", "{}"), + ( + "help.discover", + "VectorCraft Help…", + "F1", + "{query?: string (at most 1024 characters, VectorCraft's limit)} show the Help panel without toggling it closed; a supplied query searches tools, menu commands, and built-in tutorials; omission keeps the current search. Returns {query, results: [{kind: tool|command|tutorial, id, label, path, shortcut}], selected: index|null}", + ), + ( + "help.discover.search", + "Search", + "", + "{query: string (at most 1024 characters, VectorCraft's limit)} search tools, menu commands, and built-in tutorials and show the Help panel; empty or whitespace-only text clears the results. Returns the help.discover result", + ), + ( + "help.discover.choose", + "Select", + "", + "{index: zero-based result index} show a tool's location, a tutorial's steps in Help, or a command's menu path and shortcut without running it; an invalid index is an error. Returns {result: chosen result, location: tool location, tutorial id, or command path}", + ), + ("help.discover.back", "Back", "", "{} return from a Help result to its search results without changing the query"), ( "help.safeMode", "Safe Mode…", @@ -948,7 +973,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.brushOptions", "Brush Options…", "", - "{name?} (default: the selected path's brush, else the current brush) open its Brush Options, what double-clicking a brush in the Brushes panel opens (dialog `brushOptions`): Calligraphic (fields name, angle −180..180, roundness 0..100, size 0..1296 pt, angleMode/roundnessMode/sizeMode: fixed|random|pressure, angleVariation/roundnessVariation/sizeVariation), Bristle (fields name, shape, size, length, density, thickness, opacity, stiffness), Scatter (fields sizeMin/sizeMax/sizeMode, spacingMin/spacingMax/spacingMode, scatterMin/scatterMax/scatterMode, rotationMin/rotationMax/rotationMode with modes fixed|random|pressure, rotationRelativeTo: page|path), Art (fields width %, scaleMode: proportional|stretch|betweenGuides, guideStart/guideEnd % of the art length, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flipAlong, flipAcross) or Pattern (fields scale %, spacing %, fit: stretch|addSpace|approximate, flipAlong, flipAcross); Scatter, Art and Pattern also colorization: none|tints|tintsAndShades|hueShift, keyColor, and tips: true opens Colorization Tips (what each method does, beside a sample of the brush painted with it), as the Tips button beside Method does; OK runs brush.options", + "{name?} (default: the selected path's brush, else the current brush) open its Brush Options, what double-clicking a brush in the Brushes panel opens (dialog `brushOptions`): Calligraphic (fields name, angle −180..180, roundness 0..100, size 0..1296 pt, angleMode/roundnessMode/sizeMode: fixed|random|pressure, angleVariation/roundnessVariation/sizeVariation), Bristle (fields name, shape, size, length, density, thickness, opacity, stiffness), Scatter (fields sizeMin/sizeMax/sizeMode, spacingMin/spacingMax/spacingMode, scatterMin/scatterMax/scatterMode, rotationMin/rotationMax/rotationMode with modes fixed|random|pressure, rotationRelativeTo: page|path, hueJitter 0..180°), Art (fields width %, scaleMode: proportional|stretch|betweenGuides, guideStart/guideEnd % of the art length, direction: leftToRight|rightToLeft|topToBottom|bottomToTop, flipAlong, flipAcross) or Pattern (fields scale %, spacing %, fit: stretch|addSpace|approximate, flipAlong, flipAcross); Scatter, Art and Pattern also colorization: none|tints|tintsAndShades|hueShift, keyColor, and tips: true opens Colorization Tips (what each method does, beside a sample of the brush painted with it), as the Tips button beside Method does; OK runs brush.options", ), ( "ui.brushObjectOptions", @@ -1002,7 +1027,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.symbolOptions", "Symbol Options…", "F8", - "{name?} open Symbol Options (dialog `symbolOptions`, fields `name`, `exportType`: movieClip|graphic, `registration` 0..8). Without `name` and with a selection: New Symbol (default name the first free \"New Symbol\"/\"New Symbol N\", Export Type Movie Clip, Registration centre); OK runs symbol.new {name, exportType, registration}. With `edit: true` or `name`: edit that symbol; OK runs symbol.options {name, newName?, exportType, registration}", + "{name?, edit?, keepArt?: false} open Symbol Options (dialog `symbolOptions`, fields `name`, `exportType`: movieClip|graphic, `registration` 0..8). Without `name` and with a selection: New Symbol (default name the first free \"New Symbol\"/\"New Symbol N\", Export Type Movie Clip, Registration centre); OK runs symbol.new {name, exportType, registration}, with keepArt: true when it was opened with keepArt: true (the selection stays ordinary art). With `edit: true` or `name`: edit that symbol; OK runs symbol.options {name, newName?, exportType, registration}; keepArt: true is then an error", ), ( "tool.options", diff --git a/crates/ui-egui/src/native_menu.rs b/crates/ui-egui/src/native_menu.rs index 5f133a6686..abe15ab2a0 100644 --- a/crates/ui-egui/src/native_menu.rs +++ b/crates/ui-egui/src/native_menu.rs @@ -610,7 +610,7 @@ pub fn sync(app: &mut VectorcraftApp, ctx: &egui::Context) { /// interaction is open (for example a move, scale or shape drag, a dialog's or the font menu's /// preview, or a typing session), the revision, which each of its previews changes, is left out: /// the hash changes as the interaction begins and as it ends. -fn state_hash(app: &VectorcraftApp, input: Option) -> u64 { +pub(crate) fn state_hash(app: &VectorcraftApp, input: Option) -> u64 { let mut h = DefaultHasher::new(); input.hash(&mut h); app.run_count.hash(&mut h); diff --git a/crates/ui-egui/src/palette.rs b/crates/ui-egui/src/palette.rs index 6122e7357b..9832567689 100644 --- a/crates/ui-egui/src/palette.rs +++ b/crates/ui-egui/src/palette.rs @@ -9,6 +9,7 @@ use crate::theme::Tokens; use crate::{VectorcraftApp, menus}; mod search; +pub(crate) mod words; /// Engine commands the palette leaves out, each with the UI command of the same name that runs it /// the way the panels and menus do: (engine id, UI command id). The Layers panel's Delete @@ -286,6 +287,12 @@ pub(crate) struct Entry { menu_item: &'static str, /// The entry's kind, in the order [`search::kind`] ranks kinds. kind: u8, + /// Where the row's label starts in `shown`: after the menu path, which the row shows as the + /// entry's home instead ([`home_text`]), or 0. + label_at: usize, + /// Does the row's home name the item of the menu bar after its menu path, since the item's + /// label differs from the entry's? + names_item: bool, } /// The palette's entries, the index a query is looked up in, and the last query's ranked results. @@ -338,10 +345,27 @@ fn catalog(lang: crate::i18n::Lang, native: bool) -> Catalog { let list = build_in(lang, native); let shown_homes: Vec> = list.iter().map(|e| e.home.as_deref().map(|h| format!("{} › {}", shown_label(lang, h), crate::i18n::tr(lang, e.menu_item)))).collect(); - let index = search::Index::build(&list, &shown_homes); + // A group's row in the `search` context gives its words in `lang`; a plain row is not read. + let search_row = |key: &str| crate::i18n::tr_ctx_row(lang, words::CONTEXT, key).map(str::to_string); + let index = search::Index::build(&list, &shown_homes, ¶ms_texts(&list), search_row); Catalog { list, index, ranked: std::sync::Mutex::new(None) } } +/// The params text of each entry's command, which the index reads a description from +/// ([`search::description`]): an engine or plug-in command's, a UI command's (the one it wraps +/// keeps its own) and an effect's. A tool, a panel and a filter plug-in have none. +fn params_texts(list: &[Entry]) -> Vec<&'static str> { + let engine = vectorcraft_engine::command_specs().iter().chain(vectorcraft_engine::cmd::plugin::command_specs()); + let mut by_id: std::collections::HashMap<&str, &'static str> = engine.map(|c| (c.id, c.params)).collect(); + by_id.extend(menus::UI_COMMANDS.iter().map(|c| (c.0, c.3))); + list.iter() + .map(|e| match e.id.strip_prefix("effect:") { + Some(effect) => vectorcraft_effects::effect_info(effect).map_or("", |info| info.params), + None => by_id.get(e.id.as_str()).copied().unwrap_or(""), + }) + .collect() +} + /// The palette's entries in `lang` with the in-window menu bar. #[cfg(test)] fn build(lang: crate::i18n::Lang) -> Vec { @@ -374,7 +398,16 @@ fn build_in(lang: crate::i18n::Lang, native: bool) -> Vec { } let (home, menu_item) = homes.get(&d.id).map_or((None, ""), |(path, item)| (Some(path.clone()), *item)); let kind = search::kind(&d.id, home.as_deref()); - Entry { id: d.id, shortcut: d.shortcut, shown, haystack, home, menu_item, kind } + // A row with a home shows its label without the menu path in front of it. A path that + // makes the name distinct ([`distinct_names`]) stays, unless the row's home shows that + // same path or it is the Tools in front of a tool's name, which the tool's kind and + // toolbar show. + let tool = d.id.starts_with("tool:"); + let drop = if d.in_context { home.as_deref() == Some(d.path.as_str()) || (tool && d.path == "Tools") } else { home.is_some() || tool }; + let prefix = format!("{} › ", shown_label(lang, &d.path)); + let label_at = if drop && !d.path.is_empty() && shown.starts_with(&prefix) { prefix.len() } else { 0 }; + let names_item = !menu_item.is_empty() && menu_item != d.label; + Entry { id: d.id, shortcut: d.shortcut, shown, haystack, home, menu_item, kind, label_at, names_item } }) .collect() } @@ -445,10 +478,87 @@ const TOP: f32 = 90.0; /// The space kept between the popup and the bottom of the window, in points. const BOTTOM_GAP: f32 = 8.0; -/// What a result row shows and screen readers read: its name, and its shortcut after a comma. -fn row_label(e: &Entry) -> String { +/// The point size of the kind icon at the start of a result row. +const KIND_ICON: f32 = 14.0; +/// The point size of the home's text after a row's label. +const HOME_TEXT: f32 = 11.0; + +/// The kind of result `e` is: the icon its row starts with and the word screen readers read +/// first, in the UI language. A tool shows its own icon. +fn kind_of(e: &Entry) -> (&'static str, &'static str) { + match e.id.split_once(':') { + Some(("tool", tool)) => (vectorcraft_tools::tool_info(tool).map_or("square-dashed", |t| crate::icons::tool_icon(t.icon)), tl!("Tool")), + Some(("panel", _)) => ("layout-grid", tl!("Panel")), + Some(("effect", _)) => ("dc-fx", tl!("Effect")), + Some(("plugin", _)) => ("dc-filter", tl!("Filter")), + _ => ("menu", tl!("Command")), + } +} + +/// The label a result row shows: its name without the menu path its home shows. +fn label_of(e: &Entry) -> &str { + e.shown.get(e.label_at..).unwrap_or(&e.shown) +} + +/// Where result `e` lives, as its row shows it: a tool's place on the toolbars ([`tool_home`]), +/// the menu path of the item of the menu bar that runs it (with the item's label when it differs +/// from the result's), or "No menu item". +fn home_text(app: &VectorcraftApp, e: &Entry) -> String { + let lang = crate::i18n::current(); + if let Some(tool) = e.id.strip_prefix("tool:") { + return tool_home(app, tool); + } + match &e.home { + Some(path) if e.names_item => format!("{} › {}", shown_label(lang, path), crate::i18n::tr(lang, e.menu_item)), + Some(path) => shown_label(lang, path), + None => tl!("No menu item").to_string(), + } +} + +/// Where `tool` is in the current layout: "Toolbar" for its button on the Tools panel, or the name +/// of the toolbar made with New Toolbar that holds it, followed by ", in the group", naming +/// the tool its slot's button shows, when the tool is hidden in that slot's group; "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 are hidden in Presentation Mode and while Tab hides the panels. +fn tool_home(app: &VectorcraftApp, tool: &str) -> String { + let lang = crate::i18n::current(); + let place = |name: &str, shown: Option<&str>| match shown.filter(|s| *s != tool).and_then(vectorcraft_tools::tool_info) { + // The tool goes in first, so a toolbar named with a placeholder keeps its name. + Some(t) => crate::i18n::fmt(tl!("{toolbar}, in the {tool} group"), &[("tool", crate::i18n::tr(lang, t.label)), ("toolbar", name)]), + None => name.to_string(), + }; + let toolbars_shown = app.ui.screen_mode < 3 && app.ui.tab_hid.is_none(); + let main = crate::toolbar::slots(app).into_iter().map(|(_, s)| s).find(|s| s.contains(&tool)); + let main = main.map(|slot| place(tl!("Toolbar"), Some(crate::toolbar::shown_tool(app, &slot)))); + let active = app.session.tool_id(); + let custom = |shown: bool| { + app.ui.custom_toolbars.iter().filter(|b| b.shown == shown).find_map(|bar| { + let slot = bar.slots.iter().find(|s| s.iter().any(|t| t == tool))?; + let tools: Vec<&'static str> = slot.iter().filter_map(|id| vectorcraft_tools::tool_info(id).map(|t| t.id)).collect(); + Some(place(&bar.name, crate::custom_toolbars::shown_tool(bar, active, &tools))) + }) + }; + if toolbars_shown { + if app.ui.toolbar + && let Some(main) = &main + { + return main.clone(); + } + if let Some(bar) = custom(true) { + return bar; + } + } + main.or_else(|| custom(true)).or_else(|| custom(false)).unwrap_or_else(|| tl!("All Tools").to_string()) +} + +/// What screen readers read for a result row, and its hover text: its kind, its label, where it +/// lives (`home`) and its shortcut, after commas. +fn row_label(e: &Entry, home: &str) -> String { let shortcut = menus::shown_shortcut(&e.shortcut); - if shortcut.is_empty() { e.shown.clone() } else { format!("{}, {shortcut}", e.shown) } + let kind = kind_of(e).1; + let start = format!("{kind}, {}, {home}", label_of(e)); + if shortcut.is_empty() { start } else { format!("{start}, {shortcut}") } } /// The line under the results: how many results matched, how many of them the list holds when it @@ -502,6 +612,41 @@ fn name_galley(painter: &egui::Painter, name: &str, font: egui::FontId, color: e painter.layout_job(job) } +/// A result row's label and home laid out in `width` points, and whether either was cut short. The +/// home goes after the label in the smaller dim text and is cut first; when the label alone does +/// not fit, the home is left out and the label is cut before the id it shows after its name +/// ([`distinct_names`]), which stays whole unless the id alone is wider than the row. +fn row_galleys( + painter: &egui::Painter, + e: &Entry, + home: &str, + font: egui::FontId, + color: egui::Color32, + dim: egui::Color32, + width: f32, +) -> (Arc, Option>, bool) { + let label = label_of(e); + let full = name_galley(painter, label, font.clone(), color, f32::INFINITY); + let room = width - full.size().x - 10.0; + if full.size().x <= width { + if room < HOME_TEXT { + return (full, None, !home.is_empty()); + } + let home = name_galley(painter, home, egui::FontId::new(HOME_TEXT, font.family), dim, room); + let cut = home.elided; + return (full, Some(home), cut); + } + let suffix = format!(" ({})", e.id); + let (head, suffix) = match label.strip_suffix(suffix.as_str()) { + Some(head) => (head, suffix), + None => (label, String::new()), + }; + let suffix_width = name_galley(painter, &suffix, font.clone(), color, f32::INFINITY).size().x; + let cut_head = name_galley(painter, head, font.clone(), color, width - suffix_width); + let shown: String = cut_head.rows.iter().flat_map(|r| r.glyphs.iter().map(|g| g.chr)).collect(); + (name_galley(painter, &format!("{shown}{suffix}"), font, color, width), None, true) +} + /// The scroll offset that keeps row `sel` in a list `view` points tall that was scrolled to `offset`. fn offset_showing(sel: usize, offset: f32, view: f32) -> f32 { let top = sel as f32 * ROW_HEIGHT; @@ -740,7 +885,8 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { let rank = if sel + 1 == matches.len() { kept.unwrap_or(sel) } else { sel }; let pos = (rank + 1).to_string(); let of = total.to_string(); - let said = crate::i18n::fmt(tl!("{pos} of {total}: {name}"), &[("pos", &pos), ("total", &of), ("name", &row_label(e))]); + let name = row_label(e, &home_text(app, e)); + let said = crate::i18n::fmt(tl!("{pos} of {total}: {name}"), &[("pos", &pos), ("total", &of), ("name", &name)]); ui.ctx().accesskit_node_builder(r.id, |node| node.set_description(said)); } if n > 0 { @@ -765,16 +911,29 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { } let font = egui::TextStyle::Body.resolve(ui.style()); let shortcut = menus::shown_shortcut(&e.shortcut); + let home = home_text(app, e); + let said = row_label(e, &home); let p = ui.painter(); let shortcut_at = rect.right_center() - egui::vec2(8.0, 0.0); let used = p.text(shortcut_at, egui::Align2::RIGHT_CENTER, &shortcut, font.clone(), t.text_dim); let name_end = if shortcut.is_empty() { rect.right() - 8.0 } else { used.left() - 12.0 }; - let name_at = rect.left() + 8.0; - let name = name_galley(p, &e.shown, font, t.text, name_end - name_at); - p.galley(egui::pos2(name_at, rect.center().y - name.size().y / 2.0), name, t.text); + let icon = egui::Rect::from_center_size( + egui::pos2(rect.left() + 8.0 + KIND_ICON / 2.0, rect.center().y), + egui::Vec2::splat(KIND_ICON), + ); + crate::icons::paint(ui, kind_of(e).0, icon, t.icon); + let name_at = icon.right() + 6.0; + let (label, home, cut) = row_galleys(p, e, &home, font, t.text, t.text_dim, name_end - name_at); + let home_at = name_at + label.size().x + 10.0; + p.galley(egui::pos2(name_at, rect.center().y - label.size().y / 2.0), label, t.text); + if let Some(home) = home { + p.galley(egui::pos2(home_at, rect.center().y - home.size().y / 2.0), home, t.text_dim); + } + // A row whose text is cut short shows all of it while the pointer rests on it. + let resp = if cut { resp.on_hover_text(said.clone()) } else { resp }; // `WidgetInfo::selected` reaches screen readers as a toggled state, so the // row sets the selected state on its node itself. - resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::ListItem, true, row_label(e))); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::ListItem, true, said.clone())); ui.ctx().accesskit_node_builder(resp.id, |node| node.set_selected(on)); if resp.clicked() { run = Some(e.id.clone()); @@ -1934,6 +2093,12 @@ mod tests { self.ctx.memory(|m| m.area_rect(egui::Id::unique("palette"))).unwrap() } + /// What screen readers read for result `id`'s row. + fn said(&self, id: &str) -> String { + let entries = entries(&self.ctx, Lang::EN); + entries.iter().find(|e| e.id == id).map(|e| row_label(e, &home_text(&self.app, e))).unwrap() + } + /// The results the palette lists for its query. fn listed(&self) -> Vec { let entries = entries(&self.ctx, Lang::EN); @@ -2042,8 +2207,7 @@ mod tests { let nodes = open.press(egui::Key::ArrowDown, 15); assert_eq!(open.highlighted(), 15); let lit: Vec<_> = rows(&nodes).into_iter().filter(|r| r.1).collect(); - let entries = entries(&open.ctx, Lang::EN); - let want = entries.iter().find(|e| e.id == listed[15]).map(row_label).unwrap(); + let want = open.said(&listed[15]); assert_eq!(lit.len(), 1, "{lit:?}"); assert_eq!(lit[0].0, want); let popup = open.popup(); @@ -2118,7 +2282,7 @@ mod tests { let lit: Vec<_> = rows(&nodes).into_iter().filter(|r| r.1).collect(); assert_eq!(lit.len(), 1, "{lit:?}"); assert!(lit[0].2 >= f64::from(popup.top()) && lit[0].3 <= f64::from(popup.bottom()), "{lit:?} in {popup:?}"); - assert_eq!(lit[0].0, row_label(entries(&open.ctx, Lang::EN).iter().find(|e| e.id == open.listed()[sel]).unwrap())); + assert_eq!(lit[0].0, open.said(&open.listed()[sel])); } /// Page Down, Up and Enter pressed in one frame move the highlight in that order, and Enter @@ -2211,7 +2375,7 @@ mod tests { assert!(open.repaint, "the frame that moved the highlight asks for another"); let nodes = open.frame(vec![]); let lit: Vec = rows(&nodes).into_iter().filter(|r| r.1).map(|r| r.0).collect(); - let label = entries.iter().find(|e| e.id == listed[3]).map(row_label).unwrap(); + let label = open.said(&listed[3]); assert_eq!(lit, std::slice::from_ref(&label)); assert_eq!(field_description(&nodes), format!("4 of {}: {label}", matching(&entries, "select").len())); } @@ -2233,6 +2397,206 @@ mod tests { out.textures_delta.clear(); } + /// The label and home of English result `id`'s row with the app's current layout. + fn label_and_home(app: &VectorcraftApp, id: &str) -> (String, String) { + crate::i18n::set_current(Lang::EN); + let entries = build(Lang::EN); + let e = entries.iter().find(|e| e.id == id).unwrap_or_else(|| panic!("{id} is listed")); + (label_of(e).to_string(), home_text(app, e)) + } + + /// A row shows its label without the menu path, and the menu path of the item of the menu bar + /// that runs it after it: with that item's label when it differs, and "No menu item" for a + /// command no item runs. + #[test] + fn rows_show_where_each_result_lives() { + let app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + let row = |id: &str| label_and_home(&app, id); + assert_eq!(row("effect:stylize.roundCorners"), ("Round Corners…".into(), "Effect › Stylize".into())); + assert_eq!(row("panel:layers"), ("Layers".into(), "Window".into())); + assert_eq!(row("object.group"), ("Group".into(), "Object".into())); + assert_eq!(row("app.quit").1, "File › Exit"); + // Window › Learn runs the Learn command as well as showing the Learn panel. + assert_eq!(row("window.learn").1, "Window"); + let entries = build(Lang::EN); + let learn = entries.iter().find(|e| e.id == "window.learn").expect("the Learn command"); + assert_eq!(learn.kind, search::kind("object.group", Some("Object")), "the Learn command ranks as a command of the menu bar"); + let none = entries.iter().find(|e| e.home.is_none() && !e.id.starts_with("tool:")).expect("a command with no menu item"); + assert_eq!((label_of(none), home_text(&app, none).as_str()), (none.shown.as_str(), "No menu item")); + // A path that keeps two names apart stays, unless the home shows it: the Knife tool's row + // drops the Tools in front of its name, and an Other Library… row shows its library menu + // as its home only. + assert_eq!(row("tool:knife").0, "Knife"); + let other: Vec<(&str, String)> = + entries.iter().filter(|e| e.shown.ends_with("Other Library…")).map(|e| (label_of(e), home_text(&app, e))).collect(); + assert!(other.len() >= 2 && other.iter().all(|(label, home)| *label == "Other Library…" && home.starts_with("Window › ")), "{other:?}"); + let kept = entries.iter().find(|e| e.label_at == 0 && e.shown.contains(" › ")).expect("a row that keeps its path"); + assert!(kept.home.as_deref().is_none_or(|h| !kept.shown.starts_with(&format!("{h} › "))), "{}", kept.shown); + for e in entries.iter().filter(|e| e.label_at > 0) { + assert!(e.home.is_some() || e.id.starts_with("tool:"), "{} has no home but drops its path", e.id); + } + } + + /// No two results' rows show the same kind, label and home, in any language, with the menu bar + /// in the window or the native one. + #[test] + fn no_two_rows_read_alike() { + let app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + let mut alike = vec![]; + for lang in Lang::all() { + crate::i18n::set_current(lang); + for native in [false, true] { + let mut seen = std::collections::HashMap::new(); + for e in &build_in(lang, native) { + let row = (kind_of(e).1, label_of(e).to_string(), home_text(&app, e)); + if let Some(other) = seen.insert(row.clone(), e.id.clone()) + && other != e.id + { + alike.push(format!("{} (native {native}): {other} and {}: {row:?}", lang.code(), e.id)); + } + } + } + } + crate::i18n::set_current(Lang::EN); + assert!(alike.is_empty(), "{}", alike.join("\n")); + } + + /// Every catalog translates the words a row's kind and home are read with. + #[test] + fn catalogs_translate_the_kind_and_home_words() { + let words = ["Tool", "Panel", "Effect", "Filter", "Command", "Toolbar", "{toolbar}, in the {tool} group", "All Tools", "No menu item"]; + let missing: Vec = Lang::all() + .filter(|l| *l != Lang::EN) + .flat_map(|l| words.iter().filter(move |w| !crate::i18n::has(l, w)).map(move |w| format!("{}: {w}", l.code()))) + .collect(); + assert!(missing.is_empty(), "{missing:?}"); + } + + /// A tool's row names the toolbar it is on, and the tool its slot's button shows while it is + /// hidden in that slot's group. A toolbar shown now comes before a hidden Tools panel, which + /// comes before a hidden toolbar made with New Toolbar. + #[test] + fn a_tool_row_names_its_toolbar_slot() { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + let home = |app: &VectorcraftApp, id: &str| label_and_home(app, id).1; + assert_eq!(home(&app, "tool:groupSelection"), "Toolbar, in the Direct Selection Tool group"); + assert_eq!(home(&app, "tool:directSelection"), "Toolbar"); + app.select_tool("groupSelection"); + assert_eq!(home(&app, "tool:groupSelection"), "Toolbar"); + assert_eq!(home(&app, "tool:directSelection"), "Toolbar, in the Group Selection Tool group"); + let bar = |name: &str, slot: &[&str], shown: bool| crate::state::CustomToolbar { + name: name.into(), + slots: vec![slot.iter().map(|t| t.to_string()).collect()], + shown, + pos: [0.0, 0.0], + dock: None, + dock_right: false, + slot_tool: Default::default(), + double: false, + floating: vec![], + }; + // Window › Tools hides the Tools panel while a toolbar made with New Toolbar holds the Pen + // Tool: the row names that toolbar. + app.ui.toolbar = false; + assert_eq!(home(&app, "tool:pen"), "Toolbar"); + app.ui.custom_toolbars.push(bar("Drawing", &["pen", "curvature"], true)); + assert_eq!(home(&app, "tool:pen"), "Drawing"); + assert_eq!(home(&app, "tool:curvature"), "Drawing, in the Pen Tool group"); + app.ui.custom_toolbars[0].name = "{tool}".into(); + assert_eq!(home(&app, "tool:curvature"), "{tool}, in the Pen Tool group"); + app.ui.custom_toolbars[0].name = "Drawing".into(); + // Tab hides the toolbars made with New Toolbar too: the hidden Tools panel comes first. + app.ui.tab_hid = Some(crate::state::TabHid { dock: true, toolbar: true, control_bar: true }); + assert_eq!(home(&app, "tool:pen"), "Toolbar"); + app.ui.tab_hid = None; + // The Tools panel shown again comes first. + app.ui.toolbar = true; + assert_eq!(home(&app, "tool:pen"), "Toolbar"); + // In Presentation Mode no toolbar shows; the tool still lives on the Tools panel. + app.ui.screen_mode = 3; + assert_eq!(home(&app, "tool:pen"), "Toolbar"); + app.ui.screen_mode = 0; + // A tool that only a hidden toolbar made with New Toolbar holds is named on it, and one no + // toolbar holds is in All Tools. + let on_tools: Vec<&str> = crate::toolbar::slots(&app).into_iter().flat_map(|(_, s)| s).collect(); + let loose = vectorcraft_tools::catalog::all_tools().map(|t| t.id).find(|t| !on_tools.contains(t)).expect("a tool not on the Tools panel"); + let id = format!("tool:{loose}"); + assert_eq!(home(&app, &id), "All Tools"); + app.ui.custom_toolbars.push(bar("Cutting", &[loose], false)); + assert_eq!(home(&app, &id), "Cutting"); + } + + /// A row too narrow for its label and home cuts the home first; a label that does not fit + /// alone is cut before the id it shows after its name, which stays whole. + #[test] + fn a_narrow_row_cuts_the_home_first_and_keeps_the_id() { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let entries = build(Lang::EN); + let keyed = entries.iter().find(|e| e.shown.ends_with(&format!(" ({})", e.id))).expect("a result that shows its id"); + let copy = entries.iter().find(|e| e.id == "edit.copy").expect("Copy"); + let app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| { + let font = egui::TextStyle::Body.resolve(ui.style()); + let p = ui.painter(); + let lay = |e: &Entry, home: &str, width: f32| row_galleys(p, e, home, font.clone(), egui::Color32::WHITE, egui::Color32::GRAY, width); + let text = |g: &egui::Galley| g.rows.iter().flat_map(|r| r.glyphs.iter().map(|g| g.chr)).collect::(); + let (label, home, cut) = lay(copy, "Edit", 400.0); + assert_eq!((text(&label), home.map(|h| text(&h)), cut), ("Copy".into(), Some("Edit".into()), false)); + let long = "A Menu › A Submenu With A Long Name › Another Submenu"; + let (label, home, cut) = lay(copy, long, 160.0); + let home = home.expect("some of the home fits"); + assert!(cut && home.elided && text(&label) == "Copy", "{}", text(&home)); + assert!(label.size().x + 10.0 + home.size().x <= 160.0 + 0.5); + // A long German menu path is cut before the label. + crate::i18n::set_current(Lang::from_code("de").expect("German")); + let german = build_in(crate::i18n::current(), false); + let deep = german + .iter() + .filter(|e| e.label_at > 0) + .max_by_key(|e| e.home.as_ref().map_or(0, |h| shown_label(crate::i18n::current(), h).chars().count())); + let deep = deep.expect("a German row with a home"); + let path = home_text(&app, deep); + crate::i18n::set_current(Lang::EN); + let label_width = name_galley(p, label_of(deep), font.clone(), egui::Color32::WHITE, f32::INFINITY).size().x; + let (label, home, cut) = lay(deep, &path, label_width + 60.0); + assert!(cut && text(&label) == label_of(deep) && home.is_some_and(|h| h.elided), "{path}"); + let suffix = format!(" ({})", keyed.id); + let suffix_width = name_galley(p, &suffix, font.clone(), egui::Color32::WHITE, f32::INFINITY).size().x; + let full = name_galley(p, label_of(keyed), font.clone(), egui::Color32::WHITE, f32::INFINITY).size().x; + assert!(full - 5.0 > suffix_width + 20.0, "{}", label_of(keyed)); + for width in [full - 5.0, suffix_width + 20.0, suffix_width / 2.0] { + let (label, home, cut) = lay(keyed, long, width); + let shown = text(&label); + assert!(cut && home.is_none(), "{width}"); + assert!(label.size().x <= width + 0.5, "{width}: {shown} is {} wide", label.size().x); + // An id wider than the row is cut too. + assert_eq!(shown.ends_with(&format!("…{suffix}")), width > suffix_width, "{width}: {shown}"); + } + }); + out.textures_delta.clear(); + } + + /// Screen readers read a row as its kind, label, home and shortcut, and the field's + /// description names them too; the row's height is unchanged. + #[test] + fn screen_readers_hear_the_kind_and_home() { + let mut open = Open::new("round corners", WINDOW); + let nodes = open.frame(vec![]); + let said = open.said("effect:stylize.roundCorners"); + assert_eq!(said, "Effect, Round Corners…, Effect › Stylize"); + let row = rows(&nodes).into_iter().find(|r| r.0 == said).expect("its row is drawn"); + assert!((row.3 - row.2 - f64::from(ROW_HEIGHT)).abs() < 0.01, "{row:?}"); + assert!(field_description(&nodes).ends_with(&said), "{}", field_description(&nodes)); + let open = Open::new("group selection", WINDOW); + assert_eq!(open.said("tool:groupSelection"), "Tool, Group Selection Tool, Toolbar, in the Direct Selection Tool group"); + let mut open = Open::new("layers", WINDOW); + let said = open.said("panel:layers"); + assert!(said.starts_with("Panel, Layers, Window"), "{said}"); + let nodes = open.frame(vec![]); + assert!(rows(&nodes).iter().any(|r| r.0 == said)); + } + /// The popup stays inside a short window, showing fewer rows when 12 don't fit; a page is the /// rows shown. #[test] @@ -2283,7 +2647,8 @@ mod tests { let mut open = Open::new("show panel", WINDOW); let listed = open.listed(); let entries = entries(&open.ctx, Lang::EN); - let label = |i: usize| entries.iter().find(|e| e.id == listed[i]).map(row_label).unwrap(); + let said: Vec = listed.iter().map(|id| open.said(id)).collect(); + let label = |i: usize| said[i].clone(); let nodes = open.frame(vec![]); // More results match than the list holds: the place counts every match, as the footer does. let total = matching(&entries, "show panel").len(); @@ -2295,10 +2660,10 @@ mod tests { let nodes = open.press(egui::Key::ArrowDown, 1); assert_eq!(field_description(&nodes), format!("2 of {total}: {}", label(1))); // Fewer results match than the list holds. - let mut open = Open::new("copy", WINDOW); + let mut open = Open::new("eyedropper", WINDOW); let n = open.listed().len(); assert!((1..MAX_RESULTS).contains(&n), "{n}"); - let first = entries.iter().find(|e| e.id == open.listed()[0]).map(row_label).unwrap(); + let first = open.said(&open.listed()[0]); let nodes = open.frame(vec![]); assert_eq!(field_description(&nodes), format!("1 of {n}: {first}")); assert!(labels(&nodes).contains(&footer(n, n)), "{:?}", labels(&nodes)); @@ -2780,7 +3145,7 @@ mod tests { let listed: Vec<_> = matching(&entries, "show panel").into_iter().take(MAX_RESULTS).collect(); let hidden = |e: &&&Entry| e.id.strip_prefix("panel:").is_some_and(|p| !crate::panel_docking::showing(&window.app.ui, p)); let e = listed.iter().find(hidden).expect("a hidden panel's result"); - let label = row_label(e); + let label = row_label(e, &home_text(&window.app, e)); let row = rows(&nodes).into_iter().find(|r| r.0 == label).expect("its row is drawn"); let panel = e.id.strip_prefix("panel:").unwrap_or_default().to_string(); window.click(egui::pos2(window.popup().center().x, ((row.2 + row.3) / 2.0) as f32)); @@ -2868,7 +3233,7 @@ mod tests { assert!(plugin.is_some_and(|p| p < MAX_RESULTS), "the plug-in is shown: {plugin:?}"); assert_eq!(ranked.iter().position(|e| e.id == id), Some(MAX_RESULTS), "the plug-in pushed the highlight past the limit"); assert_eq!((sel, &now), (MAX_RESULTS - 1, &id), "the highlight stays on its result, in the last row"); - let label = row_label(ranked[MAX_RESULTS]); + let label = row_label(ranked[MAX_RESULTS], &home_text(&open.app, ranked[MAX_RESULTS])); assert!(rows(&nodes).iter().any(|r| r.1 && r.0 == label), "its row is drawn and highlighted"); assert_eq!(field_description(&nodes), format!("{} of {}: {label}", MAX_RESULTS + 1, ranked.len())); } diff --git a/crates/ui-egui/src/palette/search.rs b/crates/ui-egui/src/palette/search.rs index e20d75e610..d87cf4c182 100644 --- a/crates/ui-egui/src/palette/search.rs +++ b/crates/ui-egui/src/palette/search.rs @@ -11,27 +11,49 @@ use crate::menus; const INDEX_CHARS: usize = 200; /// The field of a result a word comes from, best first, and the fields of the English stem forms -/// ([`stems`]) of the words of the label and the menu path. +/// ([`stems`]) of the words of the label, the menu path and the description ([`description`]). const LABEL: u8 = 0; const PATH: u8 = 1; const ID: u8 = 2; const LABEL_STEMMED: u8 = 3; const PATH_STEMMED: u8 = 4; +const DESCRIPTION: u8 = 5; +const DESCRIPTION_STEMMED: u8 = 6; /// A word's grade in a result, best first: a whole word of the label, a word of the label it /// shares an English stem form with ("outlines" and Outline), a word of the label it starts, a -/// word of the menu path it is, shares a stem form with or starts, a word of the id it is or -/// starts, or text inside a word of any field ([`super::matching`]'s substring rule). The grades -/// without a stem are twice the values they had before stems were added, so results matched -/// without a stem keep their order by the sum of the grades. +/// word of the label with the same meaning ([`super::words`]), a word of the menu path it is, +/// shares a stem form with or starts, a word of the menu path with the same meaning, a word of the +/// id it is or starts, text inside a word of any field ([`super::matching`]'s substring rule), a +/// word of the description it is, shares a stem form with, starts or means the same as, a word of +/// the label a typo away from it ([`Index::typos`]), or a word of the menu path a typo away. A word +/// of the description comes after the substring rule, so every result the substring rule finds +/// ranks above a result found only by its description. The grades without a stem or a word with +/// the same meaning are twice the values they had before those were added, so results matched +/// without them keep their order by the sum of the grades. const LABEL_WORD: u8 = 2; const LABEL_STEM: u8 = 3; const LABEL_PREFIX: u8 = 4; +const LABEL_SYNONYM: u8 = 5; const PATH_WORD: u8 = 6; +const PATH_SYNONYM: u8 = 7; const ID_WORD: u8 = 8; const SUBSTRING: u8 = 10; +const DESCRIPTION_WORD: u8 = 11; +const LABEL_TYPO: u8 = 12; +const PATH_TYPO: u8 = 14; const NONE: u8 = u8::MAX; +/// The most characters of a command's description the index reads (VectorCraft's own limit). +const DESCRIPTION_CHARS: usize = 300; + +/// The words of a description the index leaves out, besides words of 2 characters or fewer and +/// words with no letter. +const STOP_WORDS: &[&str] = &["the", "and", "ids", "true", "false", "null"]; + +/// The most words a query word with a typo meets ([`Index::typos`]), nearest first. +const TYPO_TERMS: usize = 32; + /// How a whole query matches a result, best first: it is the result's id, it is a label, a label /// starts with it, or it is the initials of a label. const EXACT_ID: u8 = 0; @@ -62,6 +84,38 @@ pub(crate) struct Index { initials_text: String, /// Each result's offset and length in `initials_text`. initials: Vec<(u32, u16)>, + /// Each word of a group of words with the same meaning ([`super::words::GROUPS`], and the + /// words the UI language's catalog adds), with the group's place in the table. + synonyms: HashMap, u16>, +} + +/// Is `w` one word as the index splits text ([`words`])? +pub(crate) fn is_one_word(w: &str) -> bool { + let mut it = words(w); + it.next() == Some(w) && it.next().is_none() +} + +/// The words of each group of [`super::words::GROUPS`], with the words `search_row` gives for the +/// group's catalog row ([`super::words::row_key`]) in the UI language. A word the catalog gives +/// that is not a single word, or that is already a word of a group, is left out. +fn synonym_groups(search_row: impl Fn(&str) -> Option) -> HashMap, u16> { + let mut out: HashMap, u16> = HashMap::new(); + let groups = super::words::GROUPS.iter().enumerate().filter_map(|(g, words)| u16::try_from(g).ok().map(|g| (g, words))); + for (g, words) in groups.clone() { + for &w in *words { + out.insert(w.into(), g); + } + } + for (g, words) in groups { + let Some(text) = search_row(&super::words::row_key(words)) else { continue }; + for (w, single) in super::words::row_words(&text) { + if single { + out.entry(w.into()).or_insert(g); + } + } + } + out.shrink_to_fit(); + out } /// Splits `text` into lowercase words at whitespace and at `.`, `-`, `/`, `(`, `)`, `…`, `›`, `,` @@ -133,6 +187,80 @@ fn stems(word: &str) -> Vec { vec![] } +/// Is `c` a letter of a script written without spaces between words (Han, kana or Hangul)? +fn spaceless(c: char) -> bool { + matches!( + u32::from(c), + 0x1100..=0x11FF + | 0x3040..=0x30FF + | 0x3130..=0x318F + | 0x31F0..=0x31FF + | 0x3400..=0x4DBF + | 0x4E00..=0x9FFF + | 0xA960..=0xA97F + | 0xAC00..=0xD7FF + | 0xF900..=0xFAFF + | 0xFF66..=0xFFDC + | 0x20000..=0x323AF + ) +} + +/// The most edits a query word may be away from a word it meets as a typo: 1 for a word of 4 to 7 +/// characters, 2 for a longer one, and none for a shorter word or one with letters of a script +/// written without spaces ([`spaceless`]). +fn typo_bound(word: &str) -> Option { + if word.chars().any(spaceless) { + return None; + } + match word.chars().count() { + 0..=3 => None, + 4..=7 => Some(1), + _ => Some(2), + } +} + +/// The number of edits between `a` and `b` when it is at most `bound`: a character inserted, +/// removed or changed, or two adjacent characters swapped (`gruop` and `group`), each count as one. +/// The count stops as soon as every way of lining the two up needs more than `bound`. +fn edits_within(a: &[char], b: &[char], bound: usize) -> Option { + if a.len().abs_diff(b.len()) > bound { + return None; + } + let at = |row: &[usize], j: usize| row.get(j).copied().unwrap_or(usize::MAX); + // The edits between the first i characters of `a` and the first j of `b`, for the rows i - 2, + // i - 1 and i. + let mut before: Vec = vec![0; b.len() + 1]; + let mut last: Vec = (0..=b.len()).collect(); + let mut row: Vec = vec![0; b.len() + 1]; + for (i, &ca) in a.iter().enumerate() { + if let Some(first) = row.first_mut() { + *first = i + 1; + } + for (j, &cb) in b.iter().enumerate() { + let changed = at(&last, j).saturating_add(usize::from(ca != cb)); + let removed = at(&last, j + 1).saturating_add(1); + let inserted = at(&row, j).saturating_add(1); + let mut edits = changed.min(removed).min(inserted); + let swapped = i.checked_sub(1).and_then(|k| a.get(k)).zip(j.checked_sub(1).and_then(|k| b.get(k))); + if let Some((&pa, &pb)) = swapped + && pa == cb + && pb == ca + { + edits = edits.min(at(&before, j - 1).saturating_add(1)); + } + if let Some(cell) = row.get_mut(j + 1) { + *cell = edits; + } + } + if row.iter().all(|&e| e > bound) { + return None; + } + std::mem::swap(&mut before, &mut last); + std::mem::swap(&mut last, &mut row); + } + last.last().copied().filter(|&e| e <= bound) +} + /// Adds each word of `text` to `found` for result `entry` in `field`, and with `stemmed`, each /// word's English stem forms in that field. fn add_words(found: &mut Vec<(String, u16, u8)>, text: &str, entry: u16, field: u8, stemmed: Option) { @@ -152,6 +280,50 @@ fn split_name(name: &str) -> (&str, &str) { } } +/// A command's description, read from its params text: the text without each `{…}` group that is +/// not inside a `{`, `[` or `(` group (braces inside double quotes are text), without each such +/// `[…]` or `(…)` group just after a `→`, and without the `→` just before a removed group, with +/// each run of whitespace made one space and cut to its first [`DESCRIPTION_CHARS`] characters at +/// the end of a word. A group that is never closed stays in the text, and so does a result written +/// as words after a `→`. Params text that is only a group has an empty description. +pub(crate) fn description(params: &str) -> String { + let mut out = String::new(); + // The end of the text copied to `out`, and whether a removed group is open. + let (mut copied, mut open) = (0, false); + for (i, ch, depth) in crate::shortcut_editor::outside_quotes(params) { + let before = params.get(copied..i).unwrap_or_default(); + match ch { + '{' | '[' | '(' if depth == 0 && (ch == '{' || before.trim_end().ends_with('→')) => { + out.push_str(before); + (copied, open) = (i, true); + } + '}' | ']' | ')' if depth == 1 && open => { + let kept = out.trim_end().strip_suffix('→').unwrap_or(&out).len(); + out.truncate(kept); + out.push(' '); + (copied, open) = (i + ch.len_utf8(), false); + } + _ => {} + } + } + out.push_str(params.get(copied..).unwrap_or_default()); + let text = out.split_whitespace().collect::>().join(" "); + // A cut inside a word drops the rest of that word, so no part of a word is read as a word. + let Some((head, rest)) = text.char_indices().nth(DESCRIPTION_CHARS).and_then(|(end, _)| text.split_at_checked(end)) else { return text }; + let head = if rest.starts_with(' ') { head } else { head.rsplit_once(' ').map_or("", |(kept, _)| kept) }; + head.trim_end().to_string() +} + +/// The lowercase words of the lowercased `description` the index holds: split at every character +/// that is not a letter, a digit or an apostrophe, without apostrophes at either end, and leaving +/// out words of 2 characters or fewer, words with no letter and [`STOP_WORDS`]. +fn description_words(description: &str) -> impl Iterator { + description + .split(|c: char| !(c.is_alphanumeric() || c == '\'')) + .map(|w| w.trim_matches('\'')) + .filter(|w| w.chars().count() > 2 && w.chars().any(char::is_alphabetic) && !STOP_WORDS.contains(w)) +} + /// `name` without the id that follows it when the result shows its id. fn without_id<'a>(name: &'a str, id: &str) -> &'a str { name.strip_suffix(')').and_then(|n| n.strip_suffix(id)).and_then(|n| n.strip_suffix(" (")).unwrap_or(name) @@ -172,9 +344,12 @@ impl Index { /// The index of `entries`, whose menu homes and menu items read `homes` in the UI language. The /// words of a result's menu home and of its menu item's label count as menu path words. The /// words of the English names, menu home and menu item label also add their English stem forms - /// ([`stems`]); words in the UI language do not. A catalog with more results than a posting can - /// name gets an empty index, and queries match by the substring rule alone. - pub(crate) fn build(entries: &[Entry], homes: &[Option]) -> Index { + /// ([`stems`]); words in the UI language do not. `params` gives each result's params text, whose + /// [`description`] adds its words ([`description_words`]) and their stem forms; only the words + /// are kept. `search_row` gives the UI language's words for a group of words with the same + /// meaning ([`synonym_groups`]). A catalog with more results than a posting can name gets an + /// empty index, and queries match by the substring rule alone. + pub(crate) fn build(entries: &[Entry], homes: &[Option], params: &[&str], search_row: impl Fn(&str) -> Option) -> Index { if entries.len() > usize::from(u16::MAX) { return Index::default(); } @@ -211,12 +386,18 @@ impl Index { for id in ids(e) { found.extend(words(id).map(|w| (w.to_string(), entry, ID))); } + if let Some(text) = params.get(i).filter(|p| !p.is_empty()) { + for w in description_words(&description(text).to_lowercase()) { + found.push((w.to_string(), entry, DESCRIPTION)); + found.extend(stems(w).into_iter().map(|s| (s, entry, DESCRIPTION_STEMMED))); + } + } let len = u16::try_from(initials_text.len() - start).unwrap_or(0); initials.push((u32::try_from(start).unwrap_or(0), len)); } found.sort_unstable(); found.dedup(); - let mut index = Index { initials_text, initials, ..Index::default() }; + let mut index = Index { initials_text, initials, synonyms: synonym_groups(search_row), ..Index::default() }; let mut last: Option<&str> = None; for (word, entry, field) in &found { if last != Some(word.as_str()) { @@ -253,6 +434,8 @@ impl Index { + self.postings.capacity() * std::mem::size_of::() + self.initials_text.capacity() + self.initials.capacity() * std::mem::size_of::<(u32, u16)>() + + self.synonyms.capacity() * (std::mem::size_of::<(Box, u16)>() + 1) + + self.synonyms.keys().map(|w| w.len()).sum::() } /// The text of the word at `(offset, len)` in `term_text`. @@ -273,10 +456,11 @@ impl Index { self.terms.binary_search_by(|t| self.text(t).cmp(text)).ok() } - /// The best grade ([`LABEL_WORD`] to [`ID_WORD`]) `word` gets in each result, [`NONE`] where it - /// is no word, shares no English stem form with a word of the label or menu path, and starts no - /// word of the result. The words it starts are found by a binary search of the sorted words; a - /// stem form matches only a word or stem form equal to it. + /// The best grade ([`LABEL_WORD`] to [`DESCRIPTION_WORD`], without [`SUBSTRING`]) `word` gets in + /// each result, [`NONE`] where it is no word, shares no English stem form with a word of the + /// label, menu path or description, means the same as none of them, and starts no word of the + /// result. The words it starts are found by a binary search of the sorted words; a stem form + /// matches only a word or stem form equal to it. fn grades(&self, word: &str, n: usize) -> Vec { let mut out = vec![NONE; n]; let mut mark = |postings: &[Posting], grade: &dyn Fn(u8) -> Option| { @@ -301,19 +485,22 @@ impl Index { LABEL if whole => Some(LABEL_WORD), LABEL => Some(LABEL_PREFIX), PATH => Some(PATH_WORD), + DESCRIPTION => Some(DESCRIPTION_WORD), ID => Some(ID_WORD), _ => None, }); } // The word meets a stem form of a word of the result ("scale" and Scaling) when it is itself - // a word of some result, so a partly typed word ("scal") that only equals a stem form does - // not lift Scaling above Scale. + // a word of some result's label, menu path, id or description, so a partly typed word + // ("scal") that only equals a stem form does not lift Scaling above Scale. A description is + // cut at the end of a word ([`description`]), so it holds no partly typed word. if let Some(t) = self.find(word) - && self.postings_of(t).iter().any(|p| matches!(p.field, LABEL | PATH | ID)) + && self.postings_of(t).iter().any(|p| matches!(p.field, LABEL | PATH | ID | DESCRIPTION)) { mark(self.postings_of(t), &|field| match field { LABEL_STEMMED => Some(LABEL_STEM), PATH_STEMMED => Some(PATH_WORD), + DESCRIPTION_STEMMED => Some(DESCRIPTION_WORD), _ => None, }); } @@ -324,12 +511,88 @@ impl Index { mark(self.postings_of(t), &|field| match field { LABEL | LABEL_STEMMED => Some(LABEL_STEM), PATH | PATH_STEMMED => Some(PATH_WORD), + DESCRIPTION | DESCRIPTION_STEMMED => Some(DESCRIPTION_WORD), + _ => None, + }); + } + // Each other word of the word's group of words with the same meaning ([`Index::synonyms_of`]) + // meets a word of the label, menu path or description, or a stem form of one, equal to it. + // Ids are not matched this way. + for t in self.synonyms_of(word) { + mark(self.postings_of(t), &|field| match field { + LABEL | LABEL_STEMMED => Some(LABEL_SYNONYM), + PATH | PATH_STEMMED => Some(PATH_SYNONYM), + DESCRIPTION | DESCRIPTION_STEMMED => Some(DESCRIPTION_WORD), _ => None, }); } out } + /// The other words of the group of words with the same meaning that `word`, or a stem form of + /// it, is in ("bg" and background, "flipped" and reflect), as places in `terms`; the words of the + /// group no result holds are left out. + fn synonyms_of(&self, word: &str) -> Vec { + let group = std::iter::once(word.to_string()).chain(stems(word)).find_map(|w| self.synonyms.get(w.as_str()).copied()); + let Some(group) = group else { return vec![] }; + let mut found: Vec = self.synonyms.iter().filter(|&(w, &g)| g == group && &**w != word).filter_map(|(w, _)| self.find(w)).collect(); + // The map's order changes from one build to the next; the words' order in `terms` does not. + found.sort_unstable(); + found + } + + /// The words of labels and menu paths that `word` is a typo of: within [`typo_bound`] edits of + /// it ([`edits_within`]), at most [`TYPO_TERMS`], nearest first, as places in `terms`. Ids and + /// words with letters of a script written without spaces ([`spaceless`]) are not compared. + fn typos(&self, word: &str) -> Vec { + let Some(bound) = typo_bound(word) else { return vec![] }; + let word: Vec = word.chars().collect(); + let mut term: Vec = vec![]; + let mut near: Vec<(usize, usize)> = vec![]; + for (t, at) in self.terms.iter().enumerate() { + let text = self.text(at); + if text.chars().count().abs_diff(word.len()) > bound || text.chars().any(spaceless) { + continue; + } + term.clear(); + term.extend(text.chars()); + if let Some(edits) = edits_within(&word, &term, bound) + && self.postings_of(t).iter().any(|p| matches!(p.field, LABEL | PATH)) + { + near.push((edits, t)); + } + } + near.sort_unstable(); + near.truncate(TYPO_TERMS); + near.into_iter().map(|(_, t)| t).collect() + } + + /// Gives each result a word of `near` ([`Index::typos`]) is a word of its label or menu path + /// [`LABEL_TYPO`] or [`PATH_TYPO`] in `grades`, where its grade is not better. A typo replaces + /// [`DESCRIPTION_WORD`], since a result found only by its description ranks below one found + /// through a typo ([`rank`]). + fn mark_typos(&self, near: &[usize], grades: &mut [u8]) { + for &t in near { + for p in self.postings_of(t) { + let grade = match p.field { + LABEL => LABEL_TYPO, + PATH => PATH_TYPO, + _ => continue, + }; + if let Some(g) = grades.get_mut(usize::from(p.entry)) { + *g = if *g == DESCRIPTION_WORD { grade } else { (*g).min(grade) }; + } + } + } + } + + /// The text of the first word of `near` that is a word of result `i` in one of `fields` (its + /// label or its menu path, and their stem forms). + fn nearest_of(&self, near: &[usize], i: usize, fields: &[u8]) -> Option<&str> { + let t = near.iter().find(|&&t| self.postings_of(t).iter().any(|p| usize::from(p.entry) == i && fields.contains(&p.field)))?; + self.terms.get(*t).map(|at| self.text(at)) + } + /// Is `query` (no spaces) the initials of one of result `i`'s labels? fn initials_are(&self, i: usize, query: &str) -> bool { let Some(&(offset, len)) = self.initials.get(i) else { return false }; @@ -379,18 +642,29 @@ fn phrase(e: &Entry, query: &str, initials: bool) -> u8 { NO_PHRASE } -/// What results are ordered by, compared field by field: how the whole query matches, the worst -/// grade a word gets, the sum of the grades, the kind of result and the label's length. -type RankKey = (u8, u8, u32, u8, usize); +/// 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 kind of result and the label's length. +type RankKey = (bool, bool, u8, u8, u32, u8, 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 /// (the rule the palette always had, so nothing it found is lost), when every word of the query is -/// or starts a word of its label, menu path or id or shares an English stem form with a word of its -/// label or menu path ("rounded corners" for Round Corners…), or when the query is the initials of -/// a label ("ea" for Export As…). Results are ordered by how the whole query matches ([`phrase`]), -/// then by the worst grade a word gets, the sum of the grades, the kind of result ([`kind`]), the -/// label's length and the catalog order. An empty query lists every result in catalog order. +/// or starts a word of its label, menu path, description ([`description`]) or id, shares an English +/// stem form with a word of its label, menu path or description ("rounded corners" for Round +/// Corners…) or means the same as a word of its label, menu path or description ("remove bg" for +/// Remove Background…), or when the query is the initials of a label ("ea" for Export As…). A query +/// word that is no word, stem form or word start of any result's label, menu path or id also +/// matches the words of labels and menu paths it is a typo of ([`Index::typos`]). +/// Results where a word matched only through a description come after every other result. Before +/// them, results where a word matched only through a typo come after every other result, and their +/// whole-query match is read with each such word replaced by the word it is a typo of ("gruop" as +/// "group"). Results are ordered by that, by how the whole query matches ([`phrase`]), then by the +/// 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"), +/// the kind of result ([`kind`]), the label's length and the catalog order. An empty query lists +/// every result in catalog order. pub(crate) fn rank(entries: &[Entry], index: &Index, query: &str) -> Vec { let query = normalize(query); if query.is_empty() { @@ -399,8 +673,39 @@ pub(crate) fn rank(entries: &[Entry], index: &Index, query: &str) -> Vec { let spaced: Vec<&str> = query.split(' ').collect(); let head: String = query.chars().take(INDEX_CHARS).collect(); let tokens: Vec<&str> = words(&head).collect(); + // Where each word starts in the query (`head` is its start), for reading the query with a typo + // corrected. + let starts: Vec = tokens.iter().map(|t| (t.as_ptr() as usize).saturating_sub(head.as_ptr() as usize)).collect(); let n = entries.len(); - let indexed: Vec> = tokens.iter().map(|t| index.grades(t, n)).collect(); + let mut indexed: Vec> = Vec::with_capacity(tokens.len()); + let mut typos: Vec> = Vec::with_capacity(tokens.len()); + let mut meanings: Vec> = Vec::with_capacity(tokens.len()); + // After a word that is nothing in any result and a typo of nothing, a result is found only by + // the substring rule or its initials, where a typo grade changes nothing, so the later words are + // not compared. + let mut compare = true; + for (k, t) in tokens.iter().enumerate() { + // A repeated word is graded once. + if let Some(j) = tokens.iter().take(k).position(|u| u == t) + && let (Some(grades), Some(near), Some(same)) = (indexed.get(j).cloned(), typos.get(j).cloned(), meanings.get(j).cloned()) + { + indexed.push(grades); + typos.push(near); + meanings.push(same); + continue; + } + meanings.push(index.synonyms_of(t)); + let mut grades = index.grades(t, n); + // A word that matches only words of descriptions is still compared with the words of labels + // and menu paths it may be a typo of. + let near = if compare && grades.iter().all(|&g| g == NONE || g == DESCRIPTION_WORD) { index.typos(t) } else { vec![] }; + if near.is_empty() && grades.iter().all(|&g| g == NONE) { + compare = false; + } + index.mark_typos(&near, &mut grades); + indexed.push(grades); + typos.push(near); + } // The index reads only the start of a longer query, so such a query matches by the substring // rule, which reads all of it. let fits = query.chars().count() <= INDEX_CHARS; @@ -414,24 +719,80 @@ pub(crate) fn rank(entries: &[Entry], index: &Index, query: &str) -> Vec { // Each word's grade, the worst and their sum; with initials, every word counts as a word // the label starts, as the initials stand for every word of the label. let (mut all_indexed, mut worst, mut sum) = (fits && !tokens.is_empty(), 0u8, 0u32); - for (grades, token) in indexed.iter().zip(&tokens) { + // The query as read for the whole-query match, with each word matched only through a typo + // replaced by the word of this result it is a typo of; and as read with each word matched + // through a word with the same meaning replaced by that word too. + let (mut typo, mut corrected, mut copied) = (false, String::new(), 0); + let mut described = false; + let (mut synonym, mut meant, mut meant_copied) = (false, String::new(), 0); + let splice = |out: &mut String, copied: &mut usize, k: usize, token: &str, word: &str| { + if let Some(&start) = starts.get(k) + && let Some(between) = query.get(*copied..start) + { + out.push_str(between); + out.push_str(word); + *copied = start + token.len(); + } + }; + for (k, (grades, token)) in indexed.iter().zip(&tokens).enumerate() { let mut g = grades.get(i).copied().unwrap_or(NONE); if g == NONE { all_indexed = false; - if e.haystack.contains(token) { - g = SUBSTRING; + } + if g > SUBSTRING && e.haystack.contains(token) { + g = SUBSTRING; + } + let g = if initials { + g.min(LABEL_PREFIX) + } else if g == NONE { + SUBSTRING + } else { + g + }; + described |= g == DESCRIPTION_WORD; + let field = match g { + LABEL_TYPO => Some(LABEL), + PATH_TYPO => Some(PATH), + _ => None, + }; + if let Some(field) = field { + typo = true; + if let Some(near) = typos.get(k).and_then(|near| index.nearest_of(near, i, &[field])) { + splice(&mut corrected, &mut copied, k, token, near); + splice(&mut meant, &mut meant_copied, k, token, near); + } + } + let fields: &[u8] = match g { + LABEL_SYNONYM => &[LABEL, LABEL_STEMMED], + PATH_SYNONYM => &[PATH, PATH_STEMMED], + _ => &[], + }; + if !fields.is_empty() { + synonym = true; + if let Some(same) = meanings.get(k).and_then(|same| index.nearest_of(same, i, fields)) { + splice(&mut meant, &mut meant_copied, k, token, same); } } - let g = if initials { g.min(LABEL_PREFIX) } else { g.min(SUBSTRING) }; worst = worst.max(g); sum += u32::from(g); } if !(substring || all_indexed || initials) { continue; } - let tier = phrase(e, &query, initials); + let tier = if typo { + corrected.push_str(query.get(copied..).unwrap_or_default()); + phrase(e, &corrected, false) + } else { + phrase(e, &query, initials) + }; + let meant_tier = if synonym { + meant.push_str(query.get(meant_copied..).unwrap_or_default()); + phrase(e, &meant, false) + } else { + tier + }; let length = split_name(&e.shown).0.chars().count(); - ranked.push(((tier, worst, sum, e.kind, length), place)); + ranked.push(((described, typo, tier, worst, sum, meant_tier, e.kind, length), place)); } ranked.sort_by_key(|&(key, place)| (key, place)); ranked.into_iter().map(|(_, place)| place).collect() @@ -460,6 +821,10 @@ pub(crate) fn menu_homes(native: bool) -> HashMap { out.entry(key(id, p)).or_insert_with(|| (path.join(" › "), *label)); + // Window › Learn runs `window.learn`, which is a result of its own too. + if *id == "window.learn" { + out.entry((*id).to_string()).or_insert_with(|| (path.join(" › "), *label)); + } } menus::Item::Sub(name, children) => { path.push(name); @@ -510,12 +875,19 @@ mod tests { kind: kind(id, home.as_deref()), home, menu_item: "", + label_at: 0, + names_item: false, } } /// `entries` with their index. fn synthetic(entries: Vec) -> Catalog { - let index = Index::build(&entries, &[]); + described(entries, &[]) + } + + /// `entries` with their index, the params text of each in `params`. + fn described(entries: Vec, params: &[&str]) -> Catalog { + let index = Index::build(&entries, &[], params, |_| None); Catalog { list: entries, index, ranked: std::sync::Mutex::new(None) } } @@ -704,6 +1076,299 @@ mod tests { } } + /// Edits are counted up to a bound: a changed, inserted or removed character, or two adjacent + /// characters swapped, is one edit, and words further apart than the bound give none. + #[test] + fn edits_are_counted_up_to_a_bound() { + let edits = |a: &str, b: &str, bound: usize| edits_within(&a.chars().collect::>(), &b.chars().collect::>(), bound); + for (a, b, bound, expected) in [ + ("group", "group", 1, Some(0)), + ("gruop", "group", 1, Some(1)), + ("elipse", "ellipse", 1, Some(1)), + ("rectange", "rectangle", 2, Some(1)), + ("eyedroper", "eyedropper", 2, Some(1)), + ("recktanglee", "rectangle", 2, Some(2)), + ("grop", "group", 1, Some(1)), + ("grap", "group", 1, None), + ("ab", "abcd", 1, None), + ("ca", "abc", 2, None), + ("abcd", "wxyz", 2, None), + ("über", "uber", 1, Some(1)), + ("", "ab", 2, Some(2)), + ] { + assert_eq!(edits(a, b, bound), expected, "{a} {b}"); + assert_eq!(edits(b, a, bound), expected, "{b} {a}"); + } + assert_eq!(typo_bound("pen"), None); + assert_eq!(typo_bound("elip"), Some(1)); + assert_eq!(typo_bound("rectang"), Some(1)); + assert_eq!(typo_bound("rectange"), Some(2)); + for w in ["群組群組", "かなかなか", "한국어단어", "zz群組"] { + assert_eq!(typo_bound(w), None, "{w}"); + } + } + + /// A query word with a typo finds a result whose label or menu path holds the word, below every + /// result matched without a typo, and a word that is a word or a word start of some result, a + /// word of fewer than 4 letters, an id and a word of a script written without spaces get no + /// typo matches. + #[test] + fn a_word_with_a_typo_finds_the_result() { + let c = synthetic(vec![entry("Zz Group", "a.one"), entry("Zz Cut", "b.two"), entry("Zz Rectangle", "c.three")]); + assert_eq!(ranked(&c, "gruop"), ["a.one"], "two letters swapped"); + assert_eq!(ranked(&c, "gruop zz"), ["a.one"]); + assert_eq!(ranked(&c, "cutx"), ["b.two"]); + assert!(ranked(&c, "cux").is_empty(), "3 letters"); + assert_eq!(ranked(&c, "recktanglee"), ["c.three"], "two edits in a longer word"); + assert!(ranked(&c, "rectanglexxx").is_empty()); + // Below a result whose name holds the word as text, and below one that holds it whole. + let c = synthetic(vec![entry("Zz Color", "a.one"), entry("Zz Bcolrb", "b.two")]); + assert_eq!(ranked(&c, "colr"), ["b.two", "a.one"]); + let c = synthetic(vec![entry("Color", "a.one"), entry("Zz Bcolrb", "b.two")]); + assert_eq!(ranked(&c, "colr"), ["b.two", "a.one"], "also when the word spelled right is the label"); + let c = synthetic(vec![entry("Zz Color", "a.one"), entry("Zz Colr", "b.two")]); + assert_eq!(ranked(&c, "colr"), ["b.two"], "a word some result holds gets no typo matches"); + // A word of the label before a word of the menu path. + let c = synthetic(vec![entry("Color › Zz Other", "a.one"), entry("Zz Color", "b.two")]); + assert_eq!(ranked(&c, "colr"), ["b.two", "a.one"]); + // Ids and words of scripts written without spaces. + let c = synthetic(vec![entry("Zz One", "group.one"), entry("物件 › 群組群組", "b.two")]); + assert!(ranked(&c, "gruop").is_empty()); + assert!(ranked(&c, "群組群物").is_empty()); + // A word of Latin letters followed by Han letters, one edit from "abcd", is not compared. + let c = synthetic(vec![entry("Zz Abc群", "a.one")]); + assert!(ranked(&c, "abcd").is_empty()); + // The whole query is read with the word it is a typo of: "gruop" names Group as "group" does. + let c = synthetic(vec![entry("Group Selection Tool", "tool:groupSelection"), entry("Object › Group", "object.group")]); + assert_eq!(ranked(&c, "gruop"), ranked(&c, "group")); + assert_eq!(ranked(&c, "gruop").first().map(String::as_str), Some("object.group")); + // The rest of the query is read as typed, `›` included. + let c = synthetic(vec![entry("Object › Group Zz Tool", "tool:zz"), entry("Object › Group", "object.group")]); + assert_eq!(ranked(&c, "object › group"), ["object.group", "tool:zz"]); + assert_eq!(ranked(&c, "object › gruop"), ranked(&c, "object › group")); + // A label typo is read with the word of the label, even when a word of the menu path is + // nearer: "abcdefgh" reads as "abcdefyy" in the first, which is then its label. + let c = synthetic(vec![entry("Abcdefyy Zz", "tool:b"), entry("Abcdefgx › Abcdefyy", "a.one")]); + assert_eq!(ranked(&c, "abcdefgh"), ["a.one", "tool:b"]); + } + + /// A query word with a typo meets at most 32 words, the nearest first, and a long word with no + /// match finds nothing. + #[test] + fn a_typo_meets_at_most_32_words() { + // 35 words one edit from the query and one word two edits from it, which sorts before them. + let near = ('a'..='z').chain('0'..='9').filter(|&ch| ch != 'q'); + let mut entries: Vec = near.enumerate().map(|(i, ch)| entry(&format!("Abcdefg{ch}"), &format!("a.n{i}"))).collect(); + entries.insert(0, entry("Abcdeaxq", "far.one")); + let c = synthetic(entries); + let found = ranked(&c, "abcdefgq"); + assert_eq!(found.len(), 32, "{found:?}"); + assert!(!found.contains(&"far.one".to_string())); + let c = synthetic(vec![entry("Abcdeaxq", "far.one")]); + assert_eq!(ranked(&c, "abcdefgq"), ["far.one"], "two edits in a word of 8 letters"); + assert!(ranked(&c, &"q".repeat(30)).is_empty()); + } + + /// On the English results, misspelled words list first the commands the word spelled right + /// lists first by labels, menu paths and ids (a typo does not match descriptions), the tool among + /// the first four, and a word of 3 letters is not read as a typo. + #[test] + fn misspelled_words_find_the_command() { + let c = catalog(Lang::EN, false); + let first = |q: &str| ranked(&c, q).first().cloned().unwrap_or_default(); + assert_eq!(first("gruop"), "object.group"); + let plain = Index::build(&c.list, &[], &[], |_| None); + let id = |&i: &u32| c.list.get(i as usize).map(|e| e.id.clone()).unwrap_or_default(); + for (typo, word, tool) in [ + ("eyedroper", "eyedropper", "tool:eyedropper"), + ("rectange", "rectangle", "tool:rectangle"), + ("elipse", "ellipse", "tool:ellipse"), + ("gruop", "group", "tool:groupSelection"), + ] { + 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(); + assert_eq!(top(typo), spelled_right, "{typo}"); + assert!(place(&c, typo, tool).is_some_and(|p| p < 4), "{typo}: {:?}", ranked(&c, typo)); + } + assert_eq!(first("pen"), "tool:pen"); + assert!(place(&c, "pen", "file.open").is_some(), "Open… holds the text"); + } + + /// A query word finds a result whose label or menu path holds another word of its group of words + /// with the same meaning: below a result whose label holds the word itself, above one whose menu + /// path holds the word, and with a menu path word of the group last. A stem form of the query word + /// and of a result's word meet the group too; ids, word starts and words of no group do not. + #[test] + fn a_word_with_the_same_meaning_finds_the_result() { + let c = synthetic(vec![ + entry("Delete › Zz Path", "d.four"), + entry("Remove › Zz Other", "c.three"), + entry("Zz Delete", "a.one"), + entry("Zz Remove", "b.two"), + ]); + assert_eq!(ranked(&c, "remove"), ["b.two", "a.one", "c.three", "d.four"]); + assert!(ranked(&c, "remo zz").iter().all(|id| id != "a.one" && id != "d.four"), "a word start is not looked up"); + let c = synthetic(vec![entry("Zz Reflect…", "a.one"), entry("Zz Reflecting", "b.two"), entry("Zz One", "reflect.one")]); + assert_eq!(ranked(&c, "flipped zz"), ["a.one", "b.two"], "stem forms on both sides, and no id"); + let c = synthetic(vec![entry("Zz Unite", "a.one"), entry("Zz Merge", "b.two")]); + assert_eq!(ranked(&c, "merge"), ["b.two"], "merge is in no group"); + assert_eq!(ranked(&c, "combine"), ["a.one"]); + // Among results that match equally well, the whole query read with the word of the same + // meaning ("colour" as "color") puts the label Color first, but never above a label that + // holds the query word itself. + let c = synthetic(vec![entry("Zz Color", "tool:zz"), entry("Color", "panel:color"), entry("Zz Colour", "c.three")]); + assert_eq!(ranked(&c, "colour"), ["c.three", "panel:color", "tool:zz"]); + } + + /// A catalog row adds words in the UI language to a group, and a word that is not a single word + /// or that is a word of another group is left out. + #[test] + fn a_catalog_row_adds_words_to_a_group() { + let entries = || vec![entry("Zz Delete", "a.one")]; + let row = |key: &str| (key == "remove, delete, erase, clear").then(|| "Entfernen, ganz weg, text".to_string()); + let with = Catalog { list: entries(), index: Index::build(&entries(), &[], &[], row), ranked: std::sync::Mutex::new(None) }; + assert_eq!(ranked(&with, "entfernen"), ["a.one"]); + assert!(ranked(&with, "ganz weg").is_empty(), "two words are left out"); + assert!(ranked(&with, "text").is_empty(), "text stays in its own group"); + let without = synthetic(entries()); + assert!(ranked(&without, "entfernen").is_empty(), "only while the row's language is the UI language"); + } + + /// A description is the params text without the groups of its schema and result: one fixture + /// of each shape the params texts take. + #[test] + fn a_description_leaves_out_the_schema_and_the_result() { + for (params, expected) in [ + // A schema, prose and a result. + ("{a: 1, b?: bool (true)} make it so → {changed, ids}", "make it so"), + // A quoted brace inside a schema. + ("{sep: \"}\" or \"{\" (\"}\")} split the text", "split the text"), + // A schema only. + ("{radius: pt (10)}", ""), + // An empty schema, then prose with no arrow. + ("{} choose the Corner Tool", "choose the Corner Tool"), + // Prose after the result. + ("{from?: index} → {index}: moves the document", ": moves the document"), + // Nested braces and brackets. + ("{a: {b: 1}, c: [x, {y}]} trims the path", "trims the path"), + // Alternative schemas. + ("{id, dx} or {items: [{id}…], dx} move anchors", "or move anchors"), + // A result in brackets or parentheses, and a result written as words. + ("{} → [name…] for the active document", "for the active document"), + ("{id} → ({x, y}) its place", "its place"), + ("{id} → its id.", "→ its id."), + // A group inside parentheses is text, and so is a group that is never closed. + ("fits it (as {x} does) here", "fits it (as {x} does) here"), + ("{a: 1 never closed", "{a: 1 never closed"), + // No group at all. + ("plain words\n here", "plain words here"), + ("", ""), + ] { + assert_eq!(description(params), expected, "{params}"); + } + // A long description ends at the end of a word. + let cut = description(&"word ".repeat(100)); + assert!(cut.chars().count() <= DESCRIPTION_CHARS && cut.ends_with(" word"), "{cut}"); + let cut = description(&format!("{}handles", "abcd ".repeat(59))); + assert!(cut.chars().count() <= DESCRIPTION_CHARS && cut.ends_with(" abcd"), "{cut}"); + let whole = format!("{}handles", "abcd ".repeat(58)); + assert_eq!(description(&whole), whole); + assert!(description_words("the and ids true false null of a 16 10pt x").eq(["10pt"])); + assert!(description_words("image's 'quoted' png").eq(["image's", "quoted", "png"])); + } + + /// A word of a description finds the result as a whole word, a stem form, a word start or a word + /// with the same meaning, below a result that holds the word in its label or menu path or inside + /// a word. A schema's words, words left out of descriptions and typos do not find it. + #[test] + fn a_word_of_the_description_finds_the_result() { + let c = described( + vec![ + entry("Zz Alpha", "a.one"), + entry("Zz Background", "b.two"), + entry("Zz Underbackground", "c.three"), + entry("Background › Zz Delta", "d.four"), + ], + &["{corners?: bool (true)} make the background of the images transparent → {changed}", "", "", ""], + ); + assert_eq!(ranked(&c, "transparent"), ["a.one"]); + assert_eq!(ranked(&c, "making images"), ["a.one"], "stem forms"); + assert_eq!(ranked(&c, "transp"), ["a.one"], "a word start"); + assert_eq!(ranked(&c, "background"), ["b.two", "d.four", "c.three", "a.one"]); + assert_eq!(ranked(&c, "bg"), ["b.two", "d.four", "a.one"], "a word with the same meaning"); + assert_eq!(ranked(&c, "transparent background"), ["a.one"]); + assert!(ranked(&c, "corners").is_empty(), "a word of the schema"); + assert!(ranked(&c, "changed").is_empty(), "a word of the result"); + assert!(ranked(&c, "the").is_empty(), "a word left out"); + assert!(ranked(&c, "trasnparent").is_empty(), "a typo"); + assert!(synthetic(vec![entry("Zz Alpha", "a.one")]).index.find("transparent").is_none()); + } + + /// A result found only by its description ranks below a result found through a typo of a word + /// of its label: "centr" starts "centred" in a description and is a typo of "center". A result + /// matched both ways ranks as matched through the typo. + #[test] + fn a_description_match_ranks_below_a_typo() { + let c = described(vec![entry("Zz Beta", "b.two"), entry("Zz Center", "a.one")], &["{} keeps the art centred on the page", ""]); + assert_eq!(ranked(&c, "centr"), ["a.one", "b.two"]); + assert_eq!(ranked(&c, "zz centr"), ["a.one", "b.two"]); + let both = described(vec![entry("Zz Center", "a.one"), entry("Center", "c.three")], &["", "{} keeps the art centred on the page"]); + assert_eq!(ranked(&both, "centr"), ["c.three", "a.one"]); + } + + /// On the English results, words of what a command does find it: "transparent background" + /// lists Remove Background… near the top, and "png" lists it below every result with png in its + /// name or menu path, while a word of its schema alone ("corners") does not list it. + #[test] + fn words_of_a_description_find_the_command() { + let c = catalog(Lang::EN, false); + let remove = "addon.image.removeBackground"; + let text = super::super::params_texts(&c.list); + let at = c.list.iter().position(|e| e.id == remove).unwrap(); + assert!(description(text[at]).starts_with("make the background of each image transparent"), "{}", description(text[at])); + assert!(substring_rule(&c, "transparent background").len() < ranked(&c, "transparent background").len()); + assert!(place(&c, "transparent background", remove).is_some_and(|p| p < 3), "{:?}", ranked(&c, "transparent background")); + let png = ranked(&c, "png"); + let below = png.iter().position(|id| id == remove).unwrap(); + let named = |e: &Entry| names(e).chain(e.home.as_deref()).any(|n| n.to_lowercase().contains("png")); + let with_png: Vec = c.list.iter().filter(|e| named(e)).filter_map(|e| png.iter().position(|id| *id == e.id)).collect(); + assert!(!with_png.is_empty() && with_png.iter().all(|&p| p < below), "{png:?}"); + assert!(place(&c, "corners", remove).is_none()); + assert!(place(&c, "corners", "effect:stylize.roundCorners").is_some_and(|p| p < 3), "{:?}", ranked(&c, "corners")); + } + + /// On the English results, everyday words find commands whose names use another word, and a + /// result whose label holds a word with the same meaning as the query ranks above one that holds + /// the query only in its menu path. + #[test] + fn words_with_the_same_meaning_find_the_command() { + let c = catalog(Lang::EN, false); + let first = |q: &str| ranked(&c, q).first().cloned().unwrap_or_default(); + let within = |q: &str, id: &str, n: usize| place(&c, q, id).is_some_and(|p| p < n); + for q in ["remove bg", "outline text", "flip", "combine", "vectorize", "colour"] { + assert!(substring_rule(&c, q).len() < ranked(&c, q).len(), "{q} finds more than before"); + } + assert_eq!(first("remove bg"), "addon.image.removeBackground"); + assert_eq!(first("outline text"), "type.createOutlines"); + assert!(within("flip", "object.reflect", 3), "{:?}", ranked(&c, "flip")); + assert!(within("combine", "object.pathfinder.unite", 3), "{:?}", ranked(&c, "combine")); + assert!(ranked(&c, "vectorize").iter().take(3).any(|id| id.starts_with("imageTrace.")), "{:?}", ranked(&c, "vectorize")); + assert_eq!(first("colour"), "panel:color", "{:?}", ranked(&c, "colour")); + // A word that only starts other labels is in a group, and its labels follow the direct match. + assert_eq!(first("unite"), "object.pathfinder.unite"); + assert!(place(&c, "unite", "object.slice.combine").is_some(), "{:?}", ranked(&c, "unite")); + assert!(place(&c, "delete", "view.guides.clear").is_some(), "{:?}", ranked(&c, "delete")); + assert!(place(&c, "settings", "edit.preferences").is_some(), "{:?}", ranked(&c, "settings")); + let merge = ranked(&c, "merge"); + let unite = merge.iter().position(|id| id == "object.pathfinder.unite"); + let named = |id: &String| c.list.iter().any(|e| &e.id == id && split_name(&e.shown).0 == "Merge"); + assert!(merge.first().is_some_and(named), "{merge:?}"); + assert!(unite.is_none() || merge.iter().rposition(named) < unite, "{merge:?}"); + let (scale, vertical) = (place(&c, "type", "type.scaleTextAttributes"), place(&c, "type", "type.orientation.vertical")); + assert!(scale.is_some() && scale < vertical, "{scale:?} {vertical:?}"); + } + /// The application menu of the native Mac menu bar holds the items [`menu_homes`] puts there, /// under the same submenus. #[test] @@ -949,8 +1614,8 @@ mod tests { assert_eq!(of("tool:pen"), None); // The home's words find the result: Preferences… under the native bar's Settings. let native_catalog = catalog(Lang::EN, true); - assert!(place(&native_catalog, "settings pref", "edit.preferences").is_some()); - assert!(place(&c, "settings pref", "edit.preferences").is_none()); + assert!(place(&native_catalog, "vectorcraft settings pref", "edit.preferences").is_some()); + assert!(place(&c, "vectorcraft settings pref", "edit.preferences").is_none()); // The menu item's own label finds the result too: File › Exit runs Quit VectorCraft. assert!(place(&c, "exit", "app.quit").is_some()); } @@ -972,10 +1637,32 @@ mod tests { let c = catalog(Lang::EN, false); let built = started.elapsed(); let started = std::time::Instant::now(); - let index = Index::build(&c.list, &[]); + let params = super::super::params_texts(&c.list); + let index = Index::build(&c.list, &[], ¶ms, |_| None); println!("catalog {built:?}, index alone {:?}, {} results, {} bytes", started.elapsed(), c.list.len(), index.bytes()); + let started = std::time::Instant::now(); + let without = Index::build(&c.list, &[], &[], |_| None); + println!("index without descriptions {:?}, {} bytes", started.elapsed(), without.bytes()); let long = "q".repeat(200); - for q in ["e", "ea", "select", "bring front", "zzzz", long.as_str()] { + let typos = "gruop elipse rectange eyedroper trasnform patern gradeint symbl"; + let repeated = format!("{typos} ").repeat(3); + let queries = [ + "e", + "ea", + "select", + "bring front", + "zzzz", + "eyedroper", + "gruop zz", + "remove bg", + "colour", + "transparent background", + "png", + typos, + repeated.as_str(), + long.as_str(), + ]; + for q in queries { let started = std::time::Instant::now(); let runs = 100; for _ in 0..runs { diff --git a/crates/ui-egui/src/palette/words.rs b/crates/ui-egui/src/palette/words.rs new file mode 100644 index 0000000000..44176dbd24 --- /dev/null +++ b/crates/ui-egui/src/palette/words.rs @@ -0,0 +1,125 @@ +//! Words that mean the same thing when searching the command palette: VectorCraft's own groups, +//! written for this table. A query word in a group also finds results whose label or menu path +//! holds another word of its group ([`super::search`]). +//! +//! A word that is the whole label of a command stays out of a group whose other words name a +//! different command: Merge is the label of Pathfinder and Live Paint commands that are not Unite, +//! and Mirror is the label of a repeat that is not Reflect…, so these are in no group. Insert is left +//! out too, since it starts the labels of type commands that are not Place…. A word that only starts +//! or ends other labels can be in a group, and a search for another word of its group also lists +//! those labels: "unite" lists Combine Slices after Unite, and "delete" lists Clear Guides. Plural and +//! verb forms that the search's English stem forms already join (round and rounded) are not groups. +//! +//! 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 joined by ", ". The words join the group +//! while that language is the UI language. No catalog has to have these rows. The search splits +//! labels into words only at spaces and punctuation, so in a language written without spaces a row's +//! word finds only a label that is that word alone. + +/// The groups: lowercase single English words, at most `MAX_WORDS` in a group and `MAX_GROUPS` +/// groups, no word longer than [`MAX_CHARS`] characters and no word in two groups. +pub(crate) const GROUPS: &[&[&str]] = &[ + &["remove", "delete", "erase", "clear"], + &["background", "bg"], + &["image", "picture", "photo", "img", "bitmap"], + &["text", "type"], + &["reflect", "flip"], + &["unite", "combine"], + &["trace", "vectorize"], + &["color", "colour"], + &["gray", "grey"], + &["grayscale", "greyscale"], + &["center", "centre"], + &["duplicate", "clone"], + &["zoom", "magnify"], + &["rotate", "turn", "spin"], + &["scale", "resize"], + &["opacity", "transparency"], + &["font", "typeface"], + &["preferences", "settings", "prefs"], + &["artboard", "canvas"], + &["swatch", "palette"], + &["eyedropper", "dropper"], +]; + +/// The most groups [`GROUPS`] may hold. +#[cfg(test)] +const MAX_GROUPS: usize = 60; +/// The most words a group may hold. +#[cfg(test)] +const MAX_WORDS: usize = 6; +/// The most characters a word may have. +pub(crate) const MAX_CHARS: usize = 20; + +/// The context of a catalog row that adds a group's words in its language. +pub(crate) const CONTEXT: &str = "search"; + +/// The source text of group `group`'s row in a catalog: its words joined by ", ". +pub(crate) fn row_key(group: &[&str]) -> String { + group.join(", ") +} + +/// The words of a catalog row's translation `text`, each trimmed and lowercased with its runs of +/// whitespace made one space, and whether each is a single word of at most [`MAX_CHARS`] +/// characters that the search can look up. +pub(crate) fn row_words(text: &str) -> impl Iterator + '_ { + text.split(',').map(|w| { + let w = super::search::normalize(w); + let single = !w.is_empty() && w.chars().count() <= MAX_CHARS && super::search::is_one_word(&w); + (w, single) + }) +} + +/// What is wrong with a catalog's `search` row for `source` translated as `text`: a source that is +/// no group's [`row_key`], an empty word, a word that is not a single word, or a word that is a word +/// of another group. +#[cfg(test)] +pub(crate) fn row_problems(source: &str, text: &str) -> Vec { + let Some(group) = GROUPS.iter().position(|g| row_key(g) == source) else { + return vec![format!("{source:?} is not a group")]; + }; + let mut problems = vec![]; + for (w, single) in row_words(text) { + if w.is_empty() { + problems.push(format!("{source:?}: an empty word")); + } else if !single { + problems.push(format!("{source:?}: {w:?} is not a single word")); + } else if let Some(other) = GROUPS.iter().enumerate().find(|&(i, g)| i != group && g.contains(&w.as_str())) { + problems.push(format!("{source:?}: {w:?} is a word of {:?}", row_key(other.1))); + } + } + problems +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The table keeps to its limits: groups, words per group, characters per word, and each word + /// lowercase, a single word and in one group only. + #[test] + fn the_groups_keep_to_their_limits() { + assert!(GROUPS.len() <= MAX_GROUPS, "{} groups", GROUPS.len()); + let mut seen = std::collections::HashSet::new(); + for group in GROUPS { + assert!((2..=MAX_WORDS).contains(&group.len()), "{group:?}"); + for &w in *group { + assert!(w.chars().count() <= MAX_CHARS, "{w}"); + assert_eq!(super::super::search::normalize(w), w, "{w} is lowercase"); + assert!(super::super::search::is_one_word(w), "{w} is one word"); + assert!(seen.insert(w), "{w} is in two groups"); + } + } + } + + /// A catalog row passes when it names a group and adds single words of no other group, and fails + /// otherwise. + #[test] + fn catalog_rows_are_checked() { + assert!(row_problems("remove, delete, erase, clear", "entfernen, löschen").is_empty()); + assert_eq!(row_problems("remove, delete", "entfernen").len(), 1, "not a group's words"); + assert_eq!(row_problems("remove, delete, erase, clear", "entfernen,, löschen").len(), 1, "an empty word"); + assert_eq!(row_problems("remove, delete, erase, clear", "ganz entfernen").len(), 1, "two words"); + assert_eq!(row_problems("remove, delete, erase, clear", "Text").len(), 1, "a word of another group once lowercased"); + } +} diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index 18fbfc39a7..2e1b81e732 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -17,6 +17,7 @@ pub mod color_guide; pub mod color_themes; pub mod color_wheel; pub mod css_properties; +pub mod discover; pub mod doc_info; pub mod flattener_preview; pub mod glyphs; @@ -192,6 +193,7 @@ pub fn show_icon_panel(app: &mut VectorcraftApp, ui: &mut Ui, id: &str) { three_d::ID => three_d::show(app, ui), script_console::ID => script_console::show(app, ui), learn::ID => learn::show(app, ui), + discover::ID => discover::show(app, ui), crate::addons::cleanup::ID => crate::addons::cleanup::show(app, ui), crate::addons::color::ID => crate::addons::color::show(app, ui), crate::addons::packaging::ID => crate::addons::packaging::show(app, ui), diff --git a/crates/ui-egui/src/panels/blend.rs b/crates/ui-egui/src/panels/blend.rs index ebc182d238..9991e0b37a 100644 --- a/crates/ui-egui/src/panels/blend.rs +++ b/crates/ui-egui/src/panels/blend.rs @@ -55,13 +55,10 @@ fn available(app: &VectorcraftApp, cmd: &str) -> bool { /// Selection counts as its blend. fn selects_blend_without_spine(app: &VectorcraftApp) -> bool { let Some(st) = app.session.active().filter(|st| st.selection.symbol_part.is_none()) else { return false }; + let mut find = st.doc.nearest_finder(); st.selection.objects.iter().any(|id| { - let ancestry = st.doc.ancestry(*id).unwrap_or_default(); - let blend = ancestry.iter().rev().find_map(|a| match st.doc.node(*a).map(|n| &n.kind) { - Some(NodeKind::Blend { spec, .. }) => Some(spec.no_spine), - _ => None, - }); - blend == Some(true) + let blend = find.nearest(*id, |n| matches!(n.kind, NodeKind::Blend { .. })); + matches!(blend.map(|n| &n.kind), Some(NodeKind::Blend { spec, .. }) if spec.no_spine) }) } diff --git a/crates/ui-egui/src/panels/discover.rs b/crates/ui-egui/src/panels/discover.rs new file mode 100644 index 0000000000..1c3fd12262 --- /dev/null +++ b/crates/ui-egui/src/panels/discover.rs @@ -0,0 +1,336 @@ +//! Help searches the tools, menu commands, and built-in tutorials. + +use egui::Ui; +use serde::Serialize; +use serde_json::{Value, json}; + +use crate::{VectorcraftApp, menus}; + +pub const ID: &str = "discover"; +const MAX_QUERY: usize = 1024; + +#[derive(Clone, Debug, Serialize)] +pub struct Hit { + pub kind: &'static str, + pub id: String, + pub label: String, + pub path: Vec, + pub shortcut: String, + /// The English label and menu path that `label` and `path` translate, and a command's menu + /// params, kept to bring a retained result up to date ([`refresh`]). + #[serde(skip)] + english_label: String, + #[serde(skip)] + english_path: Vec, + #[serde(skip)] + params: Value, +} + +#[derive(Clone, Debug, Default)] +pub struct View { + pub query: String, + pub results: Vec, + pub selected: Option, + pub focus: bool, + /// The menu state ([`crate::native_menu::state_hash`]: commands run, shortcuts, the language, + /// recent files and more) the results were last brought up to date for. + current_for: Option, +} + +fn matches(query: &str, text: &str) -> bool { + let text = text.to_lowercase(); + query.split_whitespace().all(|word| text.contains(word)) +} + +fn now(app: &VectorcraftApp) -> u64 { + crate::native_menu::state_hash(app, None) +} + +/// Updates the retained results' labels, menu paths and shortcuts after the menu state changes (a +/// command, a shortcut or the UI language), keeping the query, the results' order and the selected +/// result. A command result takes its menu item's current label and place (Show Grid becomes Hide +/// Grid), and leaves the results when no menu lists it any more, such as a recent file that was +/// removed. +fn refresh(app: &mut VectorcraftApp) { + let stamp = now(app); + if app.ui.discover.current_for == Some(stamp) { + return; + } + let lang = crate::i18n::current(); + let entries = if app.ui.discover.results.iter().any(|hit| hit.kind == "command") { menus::menu_entries(app) } else { Vec::new() }; + let mut by_command: std::collections::HashMap<(&str, String), Vec<&menus::MenuEntry>> = std::collections::HashMap::new(); + for entry in &entries { + if let Some(id) = entry.command.as_deref() { + by_command.entry((id, entry.params.to_string())).or_default().push(entry); + } + } + let selected = app.ui.discover.selected.take(); + let mut kept = Vec::with_capacity(app.ui.discover.results.len()); + for (index, mut hit) in std::mem::take(&mut app.ui.discover.results).into_iter().enumerate() { + match hit.kind { + "tool" => { + hit.label = crate::i18n::tr(lang, &hit.english_label).into(); + hit.shortcut = crate::shortcut_editor::tool_shortcut(&hit.id).unwrap_or_default().into(); + } + "command" => { + let same = by_command.get(&(hit.id.as_str(), hit.params.to_string())).map_or(&[][..], Vec::as_slice); + let Some(entry) = same.iter().find(|e| e.path == hit.english_path).or_else(|| same.first()) else { + continue; + }; + hit.english_label = entry.label.clone(); + hit.english_path = entry.path.clone(); + hit.label = menus::shown_label(app, &hit.id, &hit.params, &hit.english_label); + hit.path = entry.shown_path.clone(); + hit.shortcut = menus::item_shortcut(&hit.id, &hit.params).or_else(|| menus::shortcut_of(&hit.id)).unwrap_or_default().into(); + } + _ => {} + } + if selected == Some(index) { + app.ui.discover.selected = Some(kept.len()); + } + kept.push(hit); + } + app.ui.discover.results = kept; + app.ui.discover.current_for = Some(stamp); +} + +fn search(app: &VectorcraftApp, query: &str) -> Vec { + let query = query.trim().to_lowercase(); + if query.is_empty() { + return Vec::new(); + } + let mut hits = Vec::new(); + let lang = crate::i18n::current(); + for tool in vectorcraft_tools::catalog::all_tools() { + let label = crate::i18n::tr(lang, tool.label); + if matches(&query, &format!("{} {label} {}", tool.label, tool.id)) { + hits.push(Hit { + kind: "tool", + id: tool.id.into(), + label: label.into(), + path: vec![], + shortcut: crate::shortcut_editor::tool_shortcut(tool.id).unwrap_or_default().into(), + english_label: tool.label.into(), + english_path: vec![], + params: Value::Null, + }); + } + } + for entry in menus::menu_entries(app) { + let Some(id) = entry.command else { continue }; + // The menu bar in the window has no VectorCraft menu; only the native macOS bar shows it. + if !cfg!(target_os = "macos") && entry.path.first().is_some_and(|title| title == "VectorCraft") { + continue; + } + let label = menus::shown_label(app, &id, &entry.params, &entry.label); + let path = entry.shown_path; + if matches(&query, &format!("{} {label} {} {} {id}", entry.label, entry.path.join(" "), path.join(" "))) { + hits.push(Hit { + kind: "command", + id, + label, + path, + shortcut: entry.shortcut, + english_label: entry.label, + english_path: entry.path, + params: entry.params, + }); + } + } + for skill in super::learn::catalog::SKILLS { + for tutorial in skill.tutorials { + if matches(&query, &format!("{} {} {}", skill.title, tutorial.title, tutorial.id)) { + hits.push(Hit { + kind: "tutorial", + id: tutorial.id.into(), + label: tutorial.title.into(), + path: vec![skill.title.into()], + shortcut: String::new(), + english_label: tutorial.title.into(), + english_path: vec![skill.title.into()], + params: Value::Null, + }); + } + } + } + hits +} + +fn results(app: &VectorcraftApp) -> Value { + json!({"query": app.ui.discover.query, "results": app.ui.discover.results, "selected": app.ui.discover.selected}) +} + +fn set_query(app: &mut VectorcraftApp, query: &str) { + app.ui.discover.current_for = Some(now(app)); + app.ui.discover.results = search(app, query); + app.ui.discover.query = query.into(); + app.ui.discover.selected = None; +} + +pub(crate) fn command(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option> { + let spec = menus::UI_COMMANDS.iter().find(|spec| spec.0 == id && id.starts_with("help.discover"))?; + if !(p.is_object() || p.is_null()) { + return Some(Err("`params` must be an object".into())); + } + if let Err(e) = vectorcraft_engine::cmd::params::check_keys(id, spec.3, p) { + return Some(Err(e.to_string())); + } + refresh(app); + Some(match id { + "help.discover" | "help.discover.search" => { + let query = match p.get("query") { + Some(Value::String(query)) => Some(query.as_str()), + None if id == "help.discover" => None, + _ => { + let key = "query"; + return Some(Err(format!("`{key}` must be a string"))); + } + }; + if let Some(query) = query { + if query.chars().take(MAX_QUERY + 1).count() > MAX_QUERY { + let label = "query"; + let max = MAX_QUERY; + return Some(Err(format!("{label} must be at most {max} characters"))); + } + set_query(app, query); + } + app.ui.discover.focus = true; + crate::panel_docking::reveal_panel(app, ID).map(|_| results(app)) + } + "help.discover.choose" => { + let hit = p + .get("index") + .and_then(Value::as_u64) + .and_then(|i| usize::try_from(i).ok()) + .and_then(|i| app.ui.discover.results.get(i).cloned().map(|hit| (i, hit))); + let Some((index, hit)) = hit else { + return Some(Err("index out of range".into())); + }; + let outcome = match hit.kind { + "tool" => app.run("learn.locateTool", json!({"tool": hit.id})), + "tutorial" => Ok(json!({"tutorial": hit.id})), + _ => Ok(json!({"command": hit.id, "path": hit.path, "shortcut": hit.shortcut})), + }; + outcome.and_then(|outcome| { + crate::panel_docking::reveal_panel(app, ID)?; + app.ui.discover.selected = Some(index); + app.ui.discover.focus = true; + Ok(json!({"result": hit, "location": outcome})) + }) + } + "help.discover.back" => { + app.ui.discover.selected = None; + app.ui.discover.focus = true; + Ok(results(app)) + } + _ => return None, + }) +} + +pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { + refresh(app); + let mut query = app.ui.discover.query.clone(); + let field = ui.add(egui::TextEdit::singleline(&mut query).char_limit(MAX_QUERY).hint_text(tl!("Search")).desired_width(f32::INFINITY)); + if std::mem::take(&mut app.ui.discover.focus) { + field.request_focus(); + } + if field.changed() + && let Err(e) = app.run("help.discover.search", json!({"query": query})) + { + app.status(e); + } + if (field.has_focus() || field.lost_focus()) + && !app.session.tool_busy() + && !app.session.tool_composing() + && ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Escape)) + { + if let Err(e) = app.run("window.panel.close", json!({"panel": ID})) { + app.status(e); + } + return; + } + let mut chosen = None; + let mut home = false; + let mut back = false; + let mut locate = None; + ui.horizontal(|ui| { + home = ui.button(tl!("Home")).clicked(); + if app.ui.discover.selected.is_some() { + back = ui.button(tl!("Back")).clicked(); + } + }); + crate::widgets::divider(ui); + if let Some(hit) = app.ui.discover.selected.and_then(|i| app.ui.discover.results.get(i)) { + ui.heading(&hit.label); + if !hit.path.is_empty() { + ui.label(hit.path.join(" › ")); + } + if !hit.shortcut.is_empty() { + ui.label(menus::pretty_shortcut(&hit.shortcut)); + } + if hit.kind == "tutorial" + && let Some((_, tutorial)) = super::learn::catalog::tutorial(&hit.id) + { + for (index, step) in tutorial.steps.iter().enumerate() { + ui.label(format!("{}. {}", index + 1, step.plain())); + if let Some(tool) = step.tool + && let Some(info) = vectorcraft_tools::tool_info(tool) + && ui.link(crate::i18n::tr(crate::i18n::current(), info.label)).clicked() + { + locate = Some(tool); + } + } + } + } else { + egui::ScrollArea::vertical().id_salt("discover-results").show(ui, |ui| { + if app.ui.discover.results.is_empty() && !query.trim().is_empty() { + ui.label(tl!("No results")); + } + for kind in ["tool", "command", "tutorial"] { + let label = match kind { + "tool" => tl!("Tools"), + "command" => tl!("Search Commands…"), + _ => tl!("Learn"), + }; + let mut heading = false; + for (index, hit) in app.ui.discover.results.iter().enumerate().filter(|(_, h)| h.kind == kind) { + if !heading { + crate::widgets::subheader(ui, label); + heading = true; + } + if ui.selectable_label(false, &hit.label).on_hover_text(hit.path.join(" › ")).clicked() { + chosen = Some(index); + } + } + } + }); + } + if home { + if let Err(e) = app.run("help.discover.search", json!({"query": ""})) { + app.status(e); + } + } else if back { + if let Err(e) = app.run("help.discover.back", json!({})) { + app.status(e); + } + } else if let Some(index) = chosen { + match app.run("help.discover.choose", json!({"index": index})) { + Ok(picked) => status_reason(app, &picked["location"]), + Err(e) => app.status(e), + } + } + if let Some(tool) = locate { + match app.run("learn.locateTool", json!({"tool": tool})) { + Ok(located) => status_reason(app, &located), + Err(e) => app.status(e), + } + } +} + +/// A `learn.locateTool` reply that could not mark its tool (`location: "unavailable"`) shows its +/// `reason` in the status bar. +fn status_reason(app: &mut VectorcraftApp, located: &Value) { + if let Some(reason) = located.get("reason").and_then(Value::as_str) { + app.status(reason); + } +} diff --git a/crates/ui-egui/src/panels/graphic_styles.rs b/crates/ui-egui/src/panels/graphic_styles.rs index 365a878421..2696c78c08 100644 --- a/crates/ui-egui/src/panels/graphic_styles.rs +++ b/crates/ui-egui/src/panels/graphic_styles.rs @@ -3,7 +3,8 @@ //! 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, applies it +//! 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 //! canvas or the Appearance panel's thumbnail dropped on the panel becomes a new style, and @@ -368,6 +369,8 @@ struct Events { new_from: Option, /// Art or an appearance dropped on a style with Alt held: the style takes this object's look. replaced: Option<(String, NodeId)>, + /// A style dropped on another with Alt held: the second (`.0`) takes the first's (`.1`) look. + restyled: Option<(String, String)>, /// The style the right button is held on. large: Option, /// A style is dragged over a tile or row. @@ -387,7 +390,8 @@ fn clicked(ui: &Ui, resp: &Response, name: &str) -> Option { /// Clicks, drags and the right button on the tile or row `resp` of style `i` of `d` (`list`: rows /// stack downwards). A drag from it carries the style ([`PanelDrag::GraphicStyle`]); a style -/// dragged over it lands before or after it by the pointer's half. Art (its first object) or the +/// dragged over it lands before or after it by the pointer's half, or with Alt held outlines it +/// and, released there, replaces it with the dragged style's look. Art (its first object) or the /// Appearance panel's thumbnail held over it with Alt outlines it, and released there replaces the /// style with that object's look; without Alt it is left to the list ([`zone_input`]). fn cell_input(ui: &Ui, resp: &Response, d: &Document, i: usize, list: bool, ev: &mut Events) { @@ -414,6 +418,11 @@ fn cell_input(ui: &Ui, resp: &Response, d: &Document, i: usize, list: bool, ev: if moving == name { // Dropped on itself: it stays where it is. resp.dnd_release_payload::(); + } else if alt_held(ui) { + widgets::drop_target_outline(ui, resp.rect); + if resp.dnd_release_payload::().is_some() { + ev.restyled = Some((name.clone(), moving.clone())); + } } else { let r = resp.rect; let at = ui.input(|i| i.pointer.interact_pos()).unwrap_or(r.center()); @@ -531,6 +540,9 @@ fn act(app: &mut VectorcraftApp, ui: &Ui, s: &Shown, ev: Events, picker: bool) { { run(app, "graphicStyle.redefine", json!({ "name": name, "id": id.0 })); } + if let Some((name, from)) = ev.restyled { + run(app, "graphicStyle.redefine", json!({ "name": name, "from": from })); + } match ev.click { Some(Click::Pick(name, _)) if picker => { app.run("graphicStyle.apply", json!({"name": name, "add": alt_held(ui)})).ok(); @@ -1535,10 +1547,10 @@ mod tests { assert_eq!(doc(&app).graphic_style("Red").unwrap().appearance, red.appearance, "{view:?}"); app.run("edit.undo", json!({})).unwrap(); - // A style dragged onto Red with Alt moves and replaces nothing. + // A style dragged onto Red without Alt moves and replaces nothing. let last = n.last().unwrap().clone(); egui::DragAndDrop::set_payload(&ctx, PanelDrag::GraphicStyle(last.clone())); - frame_at(&mut app, at, release(at, alt), alt); + frame_at(&mut app, at, release(at, none), none); assert_eq!(names(&app)[0], last, "{view:?}"); assert_eq!(doc(&app).graphic_style("Red").unwrap().appearance, red.appearance, "{view:?}"); app.run("edit.undo", json!({})).unwrap(); @@ -1557,6 +1569,91 @@ mod tests { } } + /// A style dropped on another with Alt held replaces that style's look with its own: the + /// replaced style keeps its name, place and id, and its art follows, in one undo step; the + /// dragged style and its art stay as they are. Without Alt the style moves; dropped on itself + /// it does nothing. + #[test] + fn a_style_dropped_on_another_with_alt_replaces_that_style() { + let mut app = app(); + let rect = app.session.active().unwrap().doc.layers[0].children().unwrap()[0].id; + app.run("paint.setFill", json!({"color": "#ff0000", "ids": [rect.0]})).unwrap(); + app.run("graphicStyle.new", json!({"name": "Red", "id": rect.0})).unwrap(); + app.run("graphicStyle.move", json!({"name": "Red", "to": 0})).unwrap(); + app.run("shape.ellipse", json!({"x": 60, "y": 60, "width": 20, "height": 20})).unwrap(); + let oval = app.session.active().unwrap().selection.objects[0]; + app.run("paint.setFill", json!({"color": "#00ff00", "ids": [oval.0]})).unwrap(); + app.run("graphicStyle.new", json!({"name": "Green", "id": oval.0})).unwrap(); + let ctx = egui::Context::default(); + let screen = Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(260.0, 600.0))); + // One frame of the panel with `events` and `modifiers` held: whether a drop-target outline + // the size of one style's tile or row is drawn around `at`. + let frame_at = |app: &mut VectorcraftApp, at: egui::Pos2, events: Vec, modifiers: egui::Modifiers| { + let events = std::iter::once(egui::Event::ModifiersChanged(modifiers)).chain(events).collect(); + let mut out = ctx.run_ui(egui::RawInput { screen_rect: screen, events, ..Default::default() }, |ui| show(app, ui)); + out.textures_delta.clear(); + let accent = Tokens::get(&ctx).accent; + out.shapes.iter().any(|c| match &c.shape { + egui::Shape::Rect(r) => r.stroke.width == 1.5 && r.stroke.color == accent && r.rect.contains(at) && r.rect.height() < 45.0, + _ => false, + }) + }; + let release = |at: egui::Pos2, modifiers: egui::Modifiers| { + let up = egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers }; + vec![egui::Event::PointerMoved(at), up] + }; + let (none, alt) = (egui::Modifiers::default(), egui::Modifiers::ALT); + let doc = |app: &VectorcraftApp| app.session.active().unwrap().doc.clone(); + let steps = |app: &VectorcraftApp| app.session.doc().unwrap().history.undo.len(); + let (red, green) = (doc(&app).graphic_style("Red").unwrap().clone(), doc(&app).graphic_style("Green").unwrap().clone()); + let (red_fill, green_fill) = (red.appearance.fill_paint(), green.appearance.fill_paint()); + assert_ne!(red_fill, green_fill); + // The first style: the top of the list's first row, or its first tile. + for (view, at) in [(View::SmallList, pos2(60.0, 9.0)), (View::Thumbnail, pos2(20.0, 20.0))] { + app.ui.graphic_styles_view = view; + frame_at(&mut app, at, vec![], none); + let n = names(&app); + assert_eq!(n[0], "Red", "{view:?}"); + let before = steps(&app); + // Held over Red with Alt it is outlined; without Alt it is not (the insertion marker shows instead). + egui::DragAndDrop::set_payload(&ctx, PanelDrag::GraphicStyle("Green".into())); + assert!(!frame_at(&mut app, at, vec![egui::Event::PointerMoved(at)], none), "{view:?}: no outline without Alt"); + assert!(frame_at(&mut app, at, vec![egui::Event::PointerMoved(at)], alt), "{view:?}: outlined with Alt"); + assert_eq!((names(&app), steps(&app)), (n.clone(), before), "{view:?}: holding it there changes nothing"); + + // Released there with Alt: Red takes Green's look and keeps its name, place and id. + frame_at(&mut app, at, release(at, alt), alt); + let d = doc(&app); + assert_eq!(names(&app), n, "{view:?}: no style moves"); + let g = d.graphic_style("Red").unwrap(); + assert_eq!((g.id, &g.appearance), (red.id, &green.appearance), "{view:?}"); + assert_eq!(d.node(rect).unwrap().appearance.fill_paint(), green_fill, "{view:?}: the linked rectangle follows"); + assert_eq!(d.node(rect).unwrap().extras().graphic_style, Some(red.id), "{view:?}"); + assert_eq!(d.graphic_style("Green").unwrap(), &green, "{view:?}: Green stays as it was"); + assert_eq!(d.node(oval).unwrap().extras().graphic_style, Some(green.id), "{view:?}: the oval stays linked to Green"); + assert_eq!(steps(&app), before + 1, "{view:?}: one undo step"); + app.run("edit.undo", json!({})).unwrap(); + let d = doc(&app); + assert_eq!(d.graphic_style("Red").unwrap(), &red, "{view:?}: undo restores the style"); + assert_eq!(d.node(rect).unwrap().appearance.fill_paint(), red_fill, "{view:?}"); + assert_eq!(d.node(rect).unwrap().extras().graphic_style, Some(red.id), "{view:?}"); + + // Red dropped on itself with Alt changes nothing and records nothing. + egui::DragAndDrop::set_payload(&ctx, PanelDrag::GraphicStyle("Red".into())); + frame_at(&mut app, at, release(at, alt), alt); + assert_eq!((names(&app), steps(&app)), (n.clone(), before), "{view:?}"); + assert_eq!(doc(&app).graphic_style("Red").unwrap(), &red, "{view:?}"); + + // Without Alt, Green moves before Red and Red keeps its look. + egui::DragAndDrop::set_payload(&ctx, PanelDrag::GraphicStyle("Green".into())); + frame_at(&mut app, at, release(at, none), none); + assert_eq!(names(&app)[0], "Green", "{view:?}"); + assert_eq!(doc(&app).graphic_style("Red").unwrap(), &red, "{view:?}"); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(names(&app), n, "{view:?}"); + } + } + #[test] fn shift_click_selects_a_range_and_cmd_click_adds_or_removes_one_style() { let mut app = app(); diff --git a/crates/ui-egui/src/panels/stroke.rs b/crates/ui-egui/src/panels/stroke.rs index f8dc10ac66..33faeec41e 100644 --- a/crates/ui-egui/src/panels/stroke.rs +++ b/crates/ui-egui/src/panels/stroke.rs @@ -416,7 +416,7 @@ pub(super) fn arrow_doc(mut a: Option, start: bool, w: f64, h: f64) - /// Draw an arrowhead preview (the head as the canvas draws it) in `r`: a line with the head at the /// left (`start`) or right end. -fn paint_arrow(ui: &Ui, r: Rect, a: Option<&Arrowhead>, start: bool, color: Color32) { +pub(crate) fn paint_arrow(ui: &Ui, r: Rect, a: Option<&Arrowhead>, start: bool, color: Color32) { if let Some(tex) = widgets::doc_preview(ui, &format!("arrow:{}:{start}", arrow_key(a)), r.size(), |w, h| arrow_doc(a.cloned(), start, w, h)) { ui.painter().image(tex.id(), r, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), color); } diff --git a/crates/ui-egui/src/panels/symbols.rs b/crates/ui-egui/src/panels/symbols.rs index e48a290bae..b50b7876cc 100644 --- a/crates/ui-egui/src/panels/symbols.rs +++ b/crates/ui-egui/src/panels/symbols.rs @@ -326,6 +326,10 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { // The symbols drawn selected: the ones Select All Unused picked, else the current one. let on = |n: &str| if marked.is_empty() { sel.as_deref() == Some(n) } else { marked.iter().any(|m| m == n) }; let mut clicked: Option<(String, bool)> = None; + // Art released on a symbol with Alt (Option) held redefines that symbol; while Alt art is over + // a symbol, the list does not take it as a new symbol. + let mut redefine: Option<(String, Vec)> = None; + let mut over_symbol = false; let list_rect = widgets::list_box(ui, |ui| { ui.set_min_height(110.0); ui.set_width(ui.available_width()); @@ -345,6 +349,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } chip(ui, &doc, &keys, egui::Rect::from_center_size(r.left_center() + vec2(3.0 + side / 2.0, 0.0), vec2(side, side)), n); ui.painter().text(r.left_center() + vec2(side + 10.0, 0.0), egui::Align2::LEFT_CENTER, n, egui::FontId::proportional(text), t.text); + if let Some(ids) = art_redefine_drop(ui, &resp, &doc, uid, &mut over_symbol) { + redefine = Some((n.clone(), ids)); + } let resp = resp.on_hover_text(n); if resp.double_clicked() { clicked = Some((n.clone(), true)); @@ -372,6 +379,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { Stroke::new(if on { 2.0 } else { 1.0 }, if on { t.accent } else { t.border }), StrokeKind::Inside, ); + if let Some(ids) = art_redefine_drop(ui, &resp, &doc, uid, &mut over_symbol) { + redefine = Some((n.clone(), ids)); + } let resp = resp.on_hover_text(n); if resp.double_clicked() { clicked = Some((n.clone(), true)); @@ -391,8 +401,19 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { ui.min_rect() }); let zone = ui.interact(list_rect, ui.scope_id().with("symbols-drop"), Sense::hover()); - if let Some(ids) = widgets::art_drop(ui, &zone) - && let Err(e) = app.run("symbol.new", json!({ "ids": ids, "type": "dynamic" })) + if !over_symbol && let Some(ids) = widgets::art_drop(ui, &zone) { + // Shift held at the release keeps the dropped art as ordinary art. + let mut p = json!({ "ids": ids, "type": "dynamic" }); + if modifiers_at_release(ui).shift { + p["keepArt"] = json!(true); + } + if let Err(e) = app.run("symbol.new", p) { + app.status(e); + } + } + // Redefine Symbol with the dropped art, which becomes an instance of it, in one undo step. + if let Some((name, ids)) = redefine + && let Err(e) = app.run("symbol.update", json!({ "name": name, "ids": ids })) { app.status(e); } @@ -420,6 +441,11 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { if widgets::icon_button_enabled(ui, "link-2-off", tl!("Break Link to Symbol"), false, inst, 24.0).clicked() { app.run("symbol.breakLink", json!({})).ok(); } + // Opens Symbol Options on the current symbol, as the panel menu's Symbol Options… does; + // Alt does the same. + if widgets::icon_button_enabled(ui, "dc-options", tl!("Symbol Options"), false, sel.is_some(), 24.0).clicked() { + app.run("ui.symbolOptions", json!({"edit": true, "name": sel})).ok(); + } ui.add_space((ui.available_width() - 2.0 * 28.0).max(0.0)); let new = widgets::icon_button_enabled(ui, "dc-new-item", tl!("New Symbol"), false, has_sel, 24.0); // A symbol dragged from the panel and dropped on New Symbol is duplicated, with or without @@ -430,8 +456,12 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } } else if new.clicked() { // Alt skips Symbol Options: the symbol is made under the default name, dynamic as the - // dialog's default. - let (cmd, p) = if ui.input(|i| i.modifiers.alt) { ("symbol.new", json!({"type": "dynamic"})) } else { ("ui.symbolOptions", json!({})) }; + // dialog's default. Shift keeps the selected art as ordinary art, with or without Alt. + let m = ui.input(|i| i.modifiers); + let (cmd, mut p) = if m.alt { ("symbol.new", json!({"type": "dynamic"})) } else { ("ui.symbolOptions", json!({})) }; + if m.shift { + p["keepArt"] = json!(true); + } app.run(cmd, p).ok(); } // Alt deletes an unused symbol without asking; a symbol with instances still asks. @@ -455,9 +485,13 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { let has_sel = app.session.active().is_some_and(|d| !d.selection.is_empty()); let inst = has_instances_selected(app); let name = json!({"name": sel}); + // Shift keeps the selected art as ordinary art instead of making it an instance. + let shift = ui.input(|i| i.modifiers.shift); + let redefine = if shift { json!({"name": sel, "keepArt": true}) } else { name.clone() }; + let new = if shift { json!({"keepArt": true}) } else { json!({}) }; let items: [(&str, bool, &str, Value); 3] = [ - (tl!("New Symbol…"), has_sel, "ui.symbolOptions", json!({})), - (tl!("Redefine Symbol"), has_sel && sel.is_some(), "symbol.update", name.clone()), + (tl!("New Symbol…"), has_sel, "ui.symbolOptions", new), + (tl!("Redefine Symbol"), has_sel && sel.is_some(), "symbol.update", redefine), (tl!("Duplicate Symbol"), sel.is_some(), "symbol.duplicate", name.clone()), ]; for (label, enabled, cmd, params) in items { @@ -537,6 +571,49 @@ fn symbol_dropped(ui: &Ui, button: &egui::Response, names: &[String], uid: Optio button.dnd_release_payload::().map(|_| name.clone()) } +/// The ids of the art dragged off the canvas of the active document `doc` (`uid`) and released +/// with Alt (Option) held on the symbol tile or row `item` this frame, if any. While such art is +/// held over `item` with Alt, `over` is set and `item` is outlined. Art of another document, or +/// whose objects `doc` no longer has, is not taken. Only the release of the primary button drops +/// the art; the release of another button ends the drag. +fn art_redefine_drop(ui: &Ui, item: &egui::Response, doc: &Document, uid: Option, over: &mut bool) -> Option> { + if !alt_at_release(ui) { + return None; + } + let held = item.dnd_hover_payload::()?; + let PanelDrag::Art(ids) = &*held else { return None }; + *over = true; + let ours = uid.is_some() && widgets::art_drag_doc(ui.ctx()) == uid; + if !ours || ids.is_empty() || !ids.iter().all(|id| doc.node(*id).is_some_and(|n| !n.is_layer())) { + return None; + } + widgets::drop_target_outline(ui, item.rect); + if !ui.input(|i| i.pointer.button_released(egui::PointerButton::Primary)) { + return None; + } + item.dnd_release_payload::().map(|_| ids.iter().map(|id| id.0).collect()) +} + +/// Whether Alt (Option) is held for a drop: when the primary button went up in this frame, as it +/// went up, else now. +fn alt_at_release(ui: &Ui) -> bool { + modifiers_at_release(ui).alt +} + +/// The modifiers held for a drop: when the primary button went up in this frame, as it went up, +/// else now. +fn modifiers_at_release(ui: &Ui) -> egui::Modifiers { + ui.input(|i| { + i.events + .iter() + .find_map(|e| match e { + egui::Event::PointerButton { button: egui::PointerButton::Primary, pressed: false, modifiers, .. } => Some(*modifiers), + _ => None, + }) + .unwrap_or(i.modifiers) + }) +} + /// The panel state key of the symbols Select All Unused picked. const MARKED: &str = "sym-unused"; @@ -769,6 +846,11 @@ mod tests { egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() } } + /// The primary button going up at `at` with Alt (Option) held. + fn alt_release(at: Pos2) -> egui::Event { + egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::ALT } + } + fn symbols(app: &mut VectorcraftApp) -> Vec { let list = app.run("symbol.list", json!({})).unwrap(); list["symbols"].as_array().unwrap().iter().map(|s| s["name"].as_str().unwrap_or_default().to_string()).collect() @@ -848,6 +930,193 @@ mod tests { menu_frame(ctx, app, vec![button(item, false)]); } + /// Clicks the menu item labeled `label` with `modifiers` held. + fn click_menu_held(ctx: &egui::Context, app: &mut VectorcraftApp, label: &str, modifiers: egui::Modifiers) { + let held = egui::Event::ModifiersChanged(modifiers); + let labels = menu_frame(ctx, app, vec![held.clone()]); + let item = labels.iter().find(|(t, _)| t.trim() == label).map(|(_, r)| r.center()).unwrap_or_else(|| panic!("{label} in the menu")); + let press = |pressed| egui::Event::PointerButton { pos: item, button: egui::PointerButton::Primary, pressed, modifiers }; + menu_frame(ctx, app, vec![held.clone(), egui::Event::PointerMoved(item), press(true)]); + menu_frame(ctx, app, vec![held, press(false)]); + } + + /// Redefine Symbol in the panel menu with Shift held updates the symbol and leaves the + /// selected art as ordinary art, still selected; without Shift the art becomes an instance. + #[test] + fn shift_redefine_symbol_in_the_menu_keeps_the_art_as_ordinary_art() { + let mut app = leaf_and_dot(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let rect = NodeId(app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 60, "height": 20})).unwrap()["id"].as_u64().unwrap()); + app.run("select.set", json!({"ids": [rect.0]})).unwrap(); + let dot_art = |app: &VectorcraftApp| app.session.active().unwrap().doc.symbols.iter().find(|s| s.name == "Dot").map(|s| s.art.clone()); + let before = dot_art(&app); + click_menu_held(&ctx, &mut app, "Redefine Symbol", egui::Modifiers::SHIFT); + assert_ne!(dot_art(&app), before, "Dot is redefined"); + assert_eq!(art(&app, "Dot"), (0, 1), "the rectangle stays ordinary art"); + assert_eq!(app.session.active().unwrap().selection.objects, vec![rect], "and stays selected"); + click_menu_held(&ctx, &mut app, "Redefine Symbol", egui::Modifiers::NONE); + assert_eq!(art(&app, "Dot"), (1, 0), "without Shift the rectangle becomes an instance"); + } + + /// `leaf_and_dot` with a selected 60 × 20 rectangle; returns its id. + fn leaf_dot_and_rect() -> (VectorcraftApp, NodeId) { + let mut app = leaf_and_dot(); + let rect = NodeId(app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 60, "height": 20})).unwrap()["id"].as_u64().unwrap()); + app.run("select.set", json!({"ids": [rect.0]})).unwrap(); + (app, rect) + } + + /// New Symbol… in the panel menu with Shift held opens Symbol Options, and its OK makes the + /// symbol and leaves the selected art as ordinary art, still selected, in one undo step, though + /// Shift is let go before OK; Cancel makes no symbol. Without Shift, OK makes the art an + /// instance. + #[test] + fn shift_new_symbol_in_the_menu_keeps_the_art_as_ordinary_art() { + let (mut app, rect) = leaf_dot_and_rect(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + click_menu_held(&ctx, &mut app, "New Symbol…", egui::Modifiers::SHIFT); + assert_eq!(dialog_kind(&app), Some(crate::dialogs::symbol_options::KIND)); + crate::dialogs::cancel(&mut app); + assert_eq!(symbols(&mut app), ["Leaf", "Dot"], "Cancel makes no symbol"); + click_menu_held(&ctx, &mut app, "New Symbol…", egui::Modifiers::SHIFT); + menu_frame(&ctx, &mut app, vec![egui::Event::ModifiersChanged(egui::Modifiers::NONE)]); + let undo = undo_len(&app); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(symbols(&mut app), ["Leaf", "Dot", "New Symbol"]); + assert_eq!(art(&app, "New Symbol"), (0, 1), "the rectangle stays ordinary art"); + assert_eq!(app.session.active().unwrap().selection.objects, vec![rect], "and stays selected"); + assert_eq!(undo_len(&app), undo + 1, "one undo step"); + click_menu_held(&ctx, &mut app, "New Symbol…", egui::Modifiers::NONE); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(art(&app, "New Symbol 2"), (1, 0), "without Shift the rectangle becomes an instance"); + } + + /// Clicks the panel's New Symbol button with `modifiers` held. + fn click_new(app: &mut VectorcraftApp, modifiers: egui::Modifiers) { + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + let out = frame_held(&ctx, app, vec![], modifiers); + let at = clickable(&out).into_iter().find(|(l, _)| l == "New Symbol").expect("a New Symbol button").1; + let press = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers }; + frame_held(&ctx, app, vec![egui::Event::PointerMoved(at), press(true), press(false)], modifiers); + } + + /// The New Symbol button with Shift held opens Symbol Options, whose OK keeps the selected art + /// as ordinary art; with Shift and Alt it makes the symbol at once under the default name and + /// keeps the art. Alt alone still makes the art an instance at once. + #[test] + fn shift_new_symbol_button_keeps_the_art_with_or_without_alt() { + let (mut app, rect) = leaf_dot_and_rect(); + click_new(&mut app, egui::Modifiers::SHIFT); + assert_eq!(dialog_kind(&app), Some(crate::dialogs::symbol_options::KIND)); + assert_eq!(symbols(&mut app).len(), 2, "no symbol before OK"); + crate::dialogs::confirm(&mut app).unwrap(); + assert_eq!(art(&app, "New Symbol"), (0, 1), "Shift: the rectangle stays ordinary art"); + assert_eq!(app.session.active().unwrap().selection.objects, vec![rect]); + let undo = undo_len(&app); + click_new(&mut app, egui::Modifiers::SHIFT | egui::Modifiers::ALT); + assert_eq!(dialog_kind(&app), None, "Alt skips Symbol Options"); + assert_eq!(symbols(&mut app), ["Leaf", "Dot", "New Symbol", "New Symbol 2"]); + assert_eq!(art(&app, "New Symbol 2"), (0, 1), "Shift and Alt: the rectangle stays ordinary art"); + assert_eq!(app.session.active().unwrap().selection.objects, vec![rect]); + assert_eq!(undo_len(&app), undo + 1, "one undo step"); + click_new(&mut app, egui::Modifiers::ALT); + assert_eq!(art(&app, "New Symbol 3"), (1, 0), "Alt alone: the rectangle becomes an instance"); + } + + /// The center of the panel's Symbol Options button, and of Break Link to Symbol and New Symbol + /// beside it, in a frame of `app`. + fn options_button(app: &mut VectorcraftApp) -> (Pos2, Pos2, Pos2) { + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + let found = clickable(&frame_held(&ctx, app, vec![], egui::Modifiers::NONE)); + let at = |label: &str| found.iter().find(|(l, _)| l == label).unwrap_or_else(|| panic!("a {label} button")).1; + (at("Break Link to Symbol"), at("Symbol Options"), at("New Symbol")) + } + + /// Clicks the panel at `at` with `modifiers` held. + fn click_at(app: &mut VectorcraftApp, at: Pos2, modifiers: egui::Modifiers) { + let ctx = egui::Context::default(); + frame_held(&ctx, app, vec![], modifiers); + let press = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers }; + frame_held(&ctx, app, vec![egui::Event::PointerMoved(at), press(true), press(false)], modifiers); + } + + /// The bottom bar's Symbol Options button sits between Break Link to Symbol and New Symbol and + /// opens Symbol Options on the current symbol, as the panel menu's item does, with or without + /// Alt, and adds no undo step; in a document without symbols it is disabled and opens nothing. + #[test] + fn symbol_options_button_edits_the_current_symbol() { + let mut app = leaf_and_dot(); + app.run("select.all", json!({})).unwrap(); + let (break_link, options, new) = options_button(&mut app); + assert!(break_link.x < options.x && options.x < new.x, "Break Link, Symbol Options, New Symbol: {break_link:?} {options:?} {new:?}"); + let undo = undo_len(&app); + for (current, modifiers) in [("Dot", egui::Modifiers::NONE), ("Leaf", egui::Modifiers::ALT)] { + app.run("symbol.setCurrent", json!({ "name": current })).unwrap(); + click_at(&mut app, options, modifiers); + let d = app.ui.dialog.as_ref().expect("Symbol Options opens"); + assert_eq!(d.kind, crate::dialogs::symbol_options::KIND); + assert_eq!((d.fields.get("name"), d.fields.get("__edit")), (Some(&json!(current)), Some(&json!(true))), "{modifiers:?}"); + crate::dialogs::cancel(&mut app); + } + assert_eq!(undo_len(&app), undo, "opening the dialog adds no undo step"); + assert_eq!(symbols(&mut app), ["Leaf", "Dot"]); + let mut empty = VectorcraftApp::new(Session::new(), Default::default()); + empty.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + for (app, disabled) in [(&mut app, false), (&mut empty, true)] { + let out = frame_held(&ctx, app, vec![], egui::Modifiers::NONE); + let nodes = &out.platform_output.accesskit_update.as_ref().expect("an accessibility tree").nodes; + let button = &nodes.iter().find(|(_, n)| n.label().is_some_and(|l| l.trim() == "Symbol Options")).expect("a Symbol Options button").1; + assert_eq!(button.is_disabled(), disabled, "disabled without a current symbol"); + } + click_at(&mut empty, options, egui::Modifiers::NONE); + assert_eq!(dialog_kind(&empty), None, "no symbol, no dialog"); + } + + /// Art dropped on the panel with Shift held as the primary button goes up becomes a new + /// symbol and stays ordinary art, still selected, though Shift is let go later in the same + /// frame; dropped without Shift, it becomes an instance. + #[test] + fn shift_art_drop_on_the_panel_keeps_the_art_as_ordinary_art() { + let (mut app, rect) = leaf_dot_and_rect(); + let ctx = egui::Context::default(); + let at = pos2(180.0, 60.0); + let release = |modifiers| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers }; + widgets::drag_art(&ctx, uid(&app).unwrap(), vec![rect]); + frame_held(&ctx, &mut app, vec![egui::Event::PointerMoved(at)], egui::Modifiers::SHIFT); + let undo = undo_len(&app); + let let_go = egui::Event::ModifiersChanged(egui::Modifiers::NONE); + frame_held(&ctx, &mut app, vec![release(egui::Modifiers::SHIFT), let_go], egui::Modifiers::SHIFT); + assert_eq!(symbols(&mut app).len(), 3, "a new symbol"); + assert_eq!(art(&app, "New Symbol"), (0, 1), "the rectangle stays ordinary art"); + assert_eq!(app.session.active().unwrap().selection.objects, vec![rect], "and stays selected"); + assert_eq!(undo_len(&app), undo + 1, "one undo step"); + widgets::drag_art(&ctx, uid(&app).unwrap(), vec![rect]); + frame_held(&ctx, &mut app, vec![egui::Event::PointerMoved(at)], egui::Modifiers::NONE); + frame_held(&ctx, &mut app, vec![release(egui::Modifiers::NONE)], egui::Modifiers::NONE); + assert_eq!(art(&app, "New Symbol 2"), (1, 0), "without Shift the rectangle becomes an instance"); + } + + /// `ui.symbolOptions` takes `keepArt` only as true or false, and only for a new symbol. + #[test] + fn symbol_options_checks_keep_art() { + let (mut app, _) = leaf_dot_and_rect(); + for bad in [json!("yes"), json!(1)] { + let e = app.run("ui.symbolOptions", json!({ "keepArt": bad })).unwrap_err(); + assert!(e.contains("`keepArt` must be true or false"), "{bad}: {e}"); + } + let e = app.run("ui.symbolOptions", json!({"edit": true, "name": "Dot", "keepArt": true})).unwrap_err(); + assert!(e.contains("only to a new symbol"), "{e}"); + assert_eq!(dialog_kind(&app), None); + app.run("ui.symbolOptions", json!({"edit": true, "name": "Dot", "keepArt": false})).unwrap(); + assert_eq!(dialog_kind(&app), Some(crate::dialogs::symbol_options::KIND)); + } + /// #4918: Select All Unused picks the symbols nothing places, Delete Symbol asks once and /// deletes them all in one undo step, and a click on a symbol picks one again. #[test] @@ -2418,6 +2687,177 @@ mod tests { assert_eq!(symbols(&mut app), ["Dot"], "the first document keeps its Dot"); } + /// The rects `out` outlines as drop targets (1.5 pt strokes). + fn drop_outlines(out: &egui::FullOutput) -> Vec { + out.shapes + .iter() + .filter_map(|c| match &c.shape { + egui::Shape::Rect(r) if (r.stroke.width - 1.5).abs() < 0.01 => Some(r.rect), + _ => None, + }) + .collect() + } + + /// Where symbol `name`'s tile or row is in the panel: its name in the list views, its tile (the + /// 44 pt squares, in panel order) in Thumbnail View. + fn item_at(ctx: &egui::Context, app: &mut VectorcraftApp, name: &str) -> Pos2 { + if app.ui.symbols_view != View::Thumbnail { + return panel_labels(ctx, app, &[name]).first().map(|l| l.1).unwrap_or_else(|| panic!("a {name} row")); + } + let out = frame_held(ctx, app, vec![], egui::Modifiers::NONE); + let tiles: Vec = out + .shapes + .iter() + .filter_map(|c| match &c.shape { + egui::Shape::Rect(r) if (r.rect.width() - 44.0).abs() < 0.01 && (r.rect.height() - 44.0).abs() < 0.01 => Some(r.rect), + _ => None, + }) + .collect(); + let i = symbols(app).iter().position(|n| n == name).unwrap_or_else(|| panic!("a {name} symbol")); + tiles.get(i).map(|r| r.center()).unwrap_or_else(|| panic!("a {name} tile in {tiles:?}")) + } + + /// The art of symbol `name` in the active document. + fn symbol_art(app: &VectorcraftApp, name: &str) -> Arc { + let doc = &app.session.active().unwrap().doc; + doc.symbols.iter().find(|s| s.name == name).map(|s| s.art.clone()).unwrap_or_else(|| panic!("a {name} symbol")) + } + + fn undo_len(app: &VectorcraftApp) -> usize { + app.session.active().unwrap().history.undo.len() + } + + /// Art dragged off the canvas and released with Alt (Option on macOS) held on a symbol's tile + /// or row, in each view, redefines that symbol and not the current one: its instances take the + /// art, the art becomes an instance of it, and no symbol is added, in one undo step. Only that + /// tile or row is outlined while the art is held over it with Alt. + #[test] + fn alt_art_drop_on_a_symbol_redefines_that_symbol_in_one_step() { + for view in ["thumbnail", "smallList", "largeList"] { + let mut app = leaf_and_dot(); + app.run("ui.panelView", json!({"panel": "symbols", "view": view})).unwrap(); + let shape = app.run("shape.rectangle", json!({"x": 200, "y": 120, "width": 40, "height": 20})).unwrap()["id"].as_u64().unwrap(); + let (leaf, dot) = (symbol_art(&app, "Leaf"), symbol_art(&app, "Dot")); + let placed = instance_of(&app, "Leaf").expect("a Leaf instance"); + let undo = undo_len(&app); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let (at, other) = (item_at(&ctx, &mut app, "Leaf"), item_at(&ctx, &mut app, "Dot")); + widgets::drag_art(&ctx, uid(&app).unwrap(), vec![NodeId(shape)]); + let out = frame_held(&ctx, &mut app, vec![egui::Event::PointerMoved(at)], egui::Modifiers::ALT); + let outlines = drop_outlines(&out); + assert_eq!(outlines.len(), 1, "{view}: only the Leaf item is outlined: {outlines:?}"); + assert!(outlines[0].contains(at) && !outlines[0].contains(other), "{view}: {outlines:?}"); + frame_held(&ctx, &mut app, vec![alt_release(at)], egui::Modifiers::ALT); + assert_eq!(symbols(&mut app), ["Leaf", "Dot"], "{view}: no symbol added"); + assert_eq!(undo_len(&app), undo + 1, "{view}: one undo step"); + // The Leaf instance there was takes the 40 × 20 rectangle's shape, where the old art was square. + let doc = app.session.active().unwrap().doc.clone(); + let shape = doc.node(placed).and_then(|n| n.geometric_bounds()).map(|b| b.width() / b.height()); + assert!(shape.is_some_and(|r| (r - 2.0).abs() < 1e-6), "{view}: Leaf is the dropped art: {shape:?}"); + assert!(Arc::ptr_eq(&dot, &symbol_art(&app, "Dot")), "{view}: the current symbol Dot is unchanged"); + assert_eq!(art(&app, "Leaf"), (2, 0), "{view}: the art became a Leaf instance"); + app.run("edit.undo", json!({})).unwrap(); + assert!(Arc::ptr_eq(&leaf, &symbol_art(&app, "Leaf")), "{view}: undo restores Leaf"); + assert_eq!(art(&app, "Leaf"), (1, 1), "{view}: undo restores the art"); + app.run("edit.redo", json!({})).unwrap(); + assert_eq!(art(&app, "Leaf"), (2, 0), "{view}: redo"); + } + } + + /// Alt held as the primary button goes up redefines the symbol, though Alt is let go later in + /// the same frame. + #[test] + fn alt_let_go_after_the_release_in_the_same_frame_still_redefines() { + let mut app = leaf_and_dot(); + let shape = app.run("shape.rectangle", json!({"x": 200, "y": 120, "width": 40, "height": 20})).unwrap()["id"].as_u64().unwrap(); + let leaf = symbol_art(&app, "Leaf"); + let undo = undo_len(&app); + let ctx = egui::Context::default(); + let at = item_at(&ctx, &mut app, "Leaf"); + widgets::drag_art(&ctx, uid(&app).unwrap(), vec![NodeId(shape)]); + frame_held(&ctx, &mut app, vec![egui::Event::PointerMoved(at)], egui::Modifiers::ALT); + frame_held(&ctx, &mut app, vec![alt_release(at), egui::Event::ModifiersChanged(egui::Modifiers::NONE)], egui::Modifiers::ALT); + assert_eq!(symbols(&mut app), ["Leaf", "Dot"], "no symbol added"); + assert!(!Arc::ptr_eq(&leaf, &symbol_art(&app, "Leaf")), "Leaf is redefined"); + assert_eq!(undo_len(&app), undo + 1, "one undo step"); + } + + /// Art released on a symbol without Alt makes a new symbol, as a drop elsewhere on the list + /// does, and leaves the symbol under the pointer as it was; nothing is outlined but the list. + #[test] + fn a_plain_art_drop_on_a_symbol_makes_a_new_symbol() { + let mut app = leaf_and_dot(); + let shape = app.run("shape.rectangle", json!({"x": 200, "y": 120, "width": 40, "height": 20})).unwrap()["id"].as_u64().unwrap(); + let leaf = symbol_art(&app, "Leaf"); + let ctx = egui::Context::default(); + let at = item_at(&ctx, &mut app, "Leaf"); + widgets::drag_art(&ctx, uid(&app).unwrap(), vec![NodeId(shape)]); + let out = frame_held(&ctx, &mut app, vec![egui::Event::PointerMoved(at)], egui::Modifiers::NONE); + let outlines = drop_outlines(&out); + assert!(outlines.len() == 1 && outlines[0].width() > 100.0, "the list is outlined, not the tile: {outlines:?}"); + frame(&ctx, &mut app, vec![button(at, false)]); + assert_eq!(symbols(&mut app).len(), 3, "a new symbol"); + assert!(Arc::ptr_eq(&leaf, &symbol_art(&app, "Leaf")), "Leaf is unchanged"); + } + + /// An Alt drop that cannot redefine the symbol under the pointer changes nothing, makes no new + /// symbol and adds no undo step: art of another document, objects the document no longer has, + /// no objects, and a release away from the panel are not outlined, and art holding an instance + /// of the symbol is refused when it is released. + #[test] + fn an_alt_art_drop_that_cannot_redefine_changes_nothing() { + let mut app = leaf_and_dot(); + let shape = app.run("shape.rectangle", json!({"x": 200, "y": 120, "width": 40, "height": 20})).unwrap()["id"].as_u64().unwrap(); + let instance = instance_of(&app, "Leaf").expect("a Leaf instance"); + let leaf = symbol_art(&app, "Leaf"); + let undo = undo_len(&app); + let ctx = egui::Context::default(); + let at = item_at(&ctx, &mut app, "Leaf"); + let doc = uid(&app).unwrap(); + let away = pos2(230.0, 395.0); + let cases = [ + ("another document's art", doc + 1, vec![NodeId(shape)], at, false), + ("objects the document lacks", doc, vec![NodeId(u64::MAX)], at, false), + ("no objects", doc, vec![], at, false), + ("a release away from the panel", doc, vec![NodeId(shape)], away, false), + ("a Leaf instance", doc, vec![instance], at, true), + ]; + for (case, from, ids, to, outline) in cases { + widgets::drag_art(&ctx, from, ids); + let out = frame_held(&ctx, &mut app, vec![egui::Event::PointerMoved(to)], egui::Modifiers::ALT); + assert_eq!(drop_outlines(&out).len(), usize::from(outline), "{case}: {:?}", drop_outlines(&out)); + frame_held(&ctx, &mut app, vec![alt_release(to)], egui::Modifiers::ALT); + egui::DragAndDrop::clear_payload(&ctx); + assert_eq!(symbols(&mut app), ["Leaf", "Dot"], "{case}: no symbol added"); + assert!(Arc::ptr_eq(&leaf, &symbol_art(&app, "Leaf")), "{case}: Leaf is unchanged"); + assert_eq!(undo_len(&app), undo, "{case}: no undo step"); + } + } + + /// Art held over a symbol, with Alt or without, and released with the secondary button is not + /// dropped: no symbol is redefined or added and no undo step is added. + #[test] + fn a_secondary_button_release_drops_no_art() { + let mut app = leaf_and_dot(); + let shape = app.run("shape.rectangle", json!({"x": 200, "y": 120, "width": 40, "height": 20})).unwrap()["id"].as_u64().unwrap(); + let leaf = symbol_art(&app, "Leaf"); + let undo = undo_len(&app); + let ctx = egui::Context::default(); + let at = item_at(&ctx, &mut app, "Leaf"); + let secondary = egui::Event::PointerButton { pos: at, button: egui::PointerButton::Secondary, pressed: false, modifiers: Default::default() }; + for (case, modifiers) in [("with Alt", egui::Modifiers::ALT), ("without Alt", egui::Modifiers::NONE)] { + widgets::drag_art(&ctx, uid(&app).unwrap(), vec![NodeId(shape)]); + let out = frame_held(&ctx, &mut app, vec![egui::Event::PointerMoved(at)], modifiers); + assert_eq!(drop_outlines(&out).len(), 1, "{case}: the art is held over a target"); + frame_held(&ctx, &mut app, vec![secondary.clone()], modifiers); + egui::DragAndDrop::clear_payload(&ctx); + assert_eq!(symbols(&mut app), ["Leaf", "Dot"], "{case}: no symbol added"); + assert!(Arc::ptr_eq(&leaf, &symbol_art(&app, "Leaf")), "{case}: Leaf is unchanged"); + assert_eq!(undo_len(&app), undo, "{case}: no undo step"); + } + } + /// CPU time of this thread in nanoseconds where the system reports it (Linux), else `None`. fn thread_cpu_ns() -> Option { std::fs::read_to_string("/proc/thread-self/schedstat").ok()?.split_whitespace().next()?.parse().ok() diff --git a/crates/ui-egui/src/panels/tests_three_d.rs b/crates/ui-egui/src/panels/tests_three_d.rs index f3b860afed..8b526b28c6 100644 --- a/crates/ui-egui/src/panels/tests_three_d.rs +++ b/crates/ui-egui/src/panels/tests_three_d.rs @@ -1294,6 +1294,180 @@ fn export_3d_object_leaves_out_a_group_with_a_3d_fill() { assert_eq!(list.iter().map(|a| a["nodes"].clone()).collect::>(), [json!([a])]); } +/// Whether Export 3D Object is available as the panel reads it ([`super::can_export_3d_shown`]), +/// checked against the state worked out from scratch ([`super::can_export_3d`]); with a document +/// open, the panel keeps it for the document's uid and revision. +fn exportable(app: &mut VectorcraftApp, why: &str) -> bool { + let fresh = super::can_export_3d(app); + assert_eq!(super::can_export_3d_shown(app), fresh, "{why}"); + if let Some(key) = app.session.active().map(|st| (st.uid, st.revision)) { + assert_eq!(app.canvas.three_d_exportable, Some((key, fresh)), "{why}"); + } + fresh +} + +/// The Export 3D Object state the panel keeps for a revision equals the state worked out from +/// scratch: with no document and no selection, for plain paths, with a 3D object selected first or +/// last, for a path of a compound path whose compound path has the effect, after the effect is +/// hidden, Undo and Redo, in another document and back, and for a group whose 3D effect moves onto +/// its fill. +#[test] +fn export_3d_object_state_kept_for_a_revision_equals_a_fresh_one() { + let mut app = VectorcraftApp::new(Session::new(), Services::default()); + assert!(!exportable(&mut app, "no document")); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + assert!(!exportable(&mut app, "no selection")); + let rect = |app: &mut VectorcraftApp, x: f64| { + app.run("shape.rectangle", json!({"x": x, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap() + }; + let (p, q) = (rect(&mut app, 10.0), rect(&mut app, 40.0)); + app.run("select.set", json!({"ids": [p, q]})).unwrap(); + assert!(!exportable(&mut app, "plain paths")); + let solid = rect(&mut app, 70.0); + app.run("effect.apply", json!({"effect": "threeD.extrude", "item": null})).unwrap(); + app.run("select.set", json!({"ids": [solid, p, q]})).unwrap(); + assert!(exportable(&mut app, "a 3D object first")); + app.run("select.set", json!({"ids": [p, q]})).unwrap(); + assert!(!exportable(&mut app, "plain paths again")); + app.run("select.set", json!({"ids": [p, q, solid]})).unwrap(); + assert!(exportable(&mut app, "a 3D object last")); + let (a, b) = (rect(&mut app, 100.0), rect(&mut app, 110.0)); + app.run("select.set", json!({"ids": [a, b]})).unwrap(); + app.run("object.compoundPath.make", json!({})).unwrap(); + let compound = app.session.active().unwrap().selection.objects[0].0; + app.run("effect.apply", json!({"effect": "threeD.extrude", "item": null})).unwrap(); + let member = app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(compound)).unwrap().children().unwrap()[0].id.0; + app.run("select.set", json!({"ids": [p, q]})).unwrap(); + assert!(!exportable(&mut app, "plain paths before the compound path's member")); + app.run("select.set", json!({"ids": [p, member]})).unwrap(); + assert!(exportable(&mut app, "a path of a 3D compound path")); + // An edit that leaves the selection as it is. + app.run("effect.setParams", json!({"ids": [compound], "index": 0, "item": null, "visible": false})).unwrap(); + assert!(!exportable(&mut app, "the compound path's 3D effect hidden")); + app.run("edit.undo", json!({})).unwrap(); + assert!(exportable(&mut app, "Undo")); + app.run("edit.redo", json!({})).unwrap(); + assert!(!exportable(&mut app, "Redo")); + app.run("edit.undo", json!({})).unwrap(); + assert!(exportable(&mut app, "Undo again")); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + assert!(!exportable(&mut app, "a new document")); + app.session.set_active(0); + assert!(exportable(&mut app, "back to the first document")); + // A group's own 3D effect exports; the same effect on its fill does not. + app.run("select.set", json!({"ids": [p, q]})).unwrap(); + let group = app.run("object.group", json!({})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [group]})).unwrap(); + app.run("appearance.addFill", json!({})).unwrap(); + app.run("effect.apply", json!({"effect": "threeD.extrude"})).unwrap(); + assert!(exportable(&mut app, "a group with its own 3D effect")); + app.session + .edit("fill", |d, _| { + let n = d.node_mut(vectorcraft_doc::NodeId(group)).unwrap(); + let fx = n.appearance.effects.remove(0); + n.appearance.items[0].effects_mut().push(fx); + Ok(()) + }) + .unwrap(); + assert!(!exportable(&mut app, "a group with a 3D effect on its fill")); +} + +/// A frame of the panel works out the Export 3D Object state once and keeps it for the document's +/// revision: later frames read it, and a new revision works it out again. +#[test] +fn export_3d_object_state_is_worked_out_once_per_revision() { + let key = |app: &VectorcraftApp| app.session.active().map(|st| (st.uid, st.revision)).unwrap(); + let mut app = app(); + painted_text(&mut app, show); + assert_eq!(app.canvas.three_d_exportable, Some((key(&app), false))); + // A wrong answer planted for this revision is what the panel reads: nothing works it out again. + app.canvas.three_d_exportable = Some((key(&app), true)); + assert!(super::can_export_3d_shown(&mut app)); + painted_text(&mut app, show); + assert_eq!(app.canvas.three_d_exportable, Some((key(&app), true))); + app.run("select.none", json!({})).unwrap(); + painted_text(&mut app, show); + assert_eq!(app.canvas.three_d_exportable, Some((key(&app), false))); +} + +/// The thread's CPU time in nanoseconds, where Linux gives it. +fn thread_cpu_ns() -> Option { + std::fs::read_to_string("/proc/thread-self/schedstat").ok()?.split_whitespace().next()?.parse().ok() +} + +/// Time the Export 3D Object state with 200,000 selected paths: worked out from scratch on every +/// frame ([`super::can_export_3d`]), by [`super::can_export_3d_shown`] on the first frame of a +/// revision, and by [`super::can_export_3d_shown`] on later frames of the same revision. The first +/// case selects plain paths alone; the second adds a path of a compound path with Extrude & Bevel, +/// selected last. The sides alternate, and the median time per frame of 7 runs is printed. +/// Run with `cargo test --release -p vectorcraft-ui-egui --lib export_3d_object_state_timing -- --ignored --nocapture`. +#[test] +#[ignore = "manual timing probe; performance depends on machine load"] +fn export_3d_object_state_timing() { + const PATHS: usize = 200_000; + const MEASURES: u32 = 20; + const KEPT: u32 = 1_000_000; + let mut app = VectorcraftApp::new(Session::new(), Services::default()); + app.run("file.new", json!({"width": 2000, "height": 2000})).unwrap(); + let rect = app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap(); + let rect = app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(rect)).cloned().unwrap(); + app.session + .edit("Fill", |d, _| { + let layer = d.layers[0].id; + for _ in 0..PATHS - 1 { + let mut n = rect.clone(); + n.id = d.alloc_id(); + d.insert(Some(layer), usize::MAX, n)?; + } + Ok(()) + }) + .unwrap(); + app.run("select.all", json!({})).unwrap(); + let plain: Vec = app.session.active().unwrap().selection.objects.iter().map(|id| id.0).collect(); + let a = app.run("shape.rectangle", json!({"x": 0, "y": 1000, "width": 30, "height": 30})).unwrap()["id"].clone(); + let b = app.run("shape.rectangle", json!({"x": 5, "y": 1005, "width": 10, "height": 10})).unwrap()["id"].clone(); + app.run("select.set", json!({"ids": [a, b]})).unwrap(); + app.run("object.compoundPath.make", json!({})).unwrap(); + let compound = app.session.active().unwrap().selection.objects[0]; + app.run("effect.apply", json!({"effect": "threeD.extrude", "item": null})).unwrap(); + let member = app.session.active().unwrap().doc.node(compound).unwrap().children().unwrap()[0].id.0; + let mut last = plain.clone(); + last.push(member); + let median = |v: &mut Vec| { + v.sort_by(f64::total_cmp); + v[v.len() / 2] + }; + let clock = if thread_cpu_ns().is_some() { "thread CPU time" } else { "wall-clock time" }; + for (name, ids, expected) in [("plain paths", plain, false), ("plain paths, then a path of a 3D compound path", last, true)] { + app.run("select.set", json!({"ids": &ids})).unwrap(); + let selected: Vec = app.session.active().unwrap().selection.objects.iter().map(|id| id.0).collect(); + assert_eq!(selected.len(), ids.len(), "{name}"); + assert_eq!(selected.last(), ids.last(), "{name}"); + assert_eq!(super::can_export_3d(&app), expected, "{name}"); + let mut time = |frames: u32, f: &mut dyn FnMut(&mut VectorcraftApp) -> bool| { + let (cpu, wall) = (thread_cpu_ns(), std::time::Instant::now()); + for _ in 0..frames { + assert_eq!(f(&mut app), expected); + } + let ns = thread_cpu_ns().zip(cpu).map_or_else(|| wall.elapsed().as_nanos(), |(b, a)| b - a); + ns as f64 / f64::from(frames) / 1000.0 + }; + let (mut full, mut first, mut kept) = (vec![], vec![], vec![]); + for _ in 0..7 { + full.push(time(MEASURES, &mut |app| super::can_export_3d(app))); + first.push(time(MEASURES, &mut |app| { + app.canvas.three_d_exportable = None; + super::can_export_3d_shown(app) + })); + kept.push(time(KEPT, &mut super::can_export_3d_shown)); + } + eprintln!("{name}: {} objects selected, available: {expected}; {clock} per frame, median of 7 runs", selected.len()); + eprintln!("every frame worked out ({MEASURES} frames a run): {:>12.3} us {full:.3?}", median(&mut full)); + eprintln!("first frame of a revision ({MEASURES} a run): {:>12.3} us {first:.3?}", median(&mut first)); + eprintln!("later frames ({KEPT} frames a run): {:>12.4} us {kept:.4?}", median(&mut kept)); + } +} + #[test] fn changed_settings_lists_only_new_values() { let before = json!({"depth": 50.0, "cap": true, "bevel": "none"}); diff --git a/crates/ui-egui/src/panels/three_d.rs b/crates/ui-egui/src/panels/three_d.rs index db47e73ac4..c1cdbd71b1 100644 --- a/crates/ui-egui/src/panels/three_d.rs +++ b/crates/ui-egui/src/panels/three_d.rs @@ -280,9 +280,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } /// The Export 3D Object button, available while a selected object has a 3D effect that -/// `assets.add3D` exports ([`can_export_3d`]). An error goes to the status bar. +/// `assets.add3D` exports ([`can_export_3d_shown`]). An error goes to the status bar. fn export_button(app: &mut VectorcraftApp, ui: &mut Ui, ctx: &egui::Context) { - let any = can_export_3d(app); + let any = can_export_3d_shown(app); ui.add_space(10.0); if ui.add_enabled(any, egui::Button::new(tl!("Export 3D Object"))).clicked() { finish(app, ctx); @@ -301,6 +301,22 @@ pub(crate) fn can_export_3d(app: &VectorcraftApp) -> bool { st.selection.objects.iter().any(|id| st.doc.node(compound(*id).unwrap_or(*id)).is_some_and(vectorcraft_effects::exports_three_d)) } +/// [`can_export_3d`], worked out once per (document uid, revision) +/// ([`crate::caches::CanvasCache::three_d_exportable`]): the panel reads it every frame, and Select +/// All can select hundreds of thousands of objects. +pub(crate) fn can_export_3d_shown(app: &mut VectorcraftApp) -> bool { + let Some(st) = app.session.active() else { return false }; + let key = (st.uid, st.revision); + if let Some((k, any)) = app.canvas.three_d_exportable + && k == key + { + return any; + } + let any = can_export_3d(app); + app.canvas.three_d_exportable = Some((key, any)); + any +} + /// Export 3D Object: adds the selected objects that have a 3D effect to Asset Export as 3D assets /// (`assets.add3D` on the selection, one undo step, none when each is an asset already), selects /// their assets there and shows the Asset Export panel. The command leaves out the selected diff --git a/crates/ui-egui/src/panels/transform.rs b/crates/ui-egui/src/panels/transform.rs index de73950ac8..936fdda1a6 100644 --- a/crates/ui-egui/src/panels/transform.rs +++ b/crates/ui-egui/src/panels/transform.rs @@ -491,21 +491,43 @@ pub(crate) fn line_rows(app: &mut VectorcraftApp, ui: &mut Ui, live: &LiveShape, } /// An ellipse's Pie Start and End Angle (degrees, counterclockwise from 3 o'clock; 0 to 360 is the -/// whole ellipse) and Invert Pie, which shows the other part of it (Transform and Properties panels). +/// whole ellipse), the Constrain Pie Angle link beside them, and Invert Pie, which shows the other +/// part of it (Transform and Properties panels). With the link on, a typed angle moves the other +/// one by as much, so each selected ellipse keeps its span. pub(crate) fn pie_rows(app: &mut VectorcraftApp, ui: &mut Ui, pie: (f64, f64), id: &str) { - for (label, key, v) in [(tl!("Pie Start Angle:"), "pieStart", pie.0), (tl!("Pie End Angle:"), "pieEnd", pie.1)] { - ui.horizontal(|ui| { - widgets::dim_label(ui, label); - if let Some(a) = widgets::plain_field(ui, (id, key), v, "°", 1, 60.0) { - app.run("object.setLiveShape", json!({ key: a })).ok(); + ui.horizontal(|ui| { + ui.vertical(|ui| { + for (label, key, v) in [(tl!("Pie Start Angle:"), "pieStart", pie.0), (tl!("Pie End Angle:"), "pieEnd", pie.1)] { + ui.horizontal(|ui| { + widgets::dim_label(ui, label); + if let Some(a) = widgets::plain_field(ui, (id, key), v, "°", 1, 60.0) { + let params = if app.ui.constrain_pie_angle { json!({ key: a, "constrainPie": true }) } else { json!({ key: a }) }; + app.run("object.setLiveShape", params).ok(); + } + }); } }); - } + pie_link(app, ui); + }); if widgets::flat_button(ui, tl!("Invert Pie"), 90.0).clicked() { app.run("object.setLiveShape", json!({"invertPie": true})).ok(); } } +/// The Constrain Pie Angle link between Pie Start and End Angle: one toggle for the Transform and +/// Properties panels, kept while the app runs and off at launch. It is drawn after the fields, so +/// Tab reaches them first; with the keyboard on it, Space or Enter toggles it. +fn pie_link(app: &mut VectorcraftApp, ui: &mut Ui) { + let (_, at) = ui.allocate_exact_size(egui::Vec2::splat(CONSTRAIN_LINK_SIZE), egui::Sense::click()); + let on = app.ui.constrain_pie_angle; + let tip = tl!("Constrain Pie Angle"); + let keyed = at.has_focus() + && ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Space) | i.consume_key(egui::Modifiers::NONE, egui::Key::Enter)); + if widgets::paint_icon_button(ui, at, if on { "link" } else { "link-2-off" }, tip, on).clicked() || keyed { + app.ui.constrain_pie_angle = !on; + } +} + /// A live polygon's Polygon Properties (Transform and Properties panels): its side count, angle /// (counterclockwise), corner type and radius, radius (centre to vertex) and side length, and Make /// Sides Equal, which an uneven scale enables. diff --git a/crates/ui-egui/src/panels/transform/tests.rs b/crates/ui-egui/src/panels/transform/tests.rs index c8787f7c93..fe284bbe22 100644 --- a/crates/ui-egui/src/panels/transform/tests.rs +++ b/crates/ui-egui/src/panels/transform/tests.rs @@ -154,6 +154,67 @@ fn an_ellipse_shows_its_pie_properties() { assert!(shown.iter().any(|s| s == "30°") && shown.iter().any(|s| s == "120°"), "{shown:?}"); } +/// Ellipse Properties' Constrain Pie Angle link, in the Transform panel and the Properties panel's +/// Transform section: off at first, a click or Space with the keyboard on it toggles it, and while +/// it is on a typed Pie Start or End Angle moves the other angle by as much, keeping the span, in +/// one undo step. Off, each angle changes on its own. +#[test] +fn the_constrain_pie_angle_link_keeps_the_span() { + use egui_kittest::kittest::Queryable; + const LINK: &str = "Constrain Pie Angle"; + let pie = |app: &VectorcraftApp| match &first_selected(app).unwrap().kind { + NodeKind::Path { live: Some(l), .. } => match **l { + LiveShape::Ellipse { pie, .. } => pie, + ref k => panic!("{k:?}"), + }, + k => panic!("{k:?}"), + }; + let undo = |app: &VectorcraftApp| app.session.doc().unwrap().history.undo.len(); + for draw in [show as fn(&mut VectorcraftApp, &mut Ui), crate::panels::properties::transform_section] { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + app.run("shape.ellipse", json!({"x": 50, "y": 50, "width": 120, "height": 80})).unwrap(); + app.run("object.setLiveShape", json!({"pieStart": 30, "pieEnd": 120})).unwrap(); + assert!(!app.ui.constrain_pie_angle, "off at first"); + let mut fonts = false; + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(320.0, 900.0)).with_accessibility_check(false).build_ui_state( + move |ui, app: &mut VectorcraftApp| { + if !std::mem::replace(&mut fonts, true) { + crate::theme::install_fonts(ui.ctx()); + return; + } + draw(app, ui); + }, + app, + ); + h.run_steps(3); + h.get_by_role_and_label(egui::accesskit::Role::Button, LINK).click(); + h.run_steps(2); + assert!(h.state().ui.constrain_pie_angle, "a click turns it on"); + h.get_by_role_and_label(egui::accesskit::Role::Button, LINK).focus(); + h.run_steps(1); + h.key_press(egui::Key::Space); + h.run_steps(2); + assert!(!h.state().ui.constrain_pie_angle, "Space turns it off"); + h.get_by_role_and_label(egui::accesskit::Role::Button, LINK).click(); + h.run_steps(2); + assert!(h.state().ui.constrain_pie_angle); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let n = undo(h.state()); + type_into(&ctx, h.state_mut(), draw, "30°", "60"); + assert_eq!(pie(h.state()), (60.0, 150.0)); + assert_eq!(undo(h.state()), n + 1, "one undo step"); + type_into(&ctx, h.state_mut(), draw, "150°", "200"); + assert_eq!(pie(h.state()), (110.0, 200.0)); + h.get_by_role_and_label(egui::accesskit::Role::Button, LINK).click(); + h.run_steps(2); + assert!(!h.state().ui.constrain_pie_angle); + type_into(&ctx, h.state_mut(), draw, "110°", "100"); + assert_eq!(pie(h.state()), (100.0, 200.0), "off, the end stays"); + } +} + /// A live line shows its Line Properties in the Transform panel and the Properties panel's /// Transform section: a typed length keeps its first end in place and a typed angle turns it /// about its midpoint, each one undo step. A line with other objects selected, and a line after diff --git a/crates/ui-egui/src/placing.rs b/crates/ui-egui/src/placing.rs index ca380f7ca8..c43ad596b4 100644 --- a/crates/ui-egui/src/placing.rs +++ b/crates/ui-egui/src/placing.rs @@ -21,10 +21,11 @@ use vectorcraft_engine::file_access::ScopeHandle; use crate::VectorcraftApp; -/// What was read: one file to place, the files to load the place cursor with (and whether they ask -/// for their import options when placed), or a bitmap to paste. +/// What was read: one file to place (and where new art went when it was placed), the files to load +/// the place cursor with (and whether they ask for their import options when placed), or a bitmap +/// to paste. enum Read { - Place(Box), + Place(Box, Insertion), Queue(QueueRead, bool), Paste(Box), } @@ -56,7 +57,8 @@ struct Paste { } /// Where new art goes in the active document: the current layer, the isolated group or object, and -/// the drawing mode with the object Draw Inside draws into. +/// the drawing mode with the object Draw Inside draws into. A paste and a placed file read off the +/// UI thread keep the one from when they were given. #[derive(Clone, PartialEq)] struct Insertion { layer: Option, @@ -81,9 +83,34 @@ impl Insertion { Some(Self { layer, isolation, draw_mode, draw_inside }) } + /// Whether new art can still go where `self` says in `app`'s active document: the isolated group + /// or object when it names one, else the object Draw Inside draws into when it names one and + /// `draws_inside` (a paste draws inside it, a placed file does not), else its layer, which must + /// still be a layer, is still there, shown and unlocked. A paste or a placed file whose layer or + /// group was deleted, hidden or locked meanwhile goes where new art goes now. + fn usable(&self, app: &VectorcraftApp, draws_inside: bool) -> bool { + app.session.doc().is_ok_and(|st| { + let inside = self.draw_inside.filter(|_| draws_inside && self.draw_mode == vectorcraft_engine::DrawMode::Inside); + match (self.isolation, inside, self.layer) { + (Some(target), ..) | (None, Some(target), _) => st.doc.is_editable(target), + (None, None, Some(l)) => st.doc.node(l).is_some_and(|n| n.is_layer()) && st.doc.is_editable(l), + (None, None, None) => true, + } + }) + } + + /// `self` when new art can still go there ([`Self::usable`]), else `now`: where new art went + /// before the paste or the place selected anything again. + fn or_now(self, now: Option<&Self>, app: &VectorcraftApp, draws_inside: bool) -> Self { + match now { + Some(now) if !self.usable(app, draws_inside) => now.clone(), + _ => self, + } + } + /// Put back each part of `self` (where new art went before [`Self::set`] set `started`) that - /// differs from `started`, what the user changed meanwhile; a part the paste itself changed - /// stays as the paste left it. + /// differs from `started`, what the user changed meanwhile; a part the paste or the place + /// itself changed stays as it left it. fn restore_changed(self, started: &Self, app: &mut VectorcraftApp) { if let Ok(st) = app.session.doc_mut() { if self.layer != started.layer { @@ -224,7 +251,9 @@ pub fn start(app: &mut VectorcraftApp, p: &Value, dropped: bool) -> Result) { } app.session.set_active(i); let r = match r { - Ok(Read::Place(read)) => app.session.place_read(*read).map(|_| ()).map_err(|e| e.to_string()), + Ok(Read::Place(read, insertion)) => { + // The file goes where new art went when it was placed (the current layer, the isolated + // group), as a paste does, and what the user changed meanwhile is kept. Where new art + // goes now is taken before Replace selects the object it swaps again. + let current = Insertion::of(app); + let insertion = insertion.or_now(current.as_ref(), app, false); + insertion.clone().set(app); + let r = app.session.place_read(*read).map(|_| ()).map_err(|e| e.to_string()); + if let Some(current) = current { + current.restore_changed(&insertion, app); + } + r + } Ok(Read::Queue(read, asks)) => { app.session.place_queue_read(read).map(|r| crate::place::show_thumbnails(app, &r, asks)).map_err(|e| e.to_string()) } @@ -540,7 +581,8 @@ fn finish_paste(app: &mut VectorcraftApp, paste: Paste) { // The paste goes where new art went when it started (the current layer, the isolated // group, the object Draw Inside draws into), and what the user changed meanwhile is // kept. - paste.insertion.clone().set(app); + let insertion = paste.insertion.or_now(current.as_ref(), app, pastes_inside(&paste.id)); + insertion.clone().set(app); let requested_selection = app.session.doc().map(|st| st.selection.objects.clone()).unwrap_or_default(); app.placing.adopted = true; // `run` shows an error in the status bar. @@ -552,7 +594,7 @@ fn finish_paste(app: &mut VectorcraftApp, paste: Paste) { if let Ok(st) = app.session.doc() { app.placing.swatch_paste = Some(PendingSwatch { clipboard: app.session.clipboard.clone(), - insertion: paste.insertion.clone(), + insertion: insertion.clone(), selection: requested_selection, doc: st.uid, reverts: st.reverts, @@ -562,7 +604,7 @@ fn finish_paste(app: &mut VectorcraftApp, paste: Paste) { } } if let Some(current) = current { - current.restore_changed(&paste.insertion, app); + current.restore_changed(&insertion, app); } app.session.doc().ok().map(|st| st.selection.objects.clone()) } @@ -613,6 +655,12 @@ pub(crate) fn settle_swatch_paste(app: &mut VectorcraftApp) { } } +/// Does the paste command `id` paste inside the object Draw Inside draws into? Paste in Front and +/// Paste in Back keep their own places. +fn pastes_inside(id: &str) -> bool { + !matches!(id, "edit.pasteInFront" | "edit.pasteInBack") +} + /// Run the command confirmed by the deferred paste's Swatch Conflict dialog. pub(crate) fn confirm_swatch_paste(app: &mut VectorcraftApp, id: &str, params: Value, token: Option) -> Result { if !app.placing.swatch_paste.as_ref().is_some_and(|waiting| Some(waiting.chain) == token) { @@ -643,7 +691,7 @@ pub(crate) fn confirm_swatch_paste(app: &mut VectorcraftApp, id: &str, params: V if selected != now.iter().map(|id| id.0).collect::>() { let _ = app.session.execute("select.set", &json!({"ids": selected})); } - let insertion = waiting.insertion.clone(); + let insertion = waiting.insertion.clone().or_now(changed.as_ref(), app, pastes_inside(id)); insertion.clone().set(app); app.placing.adopted = true; let result = app.run(id, params); diff --git a/crates/ui-egui/src/placing/tests.rs b/crates/ui-egui/src/placing/tests.rs index 9043bac0ea..af411f3430 100644 --- a/crates/ui-egui/src/placing/tests.rs +++ b/crates/ui-egui/src/placing/tests.rs @@ -661,6 +661,134 @@ fn a_deferred_swatch_paste_uses_its_original_layer() { assert_eq!(st.current_layer(), Some(second)); } +/// A bitmap pasted from another app while a group is isolated goes into that group when the +/// isolation ends and the current layer, which does not hold the group, is locked while the bitmap +/// is decoded. +#[test] +fn a_bitmap_pasted_into_an_isolated_group_stays_there_when_another_layer_is_locked() { + let (mut app, _) = pasting_app(true, Some(Flavour { mime: PNG, data: picture(Png, 60, 40) }), None, true); + let first = app.session.doc().unwrap().doc.layers[0].id; + app.run("layer.new", json!({})).unwrap(); + let squares: Vec = + (0..2).map(|i| app.run("shape.rectangle", json!({"x": 10 + 30 * i, "y": 10, "width": 20, "height": 20})).unwrap()["id"].clone()).collect(); + app.run("select.set", json!({"ids": squares})).unwrap(); + let group = NodeId(app.run("object.group", json!({})).unwrap()["id"].as_u64().unwrap()); + app.run("select.none", json!({})).unwrap(); + app.run("layer.setCurrent", json!({"id": first.0})).unwrap(); + app.run("object.isolate", json!({"id": group.0})).unwrap(); + app.session.doc_mut().unwrap().active_layer = Some(first); + crate::menus::invoke(&mut app, "edit.paste", json!({})); + app.run("object.exitIsolation", json!({})).unwrap(); + app.run("layer.setProps", json!({"ids": [first.0], "locked": true})).unwrap(); + placed(&mut app); + let st = app.session.doc().unwrap(); + assert_eq!(st.selection.objects.first().and_then(|i| st.doc.parent_of(*i)), Some(group), "pasted into the group isolated at the paste"); + assert_eq!(st.isolation, None, "the isolation ended meanwhile stays ended"); +} + +/// A bitmap pasted from another app whose layer is locked while it is decoded goes into the layer +/// current then, also when the objects selected at the paste, which it selects again, are in +/// another layer. +#[test] +fn a_bitmap_whose_layer_is_locked_meanwhile_is_not_pasted_next_to_the_selection() { + let (mut app, _) = pasting_app(true, Some(Flavour { mime: PNG, data: picture(Png, 60, 40) }), None, true); + let first = app.session.doc().unwrap().doc.layers[0].id; + app.run("layer.new", json!({})).unwrap(); + let selected = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].clone(); + let second = app.session.doc().unwrap().current_layer().unwrap(); + app.run("layer.new", json!({})).unwrap(); + let third = app.session.doc().unwrap().current_layer().unwrap(); + app.run("select.set", json!({"ids": [selected]})).unwrap(); + app.run("layer.setCurrent", json!({"id": first.0})).unwrap(); + assert_eq!(app.session.doc().unwrap().selection.objects.len(), 1); + crate::menus::invoke(&mut app, "edit.paste", json!({})); + app.run("layer.setProps", json!({"ids": [first.0], "locked": true})).unwrap(); + app.run("layer.setCurrent", json!({"id": third.0})).unwrap(); + app.run("select.none", json!({})).unwrap(); + placed(&mut app); + let st = app.session.doc().unwrap(); + let pasted = st.selection.objects.first().and_then(|i| st.doc.layer_containing(*i)); + assert_eq!(pasted, Some(third), "pasted into the current layer, not {second:?}"); +} + +/// In Draw Inside, a bitmap decoded off the UI thread is pasted inside the object Draw Inside draws +/// into, in another layer, when the layer current at the paste is locked meanwhile. +#[test] +fn a_bitmap_pasted_in_draw_inside_stays_inside_when_its_layer_is_locked() { + let (mut app, _) = pasting_app(true, Some(Flavour { mime: PNG, data: picture(Png, 60, 40) }), None, true); + let first = app.session.doc().unwrap().doc.layers[0].id; + app.run("layer.new", json!({})).unwrap(); + let path = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 200, "height": 200})).unwrap()["id"].clone(); + app.run("layer.new", json!({})).unwrap(); + let third = app.session.doc().unwrap().current_layer().unwrap(); + app.run("select.set", json!({"ids": [path]})).unwrap(); + app.run("view.drawMode", json!({"mode": "inside"})).unwrap(); + app.run("select.none", json!({})).unwrap(); + app.run("layer.setCurrent", json!({"id": first.0})).unwrap(); + crate::menus::invoke(&mut app, "edit.paste", json!({})); + app.run("view.drawMode", json!({"mode": "normal"})).unwrap(); + app.run("layer.setProps", json!({"ids": [first.0], "locked": true})).unwrap(); + app.run("layer.setCurrent", json!({"id": third.0})).unwrap(); + placed(&mut app); + let st = app.session.doc().unwrap(); + let group = st.selection.objects.first().and_then(|i| st.doc.parent_of(*i)); + assert!( + group.is_some_and(|g| st.doc.node(g).is_some_and(|n| n.children().is_some_and(|c| c.iter().any(|n| n.id.0 == path.as_u64().unwrap())))), + "pasted inside the path" + ); +} + +/// Paste in Front does not paste inside the object Draw Inside draws into: a bitmap decoded off the +/// UI thread goes into the layer current at the paste when that object is locked meanwhile. +#[test] +fn a_bitmap_pasted_in_front_in_draw_inside_keeps_its_layer() { + let (mut app, _) = pasting_app(true, Some(Flavour { mime: PNG, data: picture(Png, 60, 40) }), None, true); + let first = app.session.doc().unwrap().doc.layers[0].id; + app.run("layer.new", json!({})).unwrap(); + let second = app.session.doc().unwrap().current_layer().unwrap(); + let path = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 200, "height": 200})).unwrap()["id"].clone(); + app.run("layer.new", json!({})).unwrap(); + let third = app.session.doc().unwrap().current_layer().unwrap(); + app.run("select.set", json!({"ids": [path]})).unwrap(); + app.run("view.drawMode", json!({"mode": "inside"})).unwrap(); + app.run("select.none", json!({})).unwrap(); + app.run("layer.setCurrent", json!({"id": first.0})).unwrap(); + crate::menus::invoke(&mut app, "edit.pasteInFront", json!({})); + app.run("layer.setProps", json!({"ids": [second.0], "locked": true})).unwrap(); + app.run("layer.setCurrent", json!({"id": third.0})).unwrap(); + placed(&mut app); + let st = app.session.doc().unwrap(); + assert_eq!(st.selection.objects.first().and_then(|i| st.doc.layer_containing(*i)), Some(first), "pasted into the layer current at the paste"); +} + +/// A paste waiting for its Swatch Conflict dialog whose layer is locked before the dialog's OK +/// goes into the layer current at the OK, not into the topmost layer. +#[test] +fn a_deferred_swatch_paste_whose_layer_is_locked_meanwhile_uses_the_current_layer() { + let (mut app, _) = pasting_app(true, None, None, true); + app.run("swatch.new", json!({"name": "Brand", "color": "#ff0000", "global": true})).unwrap(); + let source = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].clone(); + app.run("paint.setFill", json!({"ids": [source], "swatch": "Brand"})).unwrap(); + app.run("edit.copy", json!({})).unwrap(); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run("swatch.new", json!({"name": "Brand", "color": "#0000ff", "global": true})).unwrap(); + let first = app.session.doc().unwrap().doc.layers[0].id; + app.run("layer.new", json!({})).unwrap(); + let second = app.session.doc().unwrap().current_layer().unwrap(); + app.run("layer.new", json!({})).unwrap(); + app.run("layer.setCurrent", json!({"id": first.0})).unwrap(); + app.run("select.none", json!({})).unwrap(); + crate::menus::invoke(&mut app, "edit.paste", json!({})); + placed(&mut app); + assert_eq!(app.ui.dialog.as_ref().unwrap().kind, crate::dialogs::swatch_conflict::KIND); + app.run("layer.setProps", json!({"ids": [first.0], "locked": true})).unwrap(); + app.run("layer.setCurrent", json!({"id": second.0})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("choice".into(), json!("add")); + crate::dialogs::confirm(&mut app).unwrap(); + let st = app.session.doc().unwrap(); + assert_eq!(st.selection.objects.first().and_then(|i| st.doc.layer_containing(*i)), Some(second)); +} + #[test] fn a_queued_paste_stacks_after_a_deferred_swatch_confirmation() { for id in ["edit.pasteInFront", "edit.pasteInBack"] { @@ -970,6 +1098,166 @@ fn a_bitmap_read_off_the_ui_thread_is_pasted_into_its_layer() { assert_eq!(st.current_layer(), Some(second), "the layer of the object selected meanwhile stays current"); } +/// An app placing off the UI thread with three layers, the bottom one current → the app, a TIFF +/// file to place and the layers from the bottom up. +fn three_layers(test: &str) -> (VectorcraftApp, String, [NodeId; 3]) { + let mut app = app(true); + let path = saved(test, "a.tif", &picture(Tiff, 60, 40)); + let first = app.session.doc().unwrap().doc.layers[0].id; + app.run("layer.new", json!({})).unwrap(); + let second = app.session.doc().unwrap().current_layer().unwrap(); + app.run("layer.new", json!({})).unwrap(); + let third = app.session.doc().unwrap().current_layer().unwrap(); + app.run("layer.setCurrent", json!({"id": first.0})).unwrap(); + (app, path, [first, second, third]) +} + +/// A file read off the UI thread after the Place dialog's OK is placed into the layer that was +/// current at the OK, and a layer made current while it is read stays current. +#[test] +fn a_file_read_off_the_ui_thread_is_placed_into_its_layer() { + let (mut app, a, [first, second, _]) = three_layers("into-its-layer"); + app.run("file.place", json!({"paths": [a]})).unwrap(); + assert_eq!(crate::dialogs::confirm(&mut app).unwrap()["background"], true); + app.run("layer.setCurrent", json!({"id": second.0})).unwrap(); + placed(&mut app); + let st = app.session.doc().unwrap(); + assert_eq!(st.doc.layer_containing(st.selection.objects[0]), Some(first), "placed into the layer current at the OK"); + assert_eq!(st.current_layer(), Some(second), "the layer made current meanwhile stays current"); +} + +/// A file dropped on the canvas goes into the layer current at the drop, not into a group in +/// another layer isolated while the file is read, and the group stays isolated. +#[test] +fn a_dropped_file_is_placed_into_the_layer_current_at_the_drop() { + let (mut app, a, [first, second, _]) = three_layers("drop-into-its-layer"); + app.run("layer.setCurrent", json!({"id": second.0})).unwrap(); + let squares: Vec = + (0..2).map(|i| app.run("shape.rectangle", json!({"x": 10 + 30 * i, "y": 10, "width": 20, "height": 20})).unwrap()["id"].clone()).collect(); + app.run("select.set", json!({"ids": squares})).unwrap(); + let group = NodeId(app.run("object.group", json!({})).unwrap()["id"].as_u64().unwrap()); + app.run("select.none", json!({})).unwrap(); + app.run("layer.setCurrent", json!({"id": first.0})).unwrap(); + let doc = app.session.doc().unwrap().uid; + let drop = DropTarget::Place(DropAt { doc, reverts: 0, at: vectorcraft_geom::Point::new(200.0, 150.0), embed: false }); + crate::place::drop_files(&mut app, vec![(drop, ("a.tif".into(), Some(a), vec![]))]); + app.run("object.isolate", json!({"id": group.0})).unwrap(); + placed(&mut app); + let st = app.session.doc().unwrap(); + assert_eq!(st.doc.parent_of(st.selection.objects[0]), Some(first), "placed into the layer current at the drop"); + assert_eq!(st.isolation, Some(group), "the group stays isolated"); +} + +/// An object selected in another layer while a placed file is read makes that layer current, and +/// it stays current after the file is placed into the layer current at the OK. +#[test] +fn a_file_placed_while_an_object_in_another_layer_is_selected_keeps_its_layer() { + let (mut app, a, [first, second, _]) = three_layers("select-meanwhile"); + app.run("layer.setCurrent", json!({"id": second.0})).unwrap(); + let square = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].clone(); + app.run("layer.setCurrent", json!({"id": first.0})).unwrap(); + app.run("select.none", json!({})).unwrap(); + app.run("file.place", json!({"paths": [a]})).unwrap(); + crate::dialogs::confirm(&mut app).unwrap(); + app.run("select.set", json!({"ids": [square]})).unwrap(); + assert_eq!(app.session.doc().unwrap().current_layer(), Some(second)); + placed(&mut app); + let st = app.session.doc().unwrap(); + assert_eq!(st.doc.layer_containing(st.selection.objects[0]), Some(first), "placed into the layer current at the OK"); + assert_eq!(st.current_layer(), Some(second), "the layer of the object selected meanwhile stays current"); +} + +/// Replace swaps the object selected at the OK in its own layer, and a layer made current while the +/// file is read stays current after Replace selects that object again. +#[test] +fn a_replace_read_off_the_ui_thread_keeps_the_layer_made_current_meanwhile() { + let (mut app, a, [first, second, _]) = three_layers("replace-meanwhile"); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + crate::place::run_for_user(&mut app, &json!({"path": a, "replace": true})).unwrap(); + app.run("select.none", json!({})).unwrap(); + app.run("layer.setCurrent", json!({"id": second.0})).unwrap(); + placed(&mut app); + let st = app.session.doc().unwrap(); + let image = st.selection.objects[0]; + assert!(matches!(st.doc.node(image).map(|n| &n.kind), Some(vectorcraft_doc::NodeKind::Image(_))), "{}", app.ui.status); + assert_eq!(st.doc.layer_containing(image), Some(first), "the image takes the replaced object's place"); + assert_eq!(st.current_layer(), Some(second), "the layer made current meanwhile stays current"); +} + +/// A file whose layer is deleted or locked while it is read goes where new art goes now: into the +/// layer current then, not into the topmost layer. +#[test] +fn a_file_whose_layer_is_deleted_or_locked_meanwhile_goes_into_the_current_layer() { + let mut found = vec![]; + let mut wanted = vec![]; + for change in ["delete", "lock", "hide"] { + let (mut app, a, [first, second, _]) = three_layers(&format!("layer-{change}")); + app.run("file.place", json!({"paths": [a]})).unwrap(); + crate::dialogs::confirm(&mut app).unwrap(); + match change { + "delete" => app.run("layer.delete", json!({"ids": [first.0]})).unwrap(), + "lock" => app.run("layer.setProps", json!({"ids": [first.0], "locked": true})).unwrap(), + _ => app.run("layer.setProps", json!({"ids": [first.0], "visible": false})).unwrap(), + }; + app.run("layer.setCurrent", json!({"id": second.0})).unwrap(); + placed(&mut app); + let st = app.session.doc().unwrap(); + let image = st.selection.objects.first().copied(); + found.push((change, image.and_then(|i| st.doc.layer_containing(i)), st.current_layer())); + wanted.push((change, Some(second), Some(second))); + } + assert_eq!(found, wanted, "placed into the current layer, which stays current"); +} + +/// Place does not draw inside an object: with Draw Inside on for an object in another layer, a file +/// whose layer is locked while it is read goes into the layer current then. +#[test] +fn a_file_placed_with_draw_inside_on_follows_its_layer() { + let (mut app, a, [first, second, _]) = three_layers("draw-inside"); + app.run("layer.setCurrent", json!({"id": second.0})).unwrap(); + let inside = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 200, "height": 200})).unwrap()["id"].clone(); + app.run("select.set", json!({"ids": [inside]})).unwrap(); + app.run("view.drawMode", json!({"mode": "inside"})).unwrap(); + app.run("layer.setCurrent", json!({"id": first.0})).unwrap(); + app.run("select.none", json!({})).unwrap(); + assert_eq!(app.session.draw_inside.map(|t| t.0), inside.as_u64()); + app.run("file.place", json!({"paths": [a]})).unwrap(); + crate::dialogs::confirm(&mut app).unwrap(); + app.run("layer.setProps", json!({"ids": [first.0], "locked": true})).unwrap(); + app.run("layer.setCurrent", json!({"id": second.0})).unwrap(); + placed(&mut app); + let st = app.session.doc().unwrap(); + assert_eq!(st.selection.objects.first().and_then(|i| st.doc.layer_containing(*i)), Some(second), "placed into the current layer"); +} + +/// A bitmap pasted from another app whose layer is deleted, locked or hidden while it is decoded +/// goes into the layer current then, not into the topmost layer. +#[test] +fn a_bitmap_whose_layer_is_deleted_or_locked_meanwhile_is_pasted_into_the_current_layer() { + let mut found = vec![]; + let mut wanted = vec![]; + for change in ["delete", "lock", "hide"] { + let (mut app, _) = pasting_app(true, Some(Flavour { mime: PNG, data: picture(Png, 60, 40) }), None, true); + let first = app.session.doc().unwrap().doc.layers[0].id; + app.run("layer.new", json!({})).unwrap(); + let second = app.session.doc().unwrap().current_layer().unwrap(); + app.run("layer.new", json!({})).unwrap(); + app.run("layer.setCurrent", json!({"id": first.0})).unwrap(); + crate::menus::invoke(&mut app, "edit.paste", json!({})); + match change { + "delete" => app.run("layer.delete", json!({"ids": [first.0]})).unwrap(), + "lock" => app.run("layer.setProps", json!({"ids": [first.0], "locked": true})).unwrap(), + _ => app.run("layer.setProps", json!({"ids": [first.0], "visible": false})).unwrap(), + }; + app.run("layer.setCurrent", json!({"id": second.0})).unwrap(); + placed(&mut app); + let st = app.session.doc().unwrap(); + found.push((change, st.selection.objects.first().and_then(|i| st.doc.layer_containing(*i)))); + wanted.push((change, Some(second))); + } + assert_eq!(found, wanted, "pasted into the current layer"); +} + /// The Place dialog's OK with one file, with several (the place cursor and its thumbnails), a /// drop on the canvas and [`crate::io::place_bytes`] read their files off the UI thread; /// `file.place` and `file.place.queue` from MCP and scripts read them at once, with the replies diff --git a/crates/ui-egui/src/prefs_dialog/descriptions.rs b/crates/ui-egui/src/prefs_dialog/descriptions.rs index f514d37bda..b65161d131 100644 --- a/crates/ui-egui/src/prefs_dialog/descriptions.rs +++ b/crates/ui-egui/src/prefs_dialog/descriptions.rs @@ -39,6 +39,7 @@ pub(crate) const DESCRIPTIONS: &[(&str, &str)] = &[ ("ctrlWheelScrollsSideways", "The mouse wheel with Cmd/Ctrl held scrolls the canvas sideways."), ("scrubNumericFields", "Dragging sideways on a numeric field's label changes the field's value."), ("trackpadRotateView", "A two-finger rotate gesture on a trackpad rotates the canvas view."), + ("interpolateControlPoints", "When you move anchor points, each curve with one moved end keeps its shape relative to its ends."), ("holdToolKeys", "Holding a tool's shortcut key chooses the tool until you let go, and then the previous tool is chosen again."), ("boundingBoxWhileMovingAndDrawing", "Shows the bounding box while you move the selection or draw a shape."), ("japaneseCropMarks", "Create Trim Marks draws Japanese-style marks instead of Roman ones."), diff --git a/crates/ui-egui/src/prefs_dialog/tests.rs b/crates/ui-egui/src/prefs_dialog/tests.rs index be0450feac..47535cab06 100644 --- a/crates/ui-egui/src/prefs_dialog/tests.rs +++ b/crates/ui-egui/src/prefs_dialog/tests.rs @@ -20,6 +20,29 @@ fn marquee_selection_choices_are_saved_from_preferences() { assert!(text.contains("Drag Direction"), "{text}"); } +/// Plug-ins & Scratch Disks › Plug-in Instruction Budget: shown with its choices, applied by OK, +/// saved with the UI state and read back from it when the app starts again. +#[test] +fn plugin_instruction_budget_shows_applies_and_restores() { + let mut a = app(); + open(&mut a, Some("Plug-ins & Scratch Disks")); + let text = crate::tests_labels::painted_text(&mut a, |a, ui| show(a, ui.ctx())); + assert!(text.contains("Plug-in Instruction Budget") && text.contains("Normal"), "{text}"); + a.ui.dialog.as_mut().unwrap().fields.insert("pluginInstructionBudget".into(), json!("large")); + confirm(&mut a).unwrap(); + assert_eq!(a.session.prefs.plugin_instruction_budget, vectorcraft_engine::PluginBudget::Large); + let saved: Value = serde_json::from_slice(&serde_json::to_vec(&a.ui).unwrap()).unwrap(); + assert_eq!(saved["engine_prefs"]["pluginInstructionBudget"], json!("large")); + let mut b = app(); + b.ui.engine_prefs = saved["engine_prefs"].clone(); + restore(&mut b); + assert_eq!(b.session.prefs.plugin_instruction_budget, vectorcraft_engine::PluginBudget::Large); + // A saved value this version doesn't offer reads as Normal, and the other preferences stay. + b.ui.engine_prefs = json!({"keyboardIncrement": 4, "pluginInstructionBudget": 7}); + restore(&mut b); + assert_eq!((b.session.prefs.plugin_instruction_budget, b.session.prefs.keyboard_increment), (vectorcraft_engine::PluginBudget::Normal, 4.0)); +} + #[test] fn geometric_snapping_is_a_saved_smart_guides_preference() { let mut a = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); diff --git a/crates/ui-egui/src/shortcut_editor.rs b/crates/ui-egui/src/shortcut_editor.rs index 25eb47503b..e6120ad599 100644 --- a/crates/ui-egui/src/shortcut_editor.rs +++ b/crates/ui-egui/src/shortcut_editor.rs @@ -1017,14 +1017,10 @@ fn names_a_required_field(params: &str) -> bool { !(f.is_empty() || f.starts_with('…') || f[end..].starts_with('=') || f[..end].split('|').all(|n| n.trim().ends_with('?'))) }; let Some(rest) = params.strip_prefix('{') else { return false }; - let (mut depth, mut quoted, mut start) = (0usize, false, 0); - for (i, ch) in rest.char_indices() { + let mut start = 0; + for (i, ch, depth) in outside_quotes(rest) { match ch { - '"' => quoted = !quoted, - _ if quoted => {} - '{' | '[' | '(' => depth += 1, '}' if depth == 0 => return required(&rest[start..i]), - '}' | ']' | ')' => depth = depth.saturating_sub(1), ',' if depth == 0 => { if required(&rest[start..i]) { return true; @@ -1037,6 +1033,29 @@ fn names_a_required_field(params: &str) -> bool { false } +/// Each character of `text` that is not a double quote or inside a pair of them, with its byte +/// offset and the number of `{`, `[` and `(` groups open before it. A closing `}`, `]` or `)` comes +/// with a count that includes the group it closes, and one with no group open counts none. +pub(crate) fn outside_quotes(text: &str) -> impl Iterator + '_ { + let (mut depth, mut quoted) = (0usize, false); + text.char_indices().filter_map(move |(i, ch)| { + if ch == '"' { + quoted = !quoted; + return None; + } + if quoted { + return None; + } + let before = depth; + match ch { + '{' | '[' | '(' => depth += 1, + '}' | ']' | ')' => depth = depth.saturating_sub(1), + _ => {} + } + Some((i, ch, before)) + }) +} + pub fn entry(key: &str) -> Option { entries().iter().find(|e| e.key == key).cloned() } diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 83fa16dff6..8790fc9280 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -225,6 +225,7 @@ pub const ICON_PANELS: &[(&str, &str, &str)] = &[ (crate::panels::variables::ID, "Variables", "chart-column"), (crate::panels::script_console::ID, "Script Console", "message-circle"), (crate::panels::learn::ID, "Learn", "graduation-cap"), + (crate::panels::discover::ID, "VectorCraft Help…", "search"), (crate::addons::cleanup::ID, "Artwork Cleanup", "sparkles"), (crate::addons::color::ID, "Color Effects", "sun"), (crate::addons::packaging::ID, "Fold Lines", "scissors"), @@ -420,9 +421,16 @@ pub struct UiState { /// Type › Find Font…'s last Find In choice (`find_font::FIND_IN`), kept while the app runs. #[serde(skip)] pub find_font_in: String, + /// Ellipse Properties' Constrain Pie Angle link (Transform and Properties panels): a Pie Start + /// or End Angle typed while it is on keeps each selected ellipse's pie span. Kept while the app + /// runs; off at every launch. + #[serde(skip)] + pub constrain_pie_angle: bool, /// The Learn panel's tab, skill and tutorial, kept while the app runs. #[serde(skip)] pub learn: crate::panels::learn::View, + #[serde(skip)] + pub discover: crate::panels::discover::View, /// The tool whose place a Learn tutorial step's link shows (`learn.locateTool`), while its mark /// is on screen. Not saved. #[serde(skip)] @@ -1175,7 +1183,9 @@ impl Default for UiState { transient_focus: false, color_settings_scroll: false, find_font_in: String::new(), + constrain_pie_angle: false, learn: Default::default(), + discover: Default::default(), learn_locate: None, learn_practice: Default::default(), learn_progress: Default::default(), diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 8ba8350b29..45818730d1 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -42,16 +42,17 @@ pub use color::{ hex_field, hex_field_named, hsb32, hue_ring, region_texture, ring_square, segment_color, segment_color_on, segmented_wheel, stepped_area, wheel_of, }; -pub(crate) use color::{HEX_FIELD_CHARS, hex_text, pointer_phase}; +pub(crate) use color::{HEX_FIELD_CHARS, focus_by_pointer, hex_text, pointer_phase}; pub use drag::{ - PanelDrag, RowClick, SwatchRows, apply_row_click, art_drop, doc_preview, drag_ghost, drag_source, drop_target_outline, ghost_row, row_click, + PanelDrag, RowClick, SwatchRows, apply_row_click, art_drag_doc, art_drop, doc_preview, drag_art, drag_ghost, drag_source, drop_target_outline, + ghost_row, row_click, }; #[cfg(test)] use dropdowns::combo_button_id; pub(crate) use dropdowns::{combo, combo_menu, combo_menu_field_named, combo_named, field_focused_in, menu_min_width, popover_is_open}; pub use dropdowns::{ - dropdown, dropdown_icon_names, dropdown_named, dropdown_names, dropdown_names_named, dropdown_with, dropdown_with_named, list_scroll_style, - menu_room, menu_scroll, panel_scroll, popover, set_menu_floor, strip_scroll, + dropdown, dropdown_icon_names, dropdown_icon_names_sized, dropdown_named, dropdown_names, dropdown_names_named, dropdown_with, + dropdown_with_named, list_scroll_style, menu_room, menu_scroll, panel_scroll, popover, set_menu_floor, strip_scroll, }; #[cfg(test)] pub(crate) use dropdowns::{menu_floor, menu_room_either}; diff --git a/crates/ui-egui/src/widgets/color.rs b/crates/ui-egui/src/widgets/color.rs index 49c3ba73a1..54d52a6ccf 100644 --- a/crates/ui-egui/src/widgets/color.rs +++ b/crates/ui-egui/src/widgets/color.rs @@ -155,6 +155,14 @@ pub fn stepped_area(ui: &Ui, resp: &Response, name: &str, shown: Option, always: boo // a keyboard user where the focus is, and after a drag it only framed the rail. let by_pointer = id.with("focused-by-pointer"); if resp.drag_started() || resp.clicked() { - resp.request_focus(); - ui.data_mut(|d| d.insert_temp(by_pointer, true)); + focus_by_pointer(ui, id); } let focused = ui.memory(|m| m.has_focus(id)); if !focused { diff --git a/crates/ui-egui/src/widgets/drag.rs b/crates/ui-egui/src/widgets/drag.rs index eddadd4703..e0eec69ecd 100644 --- a/crates/ui-egui/src/widgets/drag.rs +++ b/crates/ui-egui/src/widgets/drag.rs @@ -17,7 +17,8 @@ pub enum PanelDrag { /// replaces the style it is dropped on with it (`graphicStyle.redefine`). Appearance(vectorcraft_doc::NodeId), /// A Graphic Styles panel style: art it is dropped on takes it (`graphicStyle.apply` with its - /// `ids`); the panel moves it to where it is dropped. + /// `ids`); the panel moves it to where it is dropped, or with Alt held replaces the style it is + /// dropped on with its look (`graphicStyle.redefine` with `from`). GraphicStyle(String), /// The selected art, dragged off the canvas with the Selection tool: the Graphic Styles panel /// makes a style of the first object (`graphicStyle.new`), or with Alt held replaces the style @@ -51,14 +52,34 @@ pub enum PanelDrag { } /// A panel list `zone` that takes art dragged off the canvas: outlined while art is held over it; -/// → the dragged ids when it is released there. +/// → the dragged ids when the primary button is released there (the release of another button +/// ends the drag). pub fn art_drop(ui: &Ui, zone: &Response) -> Option> { let drag = zone.dnd_hover_payload::()?; let PanelDrag::Art(ids) = &*drag else { return None }; ui.painter().rect_stroke(zone.rect, 0.0, Stroke::new(1.5, Tokens::get(ui.ctx()).accent), StrokeKind::Inside); + if !ui.input(|i| i.pointer.button_released(egui::PointerButton::Primary)) { + return None; + } zone.dnd_release_payload::().map(|_| ids.iter().map(|id| id.0).collect()) } +/// Key of the document whose art a [`PanelDrag::Art`] carries. +fn art_doc_id() -> egui::Id { + egui::Id::unique("panel-drag-art-doc") +} + +/// Start (or keep up) a panel drag of the art `ids` of document `uid`, dragged off its canvas. +pub fn drag_art(ctx: &egui::Context, uid: u64, ids: Vec) { + ctx.data_mut(|d| d.insert_temp(art_doc_id(), uid)); + egui::DragAndDrop::set_payload(ctx, PanelDrag::Art(ids)); +} + +/// The document (`uid`) whose art the last [`drag_art`] carried. +pub fn art_drag_doc(ctx: &egui::Context) -> Option { + ctx.data(|d| d.get_temp::(art_doc_id())) +} + /// The Swatches panel rows a drag from that panel moves: the swatch, None, Registration or colour /// group under the pointer when the drag started (`grabbed`) and `names`, the panel selection when /// the grabbed one is part of it (only colour groups, or only swatches, like the grabbed one), in diff --git a/crates/ui-egui/src/widgets/dropdowns.rs b/crates/ui-egui/src/widgets/dropdowns.rs index 7f088f25ef..1b2d4b421f 100644 --- a/crates/ui-egui/src/widgets/dropdowns.rs +++ b/crates/ui-egui/src/widgets/dropdowns.rs @@ -50,11 +50,23 @@ pub fn dropdown_icon_names( width: f32, icon_size: f32, icon: impl Fn(&Ui, Rect, usize, egui::Color32, bool), +) -> Option { + dropdown_icon_names_sized(ui, id, current, options, width, Vec2::splat(icon_size), icon) +} + +/// [`dropdown_icon_names`] with icons of any size, for a picture wider than it is tall, such as a +/// line with an arrowhead. +pub fn dropdown_icon_names_sized( + ui: &mut Ui, + id: impl std::hash::Hash, + current: Option, + options: &[&str], + width: f32, + icon_size: Vec2, + icon: impl Fn(&Ui, Rect, usize, egui::Color32, bool), ) -> Option { let icon = &icon; - let atom = move |i: usize, highlighted: bool| { - egui::Atom::paint(Vec2::splat(icon_size), move |ui, a| icon(ui, a.rect, i, a.fallback_text_color, highlighted)) - }; + let atom = move |i: usize, highlighted: bool| egui::Atom::paint(icon_size, move |ui, a| icon(ui, a.rect, i, a.fallback_text_color, highlighted)); let shown = match current.and_then(|i| options.get(i).map(|name| (i, *name))) { Some((i, name)) => (atom(i, false), egui::RichText::new(name).size(12.0)).into_atoms(), None => egui::RichText::new("").size(12.0).into_atoms(), diff --git a/crates/ui-egui/src/widgets/look_tests.rs b/crates/ui-egui/src/widgets/look_tests.rs index c6c241e504..0b89811929 100644 --- a/crates/ui-egui/src/widgets/look_tests.rs +++ b/crates/ui-egui/src/widgets/look_tests.rs @@ -524,3 +524,28 @@ fn kerning_reads_parentheses_around_its_text_with_a_manual_value_too() { assert_eq!(typed(automatic, "(1,5)"), Some(SpinPick::Value(1.5)), "a decimal comma, automatic: {automatic}"); } } + +/// Enter on text that reads as no number in a range field refuses it as a unit field does: the +/// field flashes and an open dialog is not confirmed with the old value. +#[test] +fn a_range_field_refuses_text_that_reads_as_no_number() { + let typed = |text: &str| { + let ctx = themed(Default::default()); + let picked = std::cell::Cell::new(None); + let mut add = |ui: &mut Ui| { + if let Some(v) = range_field(ui, "count", 12.0, 0.0..=100.0, "", 0, 80.0) { + picked.set(Some(v)); + } + }; + arm_field_focus(&ctx, "count"); + frame(&ctx, 0.0, vec![], &mut add); + frame(&ctx, 0.1, vec![], &mut add); + let enter = |pressed| egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed, repeat: false, modifiers: Default::default() }; + frame(&ctx, 0.2, vec![egui::Event::Text(text.into()), enter(true), enter(false)], &mut add); + let refused = ctx.data_mut(|d| d.remove_temp::(dialog_reject_commit_flag())).unwrap_or(false); + (picked.get(), refused) + }; + assert_eq!(typed("40"), (Some(40.0), false), "a number commits"); + assert_eq!(typed("abc"), (None, true), "text that reads as no number is refused"); + assert_eq!(typed("(10+5)*2"), (None, true), "parentheses the field doesn't read are refused"); +} diff --git a/crates/ui-egui/src/widgets/numeric.rs b/crates/ui-egui/src/widgets/numeric.rs index 01ce18757f..a9d4020ab3 100644 --- a/crates/ui-egui/src/widgets/numeric.rs +++ b/crates/ui-egui/src/widgets/numeric.rs @@ -917,7 +917,19 @@ fn bounded_field_reading( let stepped = step_value(ui, &resp, &mut buf, bounds, (read, show), step, &[]).map(|v| round_to(v, decimals)); let scrubbed = scrub::field(ui, id, rect, &buf, value, decimals, bounds); if commit && buf != shown { - read(&buf) + let typed = read(&buf); + if typed.is_none() { + // Text that reads as no number is refused as [`unit_field_from`] refuses it: the field + // flashes, shows its value again, and an open dialog is not confirmed by this Enter. + let end = ui.input(|i| i.time + 0.25); + ui.data_mut(|d| { + d.remove::(id); + d.insert_temp(id.with("invalid-flash"), end); + }); + crate::widgets::reject_dialog_commit(ui.ctx()); + ui.ctx().request_repaint(); + } + typed } else if let Some(v) = stepped.or(scrubbed).filter(|&v| Some(v) != value) { Some(v) } else if live && resp.changed() { diff --git a/docs/effects-parity.md b/docs/effects-parity.md index 6b0f365ce8..4ee2d45611 100644 --- a/docs/effects-parity.md +++ b/docs/effects-parity.md @@ -180,7 +180,7 @@ VectorCraft choices; an original approximation, never compared with another appl |---|---| | Revolve | initial: live, editable profile, rotation and light gizmos, default-on Cap with continuous curved rims that also closes a partial sweep's cut sides, smooth vector shading and round seam joins, overlapping faces drawn in the order of their depths where they overlap, SVG/PDF output, Expand Appearance ([revolve.md](revolve.md), #846) | | Extrude & Bevel, Inflate, Rotate | initial: live, round seam joins, depth, twist, taper, solid or hollow caps, five original bevel shapes, Inflate volume, both sides, twist, taper and cap, Rotate of every fill and stroke, groups and layers turned about one shared axis (#4506), contours that cross, touch or overlap merged first ([three-d.md](three-d.md)), Position presets, rotation and light gizmos, SVG/PDF output, Expand Appearance ([three-d.md](three-d.md)) | -| Materials panel, lighting, ray-traced render | Window › 3D and Materials panel with the object types (Plane, Extrude, Revolve, Inflate) and the Object, Rotation and Lighting settings of the applied effect, Render Settings › Wireframe, which draws the live effect as the edges of its faces, and Quick Actions › Expand as Wireframes ([three-d.md](three-d.md#3d-and-materials-panel)); one to ten directional lights with per-light Color (opaque RGB, white by default), Intensity, Rotation, Height, Softness and neutral Ambient Light, Revolve and colored Inflate use smooth vector shading; Extrude & Bevel and Rotate retain planar shading; original Standard, Diffuse, Top Left and Right lighting rigs; shadows behind or below the object from the first light, blurred by its Softness ([three-d.md](three-d.md#shadows)); the Materials tab's Graphics, document symbols mapped onto Extrude & Bevel's caps and onto a plane, moved with an artboard handle, wrapped around Revolve's side, and carried onto Inflate's puffed front and back ([three-d.md](three-d.md#graphics)); no base materials, graphics on Extrude & Bevel's walls and bevels, or ray tracing | +| Materials panel, lighting, ray-traced render | Window › 3D and Materials panel with the object types (Plane, Extrude, Revolve, Inflate) and the Object, Rotation and Lighting settings of the applied effect, Render Settings › Wireframe, which draws the live effect as the edges of its faces, and Quick Actions › Expand as Wireframes ([three-d.md](three-d.md#3d-and-materials-panel)); one to ten directional lights with per-light Color (opaque RGB, white by default), Intensity, Rotation, Height, Softness and neutral Ambient Light, Revolve and colored Inflate use smooth vector shading; Extrude & Bevel and Rotate retain planar shading; original Standard, Diffuse, Top Left and Right lighting rigs; shadows behind or below the object from the first light, blurred by its Softness ([three-d.md](three-d.md#shadows)); the Materials tab's Graphics, document symbols mapped onto Extrude & Bevel's caps and onto a plane, moved with an artboard handle, wrapped around Extrude & Bevel's walls and bevels and around Revolve's side, and carried onto Inflate's puffed front and back ([three-d.md](three-d.md#graphics)); no base materials or ray tracing | | 3D (Classic): Extrude & Bevel, Revolve, Rotate | Extrude & Bevel (Classic) initial: live, round seam joins, Extrude Depth, Cap, five original bevel shapes with Height and Bevel Extent In or Out, Position presets and rotation gizmo, Perspective, Wireframe, No Shading, Diffuse and Plastic surfaces with one to ten lights, Light Intensity, Ambient Light, Highlight Intensity and Size, Blend Steps, Black, Custom, Black Overprint or no Shading Color ([Black Overprint](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=188)), Draw Hidden Faces ([create 3D objects](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/create-3d-objects.html)); Revolve (Classic) initial: live, round seam joins, Angle, Cap, Offset from the left or right edge, Position presets and rotation gizmo, Perspective, the same four surfaces, lights, highlight, Blend Steps and Shading Color, groups and layers revolved about one shared axis (same page); Rotate (Classic) initial: live, round seam joins, every fill and stroke turned as one plane, Position presets and rotation gizmo, Perspective, No Shading and Diffuse surfaces with lights, Ambient Light, Blend Steps and Shading Color ([rotate objects in 3D](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/rotate-objects-in-3d.html)); Preserve Spot Colors in all three, unavailable with a Custom Shading Color ([Preserve Spot Color](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=260)); all three: a lighting sphere on the Lighting tab whose lights drag, move to the back or front, and are added at the front center or deleted down to one ([lighting options](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=272)); all three: the track cube (face, edge, Shift and ring drags, keyboard steps; [three-d.md](three-d.md#track-cube)); Map Art: none | | 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/file-format-parity.md b/docs/file-format-parity.md index 91af8cd7b3..36e73837d8 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File format parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-17 · **Change:** minor (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; scores and estimates unchanged; previously: PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, not butt caps and miter joins, #7741; `.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; `.ai` and EPS import: a top-object envelope whose mesh saves its sides' curves in pieces draws its contents along each whole curve, as its drawn art does, #7097; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: `.ai` and EPS import: type from the text document, type a PostScript program sets and legacy `.ai` type are set in an installed face of their font's PostScript name, exact name first, in the version a text document's record keeps; the `.ai` save writes a static font's version when its name alone gives another copy, #6983; `.ai` and EPS import: type keeps the manual kerning of its text document, #6899; `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, its strokes' miter tips and strokes a Transform effect moves included, after its glyphs grown by half its strokes' weight, #6824; `.ai` and EPS import: type filled or stroked with a pattern swatch keeps its pattern, from the art style its text document paint names, #6856; #6865: explicitly requested oversized editing artboard; PDF import: Indic type keeps its marks on their line, and a line whose type would not draw as the file does keeps the file's glyphs as outlines, #5235; previously: newly imported SVG/SVGZ titles are filtered and bounded without changing restored titles, #3626; `.ai` and EPS import, and what every export and `.ai` save draw: type's strokes in an envelope paint at their own weight along its bent outlines, Distort Appearance on or off, #6644; `.ai` and EPS import: centred and right-aligned lines of tracked type are aligned without the tracking after their last character, as the file's page aligns them, #6610; `.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; `.ai` save and open: layer colour presets Yellow, Magenta and Cyan keep their colour, as the `Lb` colour index now follows the file's numbering, #6502; `.ai` save: stroked type keeps its stroke's cap, join and miter limit in the text document, #6472; `.ai` and EPS import, PDF import: tracking and manual kerning in horizontally scaled type take the Horizontal Scale, as the file's page spaces such type; `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke, #3179; `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid, #3179; `.ai` and EPS import: stroked type keeps its stroke's cap, join and miter limit from the text document, #6472; `.ai` save: type in a variable font's named instance names its design-space setting, #6388; `.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; `.ai` and EPS import: a note for type in an envelope, #3179; `.ai` and EPS import: the live envelope and warped type check sees white art; PDF import: DeviceN images of one ink or of process plates keep their inks, #6348; `.ai` import: images in a spot ink's Separation space keep their ink, #6350; PDF import: Separation images keep their ink, #6314; 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; PDF import: image masks open colorized by the color they are painted in, #6313; EPS and `.ai` editing data: a ligature the page names by a private-use glyph matches its text object; EPS import: CIDFonts only named, over a Unicode CMap, set as live type; EPS import: CMap mappings to base-font codes and glyph names; EPS import: CID-keyed fonts in FontSets (CFF) draw their glyphs; EPS import: `kshow` procedures kern live type; EPS import: embedded Type 1 fonts' glyphs and widths; EPS import: CID-keyed fonts draw their glyphs; EPS import: Type 42 fonts' characters and widths from the font they carry, show operators' spacing kept as tracking; EPS import: an image decoder's own buffers stop counting against the memory budget once it is decoded; EPS import: sampled functions interpolate between their samples; `.ai` and EPS type from the text document keeps its tab stops; it keeps auto leading and hyphenation options, and may show more of the file's last lines in an area frame; `.ai` and EPS import: Art brushes in the older form of their objects come into the Brushes panel; EPS import: gradients drawn as abutting strips come in as one gradient, without seams; EPS import: composite fonts draw their Type 42 glyphs; SVG import: filter and mask regions clip, #5876, #5875; SVG import: Gaussian blurs keep `color-interpolation-filters`, #5877; PDF and `.ai` export: objects' URLs as links, #5785; SVG import: `color-interpolation="linearRGB"` gradients, #5878; `.ai` import: paths with a Calligraphic brush open brushed, #372) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-18 · **Change:** minor (PDF export writes the document language as the catalog's `/Lang`, #3644; 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; scores and estimates unchanged; previously: PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, not butt caps and miter joins, #7741; `.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; `.ai` and EPS import: a top-object envelope whose mesh saves its sides' curves in pieces draws its contents along each whole curve, as its drawn art does, #7097; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: `.ai` and EPS import: type from the text document, type a PostScript program sets and legacy `.ai` type are set in an installed face of their font's PostScript name, exact name first, in the version a text document's record keeps; the `.ai` save writes a static font's version when its name alone gives another copy, #6983; `.ai` and EPS import: type keeps the manual kerning of its text document, #6899; `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, its strokes' miter tips and strokes a Transform effect moves included, after its glyphs grown by half its strokes' weight, #6824; `.ai` and EPS import: type filled or stroked with a pattern swatch keeps its pattern, from the art style its text document paint names, #6856; #6865: explicitly requested oversized editing artboard; PDF import: Indic type keeps its marks on their line, and a line whose type would not draw as the file does keeps the file's glyphs as outlines, #5235; previously: newly imported SVG/SVGZ titles are filtered and bounded without changing restored titles, #3626; `.ai` and EPS import, and what every export and `.ai` save draw: type's strokes in an envelope paint at their own weight along its bent outlines, Distort Appearance on or off, #6644; `.ai` and EPS import: centred and right-aligned lines of tracked type are aligned without the tracking after their last character, as the file's page aligns them, #6610; `.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; `.ai` save and open: layer colour presets Yellow, Magenta and Cyan keep their colour, as the `Lb` colour index now follows the file's numbering, #6502; `.ai` save: stroked type keeps its stroke's cap, join and miter limit in the text document, #6472; `.ai` and EPS import, PDF import: tracking and manual kerning in horizontally scaled type take the Horizontal Scale, as the file's page spaces such type; `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke, #3179; `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid, #3179; `.ai` and EPS import: stroked type keeps its stroke's cap, join and miter limit from the text document, #6472; `.ai` save: type in a variable font's named instance names its design-space setting, #6388; `.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; `.ai` and EPS import: a note for type in an envelope, #3179; `.ai` and EPS import: the live envelope and warped type check sees white art; PDF import: DeviceN images of one ink or of process plates keep their inks, #6348; `.ai` import: images in a spot ink's Separation space keep their ink, #6350; PDF import: Separation images keep their ink, #6314; 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; PDF import: image masks open colorized by the color they are painted in, #6313; EPS and `.ai` editing data: a ligature the page names by a private-use glyph matches its text object; EPS import: CIDFonts only named, over a Unicode CMap, set as live type; EPS import: CMap mappings to base-font codes and glyph names; EPS import: CID-keyed fonts in FontSets (CFF) draw their glyphs; EPS import: `kshow` procedures kern live type; EPS import: embedded Type 1 fonts' glyphs and widths; EPS import: CID-keyed fonts draw their glyphs; EPS import: Type 42 fonts' characters and widths from the font they carry, show operators' spacing kept as tracking; EPS import: an image decoder's own buffers stop counting against the memory budget once it is decoded; EPS import: sampled functions interpolate between their samples; `.ai` and EPS type from the text document keeps its tab stops; it keeps auto leading and hyphenation options, and may show more of the file's last lines in an area frame; `.ai` and EPS import: Art brushes in the older form of their objects come into the Brushes panel; EPS import: gradients drawn as abutting strips come in as one gradient, without seams; EPS import: composite fonts draw their Type 42 glyphs; SVG import: filter and mask regions clip, #5876, #5875; SVG import: Gaussian blurs keep `color-interpolation-filters`, #5877; PDF and `.ai` export: objects' URLs as links, #5785; SVG import: `color-interpolation="linearRGB"` gradients, #5878; `.ai` import: paths with a Calligraphic brush open brushed, #372) · **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). @@ -315,7 +315,7 @@ Gradient meshes in the editing data keep each point's own color where a patch's | VectorCraft `.vectorcraft` / `.vctemplate` | — | yes | yes | lossless JSON, versioned, save down to v1; property-tested round trips (`format/tests/prop_format.rs`); documents with a lot of path data are written as compact JSON, about a fifth of the size (#1492); a save falls back to a plain fsync and to writing elsewhere and copying in when the folder refuses the usual steps (#1625, #1649, part of #1620; not confirmed on a real network share); the size limits on embedded data also apply to files read from memory (#1783), and saving over a private file on Unix leaves no readable temporary copy beside it (#1778); a dynamic symbol's type (`dynamic` on the symbol) and an instance's appearance changes to its art (`symbol_overrides`, each path at most 64 deep, counted against the object budget) are written only when set, so documents without them save as before (#4938) | | Illustrator template `.ait` | open, save | yes | PDF-compatible only, from Save as Template (`.vctemplate` stays its default) | New from Template opens a saved `.ait` untitled with its layers and art (`tests_pdfedit.rs`) | | Illustrator `.ai` | open, save | yes (PDF-compatible + editing-data structure with template layers and ruler guides, File Info) | PDF-compatible, or legacy version 7 (layers and groups) | see above; no real-file corpus | -| PDF | open, place, save | yes (authored ActualText in editable import, #6165; layers, masks, editable text, security, overprint, File Info from the XMP packet and the document information dictionary; Crop To › Trim takes the bleed box as the document's bleed; Import PDF pages as links opens each page as a placed document linked to it, on its own artboard, `tests/placed_document.rs`, and is checked when All is picked and cleared when Range is picked) | yes (presets, PDF/X-1a/3/4, layers, marks and bleed, ICC, fast web view, 1.3+; objects' URLs as link annotations, not in PDF/X) | fuzzed import; shared guarded writer and windowed reader ([pdf-backend.md](pdf-backend.md)), metadata, incomplete-content and dependency-source regressions; PDF text opens where the file draws it, glyph by glyph (#722: kerning or none, spacing per character, text rise as baseline shift, vertical writing, justified text boxes); alpha soft masks drawn as images import with the mask (#1551); a clip only counts as covering the page when its shape does (#1542); a PDF another app copied pastes as editable vector art (#1499); letter-spaced type on a path keeps its length and its glyph-by-glyph stroke comes in as one text object (#1586, #1585); a crafted name tree with shared nodes no longer takes exponential time on open (#1781); fonts named with hyphens (`Noto-Sans-Bold`) or with a composite font's CMap (`Name-Identity-H`) find the installed family; invisible text (rendering mode 3: a scanned page's recognized text) opens as type with no fill or stroke and saves back as invisible, searchable text (#2675); PDF/X-1a and X-3 flattening in a CMYK document keeps CMYK inks where it rasterizes (#2160); an image mask (`/ImageMask true`) painted in a solid color opens as a grayscale image colorized by that color, a spot color keeping its swatch and tint, so Fill and Recolor Artwork reach it, and the same mask painted again in another color keeps that color (#6313); an image in a Separation space opens as a grayscale image of its tints colorized by its ink at 100 % (a spot swatch, a process plate or Registration), its soft mask as its opacity mask (#6314); a DeviceN image of one colorant opens the same way, and one of process plates only (the ink `None` may be among them) opens in CMYK with each colorant's tint in its plate (#6348) 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. | +| PDF | open, place, save | yes (authored ActualText in editable import, #6165; layers, masks, editable text, security, overprint, File Info from the XMP packet and the document information dictionary; Crop To › Trim takes the bleed box as the document's bleed; Import PDF pages as links opens each page as a placed document linked to it, on its own artboard, `tests/placed_document.rs`, and is checked when All is picked and cleared when Range is picked) | yes (presets, PDF/X-1a/3/4, layers, marks and bleed, ICC, fast web view, 1.3+; objects' URLs as link annotations, not in PDF/X; the document language as the catalog's `/Lang` and XMP `dc:language`, #3644) | fuzzed import; shared guarded writer and windowed reader ([pdf-backend.md](pdf-backend.md)), metadata, incomplete-content and dependency-source regressions; PDF text opens where the file draws it, glyph by glyph (#722: kerning or none, spacing per character, text rise as baseline shift, vertical writing, justified text boxes); alpha soft masks drawn as images import with the mask (#1551); a clip only counts as covering the page when its shape does (#1542); a PDF another app copied pastes as editable vector art (#1499); letter-spaced type on a path keeps its length and its glyph-by-glyph stroke comes in as one text object (#1586, #1585); a crafted name tree with shared nodes no longer takes exponential time on open (#1781); fonts named with hyphens (`Noto-Sans-Bold`) or with a composite font's CMap (`Name-Identity-H`) find the installed family; invisible text (rendering mode 3: a scanned page's recognized text) opens as type with no fill or stroke and saves back as invisible, searchable text (#2675); PDF/X-1a and X-3 flattening in a CMYK document keeps CMYK inks where it rasterizes (#2160); an image mask (`/ImageMask true`) painted in a solid color opens as a grayscale image colorized by that color, a spot color keeping its swatch and tint, so Fill and Recolor Artwork reach it, and the same mask painted again in another color keeps that color (#6313); an image in a Separation space opens as a grayscale image of its tints colorized by its ink at 100 % (a spot swatch, a process plate or Registration), its soft mask as its opacity mask (#6314); a DeviceN image of one colorant opens the same way, and one of process plates only (the ink `None` may be among them) opens in CMYK with each colorant's tint in its plate (#6348) 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. | | EPS | open, place, save | yes (own PostScript L3 interpreter, Illustrator EPS editing data structure) | yes (L2/L3, TIFF previews) | CIDFonts the file doesn't carry not drawn, but for those over a predefined CMap (`UniJIS-UCS2-H`, `90ms-RKSJ-H`, `GBK-EUC-H`, `KSCms-UHC-H`, `ETen-B5-H`), set as type in the font of the CIDFont's name, vertical over a `-V` CMap; a name that ends in the row-and-cell CMap `H` or `V` splits off the CMap only when the file defines the CIDFont of that name, the CIDFont is `Ryumin-Light` or `GothicBBB-Medium` (the Japanese CIDFonts a printer carries), or the name has a hyphen and an installed face that covers Japanese has it; name-keyed fonts in a FontSet set as type by name; #505; images encoded with `CCITTFaxDecode` (ITU-T T.4 Group 3 and T.6 Group 4, with `K`, `Columns`, `Rows`, `EndOfBlock`, `EndOfLine`, `EncodedByteAlign` and `BlackIs1`) draw, and damaged data keeps the rows decoded before its first damaged row; Type 42 (TrueType) fonts set type at its size (#1553); an embedded Type 1 font's encrypted part is read for its glyphs, which space its type, outline it and draw glyphs without a character, in plain and composite fonts; a Type 42 font that carries its TrueType font gives each code its character by its glyph name or, for names that say nothing (`/g12`), by the glyph's entry in the font's own character map, spaces its type by its own widths and draws glyphs that stand for no character from its outlines; the show operators' spacing along the baseline (`ashow`, `widthshow`, `xshow`, `yshow`, `xyshow`, and the moves of `kshow`'s procedure, run between each two characters) is kept on live type as tracking, so type in a font that isn't installed keeps the file's line lengths (spacing that moves characters off the baseline, as `yshow`, `xyshow` or a `kshow` procedure can, places each character as its own text object); composite (Type 0) fonts with the 8/8 mapping, as PDF-to-PostScript converters write two-byte fonts, draw a Type 42 descendant's glyphs from the TrueType outlines it carries and an embedded Type 1 descendant's from its charstrings, and set other descendants' characters as type at the composite font's size (other mappings are still set as type in the font of their name); CID-keyed fonts (`composefont`, `FMapType` 9 over a CMap built with the CIDInit operators or `Identity-H`/`Identity-V`; `bfchar` and `bfrange` mappings give a base-font descendant its codes or glyph names) draw the glyphs of the Type 0 CIDFonts (Type 1 charstrings in their `StartData` binary data or `GlyphDirectory`) and Type 2 CIDFonts (TrueType glyphs through `CIDMap`) they carry, and the CID-keyed fonts of a FontSet's Compact Font Format data (Type 2 charstrings); a clip only counts as covering the page when its shape does (#1542); an EPS another app copied pastes as editable vector art (`clipboard.importEps`, #1499); a stitched shading keeps its hard colour changes on import (#1654); sampled functions (type 0) interpolate between their samples, multilinearly or by cubics with `Order 3`, and a sampled axial or radial gradient has a stop at each sample; a gradient the page paints as a row of abutting one-colour strips (as Level 2 writers draw smooth shades) imports as one linear gradient, without the seams the strips leave when each is drawn alone; CMYK images, CMYK JPEGs included, keep their ink amounts on import, as from PDF, and the pixels a `MaskColor` or `ImageType 3` mask hides become a grayscale opacity mask; ruzstd 0.9.1 for compressed editing data (#1807, RUSTSEC-2026-0344) | | PostScript `.ps` | open, place | yes (the EPS reader reads its first page; `.epsf` files open and place as EPS) | via Print to PostScript | `tests_epsimport.rs` | | DCS 1.0 / 2.0 | place linked | place linked only (one image of the plates; spot plates as spot swatches; the composite's clipping path; each plate on its own ink in Separations Preview and print separations) | no | `crates/eps/src/dcs/tests.rs`, `crates/engine/src/tests/dcs.rs` | @@ -383,6 +383,7 @@ Stop opacity on translated artboards remains outside this regression coverage. | Date | Change | Summary | |---|---|---| +| 2026-11-18 | minor | PDF export (#3644): the document language chosen in Document Setup is written as the catalog's `/Lang` (BCP 47, `en-US` by default) and as XMP `dc:language`; a language without a tag writes none. Scores and estimates unchanged. | | 2026-11-17 | minor | PDF import (#8300): a glyph filled only (text rendering mode 0) right after one filled and stroked (mode 2) joined the stroked run and came in stroked too: `2 Tr (B) Tj 0 Tr (C) Tj` came in as `BC` stroked throughout. A glyph filled only now joins only a run drawn alike, so it starts a run of its own, filled only, in the same type object, and takes a stroke only when the file draws one over it (the #8015 matching); a word filled whole then stroked whole, and fill and stroke rendering glyph by glyph, still come in as one run filled and stroked. Tests: `a_glyph_filled_only_after_one_filled_and_stroked_is_not_stroked`, `glyphs_filled_and_stroked_one_by_one_stay_one_run`; scores and estimates unchanged. | | 2026-11-17 | minor | PDF import (#8015 follow-up): type filled and stroked at less than full opacity is no longer joined into one type object, since the file composites the fill and the stroke apiece, darker where they overlap, while one object's opacity applies to both together; it stays a filled object and a stroked one, as a fill and stroke at different opacities already did. An upright glyph (vertical type) filled and stroked is no longer kept as an outline for a line that comes in as its outlines, as glyphs filled only weren't, so such a line can't lose them. The #8015 entries now say what is left: translucent type filled and stroked, and a `TJ` whose kerning starts a new line part way through, still come in as two objects. Tests: `translucent_fill_and_stroke_text_stays_two_objects`, `a_vertical_line_with_one_glyph_filled_and_stroked_keeps_every_glyph_filled`; scores and estimates unchanged. | | 2026-11-16 | minor | PDF import: fill and stroke rendering (text rendering modes 2 and 6) draws all the glyphs of a text-showing operator (`Tj`, `TJ`, `'`, `"`) filled, then the same glyphs stroked, so a word shown at once came in as two type objects: a stroke-only copy over a fill-only one. Each stroke is now matched, in order, to the glyph filled with the same placement (where, how large, how wide, slanted and turned) in the same font with the same text on the line, and only that glyph takes the stroke, so the word comes in as one type object, filled and stroked; glyphs stroked with another join part way through still split into runs of their own, and stroked type over no filled glyph (modes 1 and 5) stays stroke only (#8015; `a_word_filled_then_stroked_imports_as_one_filled_and_stroked_type` in `crates/pdf/src/tests/textstroke.rs`, `a_vertical_column_filled_then_stroked_is_one_filled_and_stroked_type` in `crates/pdf/src/tests/text_placement.rs`). Scores and estimates unchanged. | diff --git a/docs/gaps.md b/docs/gaps.md index 5dee50afa1..304535dacb 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Gaps -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-16 · **Change:** minor (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: 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-18 · **Change:** minor (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: 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) > Selection update (2026-11-11): path and compound-path interiors follow enabled non-None fill rows, including lower fills beneath a top None row (#6625). Hidden-only interiors miss; zero-opacity fills remain selectable. Cap/join follow-up (2026-11-12): hidden-fill and no-fill stroke hits must respect cap and join geometry; focused cap/join CPU regressions passed. Scores and estimates unchanged. @@ -36,6 +36,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-11-18 | minor | G19: PDF export writes the document language chosen in Document Setup as the catalog's `/Lang` (its BCP 47 tag, `en-US` by default) and the XMP packet's `dc:language`, in exported and printed PDFs (#3644); `/MarkInfo` stays with tagged PDF (#3643). Scores and estimates unchanged. | | 2026-11-16 | minor | G1: Recolor Artwork - native Lab entry in Color Picker, swatch libraries access in Color Picker, and row right-click context menu ("Pick from Swatches", "Limit to Library") (#4028); scores and estimates unchanged. | | 2026-11-15 | minor | G4 type: modal Check Spelling dialog (Edit › Spelling › Check Spelling…, `ui.checkSpelling`, #4936) with Not in Dictionary sentence context, suggestions, Ignore, Ignore All, Change, Change All, Add to Dictionary, Done/Cancel, keyboard navigation, and one-step Undo/Redo; spell check complete; scores and estimates unchanged. | | 2026-11-15 | minor | G5: Neon & Glow joins Shadows and Glows, Outlines and Rules, Hand-Drawn, Textures, Painted and Sketched, Gradient Finishes, Shape Effects, Blends and Transparency, Game HUD and Status Effects as an eleventh built-in graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor; original procedural styles generated in code); estimate unchanged (3–13 h). | @@ -869,7 +870,7 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi - **Missing:** AccessKit is on by default, so egui widgets reach screen readers, but custom panels, the canvas and its objects aren't described and nothing has been tested with VoiceOver, Narrator or Orca; keyboard-only canvas operation; high contrast. Illustrator's own accessibility is limited, so this is mostly beyond parity. -- **Done:** PDF export writes `/ViewerPreferences << /DisplayDocTitle true >>` when File Info has a Document Title (or an explicit export title is supplied), so viewers and accessibility checkers use that title instead of the file name (#3646). +- **Done:** PDF export writes `/ViewerPreferences << /DisplayDocTitle true >>` when File Info has a Document Title (or an explicit export title is supplied), so viewers and accessibility checkers use that title instead of the file name (#3646). It writes the document language chosen in Document Setup as the catalog's `/Lang` (its BCP 47 tag, `en-US` by default) and the XMP packet's `dc:language`, so screen readers and checkers know the language (#3644). Tagged PDF (structure tree, `/MarkInfo`) is still missing (#3643). - **Estimate:** 15–25 h. ## Highlighted-text Eyedropper (2026-10-21) diff --git a/docs/mcp.md b/docs/mcp.md index 36ee43f233..da6b96fb87 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -286,6 +286,16 @@ the suite) keep the agent to the folders you give it: linked native document with `relink: false`, as it is: when the native document such a file is or carries keeps a folder outside the read roots, the package is refused before anything is written with "a linked file's export folder is outside the read roots", which names no file or folder. +- An exporter plug-in's format (`plugin.`) carries the native document too: its plug-in is given the + document's JSON. The JavaScript and linked image rules above refuse its files from every command that writes + them, before the plug-in runs and before any file or folder is written, and the JSON the plug-in is given + leaves out an Export for Screens folder outside the read roots. +- `file.package` refuses, before anything is written, a linked file whose native document it can't read to + check against the read roots: a native document that doesn't load, a PDF or `.ai` file that can't be opened + (one that needs a password to open, or a damaged one), and a PDF, `.ai` or EPS file whose editing data + doesn't load. The error, "a linked file's editing data can't be read to check it against the read roots", + names no file or folder. A PDF, `.ai` or EPS file without editing data is copied as before, and the person at + the keyboard packages every linked file as before. - `plugin.list`, `plugin.safeMode`, `file.recovery.*` and `ui_inspect`'s `scriptReport` leave out the paths outside the read roots, also those the person or an earlier request put there. In `plugin.list`, the plug-in folder last loaded is `null` in `folder.folder`, and a failed file in `folder.failed` and a plug-in's `source` @@ -714,7 +724,7 @@ ends the wait, so the sampler can be shown again. The BSDs and headless sessions | `add_text` | `{text, x?, y?, width?, height?, fit?, fitMinPercent?, path?, mode?, pathEffect?, size?, font?, color?, justify?, vertical?}` | Point type at (x, y) (`justify`: `left`, `center` or `right` starts, centres or ends each line on x); area type with `width`/`height` (`fit`: `none`, `autoHeight`, `shrinkText`, as `text.areaOptions`); or `path` + `mode` (`area`/`onPath`) to flow text in or along a path, with `pathEffect` for type on a path (`rainbow`, `skew`, `3dRibbon`, `stairStep`, `gravity`; SVG export writes type on a path with any effect other than `rainbow` as outlines, with a warning). An invalid effect is rejected before editing. `justify` (also `auto`, `justifyAll`) aligns the paragraphs of every kind, as `text.setStyle` does later. `vertical: true` uses the existing vertical writing mode for every kind (default `false`, horizontal). Returns `{id}`, with `overflow: true` when the text doesn't fit its frame or path. | | `apply_effect` | `{effect?, params?, ids?}` | Appends a live effect. Without `effect`, returns the effect catalogue with parameters and defaults. | | `pathfinder` | `{operation, ids?}` | `unite`, `minusFront`, `intersect`, `exclude`, `divide`, `trim`, `merge`, `crop`, `outline`, `minusBack`. For a live version, apply the `pathfinder.*` effect to a group (`effect.apply` groups several loose selected objects first). In remote desktop mode, `run_command` and `invoke_menu` can both call `pathfinder.repeat` with `{}`. Successful panel operations, direct `object.pathfinder.*` commands, and `command.batch` steps (including Actions panel playback) set its history. Repeat applies it to the current selection using current Pathfinder Options. Trap, compound-shape edits, live effects and `action.batch` do not set history. With no history it returns "no Pathfinder operation applied yet". | -| `transform` | `{ids?, dx?, dy?, rotate?, scale?, scaleX?, scaleY?, reflect?, shear?, origin?, copy?}` | Runs move, rotate, scale, reflect, shear in that order. `rotate` is in degrees counter-clockwise; a positive `shear` moves the top to the right. With `copy`, the first step duplicates. | +| `transform` | `{ids?, dx?, dy?, rotate?, scale?, scaleX?, scaleY?, reflect?, shear?, origin?, copy?}` | Runs move, rotate, scale, reflect, shear in that order. `rotate` is in degrees counter-clockwise; a positive `shear` moves the top to the right. With `copy`, the first step duplicates. A `scale`, `reflect` or `shear` that its command would refuse returns that error before any step runs; nothing changes and no undo step is recorded. | | `create_graph` | `{type?, x, y, width, height, csv? \| series?, categories?, rows?}` | The nine Illustrator graph types: column, stacked column, bar, stacked bar, line, area, scatter, pie and radar. An empty CSV cell or a `null` in `rows` is a blank value; a number in straight quotes is a label. Edit later with `graph.setData` / `graph.setType` via `run_command`. `graph.column {design, columnType: vertical\|uniform\|repeating\|sliding, each, fractions: chop\|scale}` draws the columns or bars of the series picked with Group Selection (or `seriesIndexes`, or all of them) with a graph design saved by `graph.design`; with no `design` it returns the series' current design and options. Type in the design that holds a `%` followed by two digits shows each column's value, with at least the first digit's places before the decimal point and the second digit's places after it. | | `text_wrap` | `{ids?, offset?, invert?, release?}` | Area type below the objects (same layer) flows around them. `offset` is in points, from -1000 to 1000 (default 6). An offset outside that range or not a number, or an `invert` or `release` that is not true or false, is an error and changes nothing; `object.textWrap.make` and `object.textWrap.options` refuse the same values. | | `undo` / `redo` | `{}` | Many calls that change nothing record no undo step, for example `object.align` with nothing to move, `object.move` by 0 without `copy` and `object.showAll` with nothing hidden. `undo` (`edit.undo`) after such a call undoes the step before it. Settings that change without an undo step stay as they are when `undo` or `redo` brings back a step that did not change them: the perspective grid's view options and active plane, the grid preferences (`gridlineEvery`, `gridSubdivisions`), the export settings (`assets.settings.set`), and the current brush and symbol. A step that changed one of them, such as a perspective grid preset that shows the grid, takes that change back. The point Automatic Plane Positioning holds comes back with the step, and is let go when the active plane kept is another one. `inspect_document` lists the undo steps as `history`. `run_command` with `edit.clearHistory` removes every undo and redo step of the active document and returns `{cleared}`, the number of steps removed; the document stays as it is, and the command records no undo step. `run_command` with `edit.newDocumentFromState` and `{index?, created?}` makes a new document holding the art as it was at that state and makes it the active document, and returns `{index, title}`. `index` is a row of the History panel, with 0 the oldest state kept, and an omitted or null `index` uses the current state. An `index` that names no state fails with `no history state N`, one that is not a whole number with `` `index` must be a whole number ``, and either changes nothing. `created` is File Info's created date in Unix seconds or null, and defaults to now. The new document takes the next `Untitled-N` name, is marked unsaved, has nothing selected and has no steps to undo or redo. It is out of symbol, opacity-mask and pattern editing, and the art drawn in a pattern's tile is stored in the pattern, as `object.pattern.done` stores it. The source document and its steps stay as they are, except that typing or a drag in progress is first kept as a step. When a command keeps a drag whose preview Real-time Drawing off had not applied yet (`edit.undo`, `edit.redo`, `edit.clearHistory`, `edit.newDocumentFromState` and the other commands that end a drag first), and applying that preview gives a warning, the command's result carries it as `previewWarning`, and as `warning` too when the command gives no warning of its own; the app's status bar shows `warning`. While the Type tool edits type, `undo` and `redo` put its caret, with no characters selected, at the end of the text the step changed: after the text it puts back or retypes, or where the text it takes out was. A step that changes no characters, such as a formatting change, leaves the caret and the selection where they are. | @@ -3446,6 +3456,39 @@ own layout rules. {"name":"invoke_menu","arguments":{"command":"window.toolbar.dock","params":{"name":"Toolbar 1","side":"left","order":0}}} ``` +## Help search + +Help › VectorCraft Help… and F1 show the Help panel. `help.discover {query?}` opens it without +toggling it closed. A supplied string searches tools, menu commands, and VectorCraft's built-in +tutorials. Omitting `query` preserves the current search. Empty or whitespace-only text clears +the results. VectorCraft limits a query to 1024 characters and rejects a longer supplied string. + +`help.discover.search {query}` runs the same search and shows the panel. Both commands return +`{query, results: [{kind, id, label, path, shortcut}], selected}`. `kind` is `tool`, `command`, or +`tutorial`; `selected` is a zero-based result index or `null`. Search matches all the query's +words without regard to case, using translated tool labels, command labels as their menus show +them, and the English labels, ids, and menu paths. A result's `path` names the menus as they are +drawn, with plug-in submenus and Scripts folders under their own names. Outside macOS, items of +the VectorCraft application menu, which only the macOS menu bar shows, are left out. Tutorial text remains in English. After a shortcut or the interface +language changes, the kept results show the current shortcuts, labels, and menu paths, with the +query and the selected result unchanged. A command result also shows its menu item's current +label (Show Grid becomes Hide Grid), and a command that no menu lists any more, such as a removed +recent file, drops out of the results. Parameters other than an object are an error. + +`help.discover.choose {index}` shows that result. A tool result marks its toolbar location without +choosing the tool. A command result shows its menu path and current shortcut without running it. +A tutorial result shows its numbered steps; a tool link in a step marks that tool's location. +The reply is `{result, location}`, with the chosen result and the tool-location reply, tutorial +id, or command path. An invalid index returns an error and preserves the selected result. When a +tool cannot be marked because Tab or Presentation Mode hides the toolbars, the panel shows the +tool-location reply's `reason` in the status bar. + +Home clears the search. Back and `help.discover.back {}` return to its results with the query +preserved. Escape in the search field closes the panel. Escape on the canvas still cancels an +active tool operation. The panel uses the existing tool-location marks; command guidance is a +menu path. Articles, Quick Actions, personalized recommendations, and Discover preferences are +not included. + ## Learn panel Window › Learn and the Explore tutorials button beside the search field at the right end of the app bar show and hide @@ -3624,7 +3667,13 @@ already walks Image Trace. Short agent entry points: - Symbols: `symbol.list` (each row includes `registration` 0..8, `exportType`: `movieClip`|`graphic`, `type`: `static`|`dynamic` and `alignToPixelGrid`), - `symbol.new {name?, registration?, exportType?, nineSlice?, nineSliceGuides?, type?, alignToPixelGrid?, ids?}`, + `symbol.new {name?, registration?, exportType?, nineSlice?, nineSliceGuides?, type?, alignToPixelGrid?, ids?, keepArt?: false}` + (New Symbol: the selection, or `ids`, becomes the symbol's art and an instance of it in one undo step; with + `keepArt: true` the art stays ordinary art in its place, with its ids, and stays selected unless it is hidden or + locked, and the result's `id` is null; a `keepArt` other than true or false is an error; the Symbols panel sends + `keepArt: true` when its New Symbol button, with or without Alt, or its New Symbol… menu item is used with Shift + held, through Symbol Options' OK (`ui.symbolOptions {keepArt: true}`), and when art dragged off the canvas is + released on the panel with Shift held), `symbol.options {name?, newName?, registration?, exportType?, nineSlice?, nineSliceGuides?, type?, alignToPixelGrid?}` (`nineSlice` bool turns 9-slice guides on or off; `nineSliceGuides` is `[left, top, right, bottom]`, fractions of the symbol size in from each edge, each -16..16 with `left + right < 1` and `top + bottom < 1`, a quarter each when none are given; below 0 @@ -3647,6 +3696,12 @@ already walks Image Trace. Short agent entry points: when that document is no longer open; plug-ins cannot call it), `symbol.breakLink {ids?}` (the art keeps the instance's opacity mask and its bounding box, square after `object.resetBoundingBox`; a hidden or locked instance's art stays hidden or locked and is not selected), `symbol.replace`, + `symbol.update {name, ids?|id?, keepArt?: false}` (Redefine Symbol: the selection, or `ids`, becomes the symbol's art and an instance + of it in one undo step; with `keepArt: true` the art stays ordinary art in its place, with its ids, and stays selected + unless it is hidden or locked, and the result's `id` is null; a `keepArt` other than true or false is an error; art that holds an instance of the symbol (opacity masks included), directly or through the art + of the symbols it holds instances of, is refused and nothing changes; the Symbols panel menu's Redefine Symbol sends `keepArt: true` when it + is chosen with Shift held, and the panel sends it with the dragged art's `ids` when art dragged + off the canvas is released on a symbol's tile or row with Alt (Option on macOS) held), `symbol.edit {id?, ids?, name?, x?, y?, artboard?, viewCenter?}` (symbol editing mode: the symbol's art on a temporary isolated layer, where the instance `id` shows it or centered on (x, y), by default on the center of artboard `artboard`, the active one the app passes, or in a document without artboards on `viewCenter`, the view's center the @@ -3771,7 +3826,21 @@ already walks Image Trace. Short agent entry points: `brush.new` or `brush.options` without a `key` takes the color that the art's fills and strokes use most (on a tie, the one found first), or black when they use no solid color. `brush.options` changes only the fields of `colorization` and of an art brush's `scale` that `params` gives, so `{colorization: {method: "hueShift"}}` keeps a - Hue Shift brush's key. `brush.new` and `brush.options` take a bristle brush name of at most 31 characters: + Hue Shift brush's key. A scatter brush's `hue_jitter` (0 to 180 degrees, VectorCraft's own range; 0, the + default, leaves every copy's colors as the colorization gives them) turns the hue of each copy's solid fills and + strokes, its type's characters included, by that copy's own amount between minus and plus that many degrees. The + turn comes after the colorization: with None it turns the art's own colors, with Tints and Tints and Shades the + tints and shades of the stroke color, and with Hue Shift the shifted colors. Black, white and grays (equal RGB + values, a Gray color, CMYK without C, M or Y ink, Lab without a or b) have no hue and stay as they are, so a Tints + brush on a black or gray stroke draws its copies unturned. A color turns in its own model: RGB in the HSB of its + values, CMYK over its C, M and Y with its K kept, and Lab by turning its a and b, so its saturation and brightness + (Lab: lightness and chroma) stay. Gradients and patterns stay as they are, and a turned color loses its swatch + link. A symbol instance in the art turns only its own fill, the stain it draws its symbol's art with; the + symbol's own colors stay. The amounts depend only on the stroke's path + and the brush's name, so a stroke draws the same colors on every redraw, after Save and Open, and in export. Hue + jitter does not change where the copies go or their size and rotation. A value outside the range is clamped, as + the brush's other values are. A brush saves `hue_jitter` only when it is above 0, and a brush without the key + reads as 0; `brush.get` shows it for every scatter brush. `brush.new` and `brush.options` take a bristle brush name of at most 31 characters: `brush.new` refuses a longer one, counting the number it adds to a taken name, and `brush.options` refuses a longer `newName`. `brush.duplicate` does not check the length. A bristle brush that already has a longer name keeps it, and `brush.options` without a new name, or with a `newName` that only trims the white space around the @@ -4562,8 +4631,14 @@ object's, type its characters'). `graphicStyle.apply {name, ids?}` gives the obj style's look: editing their appearance or transparency breaks the link, and `graphicStyle.redefine {name?, id?}` updates only the objects still linked. Art dragged off the canvas, or the Appearance panel's thumbnail, dropped on a style in the Graphic Styles panel with Alt held runs `graphicStyle.redefine` with that style's `name` and the object's -`id` (the first object of the art); an object already linked to the style with its look changes nothing. The art of a -column or marker design in a graph series is never linked: +`id` (the first object of the art); an object already linked to the style with its look changes nothing. +`graphicStyle.redefine {name, from}` gives the style `name` the look of the style `from` instead (fills, strokes, +effects, opacity, blend mode, isolate and knockout): `name` keeps its name, place and id, its objects still linked +follow in one undo step, and `from` and its objects stay as they are. `from` naming the same style, or a style with +the same look, records nothing; a `from` that names no style or is not a string, or `from` with `id`, is an error. A +style dragged onto another in the Graphic Styles panel with Alt held runs it with the dragged style as `from`; +without Alt the style moves (`graphicStyle.move`). The art of a column or marker design in a graph series is never +linked: `graphicStyle.new` can make a style from it, and `graphicStyle.redefine` leaves its look as it was and unlinks it, whether it is the source or a linked object. `graphicStyle.list` returns each style with the ids linked to it and the style of the first selected object; `select.same.graphicStyle` selects an object's fellow users. @@ -4756,14 +4831,17 @@ unique) and leaves the art as it is: the 3D and Materials panel's Add as Single `name` that is not a string or is empty, or any other key, is refused. `threeD.mapGraphic {symbol, face?, x?, y?, scale?, rotation?, index?, item?, ids?|id?}` adds a graphic to the 3D -effect of each selected object, in one undo step: `face` is `front` (default) or `back`, `x` and `y` are the +effect of each selected object, in one undo step: `face` is `front` (default), `back` or `side`, `x` and `y` are the offset in points of the graphic's center from the center of the object's bounds in the face's plane, `scale` is a percentage of the symbol's size (1..10000; omitted, 100 or less so the graphic fits inside the object) and `rotation` is in degrees counterclockwise (-360..360). Without `index` each object's first 3D effect takes it, and `item` is refused. -Every object's 3D effect must be Extrude & Bevel with Cap on (front only at a depth of 0), Rotate (the Plane type, -front only), Revolve (front only: its swept side) or Inflate (back only with Both sides and Cap on), and `symbol` must name a document symbol; otherwise the command is refused and nothing changes. It returns `{ids, graphic}`. -On Revolve, `x` and `y` are measured on the side unrolled flat from its middle, and a graphic that does not fit -starts scaled to fit the half of the side seen from the front ([three-d.md](three-d.md#graphics)). +Every object's 3D effect must be Extrude & Bevel (front only at a depth of 0; `front` and `back` need Cap on, and +`side`, its walls and bevels, does not), Rotate (the Plane type, front only), Revolve (front only: its swept +side) or Inflate (`front` or `back`, and `back` only with Both sides and Cap on), and `symbol` must name a document symbol; otherwise the command is refused and nothing changes. It returns `{ids, graphic}`. +On Revolve and on Extrude & Bevel's side, `x` and `y` are measured on the side unrolled flat from its middle (on +Extrude & Bevel, `x` along the outline, clockwise from its top, and `y` from the front toward the back), and a +graphic that does not fit starts scaled to fit the part of Extrude & Bevel's side unrolled about `x` = 0 that does +not reach its cut, or the half of Revolve's side seen from the front ([three-d.md](three-d.md#graphics)). On Inflate, `x` and `y` are measured in the art's plane, and the graphic is carried straight out onto the puffed face, Twist and Taper turning and shrinking the back's with it. @@ -4771,7 +4849,9 @@ The graphics are the `graphics` parameter of `threeD.extrude`, `threeD.rotate`, edits: an array of up to 64 `{symbol, face, x, y, scale, rotation}` objects, drawn on the face turned, foreshortened and shaded with it and clipped to it ([Map artworks on 3D object](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/map-artwork-on-3d-objects.html)). Revolve takes graphics on its swept side and shades them with the object's light ([the archived reference, page 185](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=185)); -how a graphic wraps around the side, and how one follows Inflate's puff, are VectorCraft's own rules. +how a graphic wraps around the side, and how one follows Inflate's puff, are VectorCraft's own rules. Extrude & +Bevel takes graphics on its side, its walls and bevels unrolled as one surface; how they are unrolled is +VectorCraft's own rule. A graphic naming a symbol the document does not have is refused, unless the effect already holds a graphic of it. The drawing rules are VectorCraft's own; see [three-d.md](three-d.md#graphics). @@ -6692,6 +6772,22 @@ and Shift steps follow the box the same way; a Reflect axis drawn with the tool {"name":"run_command","arguments":{"command":"object.reflect","params":{"axis":"vertical","basis":"page"}}} ``` +## Shear along an angled axis + +`object.shear` takes `axis` as `"horizontal"`, `"vertical"` or a number of degrees from -359 to 359. A number is a +line on the page at that angle, counter-clockwise from horizontal, as `object.reflect`'s numeric `axis` is, and the art +slides along that line about `origin` by the shear `angle`, which stays a separate value. 0 shears as `"horizontal"` +and 90 as `"vertical"`. A numeric `axis` outside the range, a number given as a string, or any other value is an +error, and nothing changes. The shear `angle` runs from -359 to 359 along every axis and is sheared by its tangent; +±90 and ±270 are an error. The Shear dialog's Axis has Horizontal, Vertical and Angle; the Axis Angle field beside it +starts at 0° and takes input while Angle is chosen. The [help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/shear-objects.html) +describes the Angle axis as a custom slant direction between -359° and 359°, measured from the horizontal. The +counter-clockwise direction on the page and the 0° starting value are VectorCraft's own. + +```json +{"name":"run_command","arguments":{"command":"object.shear","params":{"angle":30,"axis":45}}} +``` + ## Free Distort on a turned bounding box `object.distort` maps the corners of `from` (TL, TR, BR, BL) onto `corners`, which are page coordinates. With @@ -6832,8 +6928,11 @@ polygon (Polygon Properties): `sides` (3–1000), `polygonAngle` (degrees counte at 0), `polygonRadius` (pt, centre to vertex), `sideLength` (pt, which sets the radius) and `makeSidesEqual: true`, which drops an uneven scale or shear (its sides then differ) and keeps its centre, angle and mean radius; a radius or length that isn't a number above 0 is an error. An ellipse (Ellipse Properties): `pieStart` and `pieEnd` (degrees -counterclockwise from 3 o'clock; 0 to 360 is the whole ellipse) and `invertPie: true`, which swaps them. A line drawn -with the Line Segment tool (Line Properties): `lineLength` (pt, above 0; the line's first end stays in place) and +counterclockwise from 3 o'clock; 0 to 360 is the whole ellipse) and `invertPie: true`, which swaps them. +`constrainPie: true` with one of `pieStart` and `pieEnd` (the panels' Constrain Pie Angle link) moves the other angle +by as much, so each selected ellipse keeps its own span, counterclockwise from its start to its end; a whole ellipse +stays whole. `constrainPie: true` with both angles, with neither, or with `invertPie: true` is a parameter error. A +line drawn with the Line Segment tool (Line Properties): `lineLength` (pt, above 0; the line's first end stays in place) and `lineAngle` (degrees counterclockwise from 3 o'clock, from the first end to the second; the line turns about its midpoint; any finite value is brought into 0 to 360). With both, the length applies first. A line whose ends meet reads 0° and keeps its place under `lineAngle`; `lineLength` points it to the right. A length that isn't a number above 0, @@ -6850,6 +6949,7 @@ below 3 or above 1000 counts as 3 or 1000, and a fractional or negative `sides` ```json {"name":"run_command","arguments":{"command":"object.setLiveShape","params":{"sides":8,"polygonAngle":22.5,"sideLength":40}}} {"name":"run_command","arguments":{"command":"object.setLiveShape","params":{"makeSidesEqual":true}}} +{"name":"run_command","arguments":{"command":"object.setLiveShape","params":{"pieStart":350,"constrainPie":true}}} {"name":"run_command","arguments":{"command":"object.setLiveShape","params":{"lineLength":72,"lineAngle":90}}} ``` @@ -7198,8 +7298,13 @@ wide. `object.align` needs `horizontal` or `vertical`. The three Align commands, `object.reflect` and `object.shear` return an error that lists the choices of a `horizontal`, `vertical`, `to`, `axis` or `bounds` param given another value -(`object.reflect` also takes an angle and names the value given), and one for a `spacing` that is not a number; nothing -moves. +(`object.reflect` and `object.shear` also take a numeric `axis` and name the value given; `object.shear`'s numeric +`axis` runs from -359 to 359), and one for a `spacing` that is not a number; nothing moves. `object.shear` takes an `angle` from -359 to 359 degrees, the range of the +[Shear dialog](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/shear-objects.html), +and shears by its tangent, so 120 slants as -60. An angle of 0 or ±180 (within 1e-9 degrees) has no slant: without +`copy`, nothing moves and no undo step is recorded, and with `copy` the copies keep the art's place. It returns an error for an angle outside that range, and, as +VectorCraft's own rule, for ±90 and ±270 (within 1e-9 degrees), which have no finite shear; nothing moves and no undo +step is recorded. ## Glyph bounds for type @@ -7258,6 +7363,22 @@ The Selection & Anchor Display and General preferences apply to `pointer_gesture - `showHandlesMultipleAnchors` (on by default): off, Direct Selection (and the Anchor Point tool, and the Pen with Alt) shows and drags direction handles only while a single anchor is selected. On, the handles of the direct-selected anchors, or of every anchor of a path selected as a whole, show and drag. `handleStyle` (`solid`, `hollow`, `large`) draws their ends (desktop app). +- `interpolateControlPoints` (General › Interpolate Control Points When Moving Anchors, off by default): the default of + the `interpolate` param of `path.moveAnchors` (a Direct Selection drag), `object.nudge` (the arrow keys), + `object.move`, `object.transform` and `object.transformAgain`. It applies when they move direct-selected anchors + without turning or scaling them. `object.setBounds` (only `x` or `y` changed) and `guide.move` (with art selected + too) take the same param and follow the preference when they move direct-selected anchors. + On, both handles of each segment with one moved end are re-mapped by the turn, uniform scale and move that take the + segment's old ends to its new ends, so a segment between two corner anchors keeps its shape relative to its ends. A + segment with both ends moved, or with its ends at the same place before or after the move, moves as it does with the + preference off. A smooth anchor keeps its handles in line: its re-mapped handle takes the new length and stays in + line with the other handle, and when both of its handles were re-mapped they point along the mean of their + directions. When the two point the same way, both move with the anchor as with the preference off. A retracted + handle stays retracted. The value used joins the command's journal entry and Transform Again's options; a saved step + without `interpolate` (an action or journal entry recorded before it) moves the handles as with the preference off, + as it did when it was recorded. Align and + Distribute, and the anchors of type paths and area type frames (`text.reshapePath`, `text.reshapeArea`), move as + before. Off, the handles of a moved anchor move with it and the other handles stay where they are. - `hideCornerWidgetAbove` (177° by default): corners wider than this show no Live Corners widget (a rectangle's right angles hide below 90°). - `transformPatternTiles` (off by default): the default of the transforms' `patterns` param (`object.transform`, @@ -7323,13 +7444,20 @@ output's `_ICC_PROFILE` property when colord has no usable profile, then the scr Color on (HDR or Automatic Color Management) and macOS windows are converted by the system, and nothing is converted again. In a Wayland session, and where no profile is set or the profile is not an RGB display profile of at most 1 MiB, the canvas stays sRGB. The app reads the display again every 10 seconds and when the window moves to another display. +Edit › Refresh Monitor Profile (`view.refreshMonitorProfile`, `{}`; a desktop UI command) reads it again on the next +frame without waiting for either interval, for example after a new profile is installed for the display; a request +made while a reading runs starts when that reading ends. It returns `{requested: true}` before the profile is read, +and is an error while `monitorProfileDisplay` is off (nothing is queued) and where nothing reads the display's profile +(the web build). It changes no document, proof setting or preference and records no undo step; reading the same +profile again leaves the canvas as it is. Exports, `ui.render`, the document, panels and thumbnails are not converted; with Proof Colors on, the proof is drawn first and then converted. Translucent art and the antialiased edges of art over an artboard's paper or the transparency grid are blended with it in sRGB, and the blend is converted; over the pasteboard and in Outline the art is converted on its own. `ui.inspect` returns `displayProfile`: `{enabled, display, source, profile, from, applied, reason, -osManaged}`, where `source` is `profile`, `srgbProfile` (a profile that shows sRGB unchanged), `system`, `none`, -`pending` or `unsupported`, `applied` says whether the canvas is converted, and `reason` says why not. +osManaged, readRequested}`, where `source` is `profile`, `srgbProfile` (a profile that shows sRGB unchanged), `system`, `none`, +`pending` or `unsupported`, `applied` says whether the canvas is converted, `reason` says why not, and `readRequested` +says whether a reading Refresh Monitor Profile asked for has not started yet. `lowLatencyDrawing` (Preferences › Performance › Low-Latency Drawing, off by default; desktop app) is read when the app starts. On, the window presents without vsync (wgpu's `AutoNoVsync`) and frames start at most 240 times a second. @@ -7908,6 +8036,12 @@ A built-in preset names its category's profile in `file.newPresets` (`profile`). profile of the preset they were made from. `file.new {profile: "Print"}` picks a profile for any settings, and `profile: null` starts with the defaults. A document made without a preset starts with the defaults. +A profile also sets the default font of its documents: new type starts in [Normal Character Style], so when the profile +redefines that style (`charStyle.setAttrs {name: "[Normal Character Style]", attrs: {font_family, font_style, size}}` in +the document `file.newProfiles.edit` opens, then save), type made in the profile's documents takes its font, style, size +and fill. A `font`, `style`, `size` or `color` given to `text.create` still wins +([Change the default font](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/change-the-default-font-in-illustrator.html)). + The profiles are `.vectorcraft` files named after their category in the `New Document Profiles` folder next to the preferences (VectorCraft's own place and form). A category without a file has the shipped profile, which holds the defaults. Runs without preferences (`VECTORCRAFT_NO_PREFS`) and the web build have no folder, so every document starts @@ -9438,7 +9572,7 @@ File → Export → Save for Web (Legacy) writes optimised web images: `document …}` renders the artboard (`clipToArtboard`, the default; `artboard` picks one) or the visible art and the slices, at `width`, `height` or `percent`, and encodes it with the format's settings: for GIF and PNG-8 `reduction`, `colors`, `dither`, `ditherAmount`, `transparency`, `matte`, `interlaced`, `webSnap`, `lossy` (GIF) and `colorTable {locked, -transparent, webShift, sort}`; for JPEG `quality`, `progressive`, `optimized`, `embedProfile` and `matte`; for PNG-24 +transparent, webShift, sort, deleted, customPalette}`; for JPEG `quality`, `progressive`, `optimized`, `embedProfile` and `matte`; for PNG-24 `transparency`, `matte` and `interlaced`. `metadata` (none, copyright, contact, all) writes File Info as PNG text or a GIF/JPEG comment; `convertToSrgb` marks PNGs as sRGB. `` is the name of `path` without its extension, or without `path` the document's title with the characters Windows does not allow in a file name as `-` and a `-` after @@ -9455,6 +9589,25 @@ file size), `seconds` to download at `kbps` (default 56.6), the size, and for pa `source` (the colour the reduction made), so a colour keeps its edits when it is web-shifted or snapped. `slice: n` previews one slice; `image: true` adds the file; `warnings` holds the export's warnings. +Delete Color is `colorTable.deleted: ["#rrggbb"…]`, by `source`. The deleted colors leave the table and the file, and +their pixels take the nearest color left, with the current reduction's color distance and dither; the preview and the +file agree. A deleted color also leaves `locked`, `transparent` and `webShift`. A color the table does not hold is +ignored. Deleting every opaque color is an error, and the settings, preview and files do not change; the transparent +entry of transparent pixels cannot be deleted. `colorTable.customPalette: ["#rrggbb"…]` is a fixed palette (a Custom +table) used instead of the reduction's own, at most `colors` entries with the transparent one included, so a color it +lacks is not made again; the dialog's Delete Color sets it to the table's colors on the first deletion. Both lists hold +at most 256 colors, and `#rrggbbaa` is refused. A `reduction` change without `colorTable` in the same params clears +both lists. JPEG and PNG-24 have no color table and do not read them. Presets and `webExport.settings` keep them. In +the dialog a click selects one color, Shift-click selects the colors between it and the last one clicked, and +Ctrl-click (Command-click on macOS) adds or removes one (`__colors` holds the selection, `__color` the last one +clicked). The trash button and Delete Color in the table's menu delete the selection in one edit, Restore Generated +Table in that menu clears `deleted` and `customPalette`, and the table reads Custom while either is set. Choosing +another reduction in the dialog also clears them. + +```json +{"name":"run_command","arguments":{"command":"document.exportForWeb.preview","params":{"format":"png8","colorTable":{"deleted":["#ff0000"],"customPalette":["#0000ff","#00ff00","#ff0000"]}}}} +``` + Optimize to File Size (the dialog's button under Preset) is `webExport.optimizeToFileSize {desiredK, startWith?, use?, slice?, …settings}`. It searches for settings whose files fit in `desiredK` K (1 K is 1024 bytes; above 0, at most 1048576) and returns them without writing a file or changing the remembered settings: `{targetBytes, achieved, @@ -10245,7 +10398,7 @@ thread. When `effect.expandAppearance` keeps a frame as type in a group (type wi effects are shadows, outer glows or Crop Marks), the type stays in the thread in the frame's place. Object › Expand (`object.expand`) outlines type with these two commands. `object.flattenTransparency` takes each frame of threaded text that it outlines (`textToOutlines`) or turns into flat regions or an image out of its thread in the same way. -`symbol.new` (New Symbol) and `symbol.update` (Redefine Symbol) take each frame of threaded text in the selection out +`symbol.new` (New Symbol) and `symbol.update` (Redefine Symbol), without `keepArt: true`, take each frame of threaded text in the selection out of its thread in the same way, and the symbol's art holds a copy of the frame with the text it shows. When every frame of a thread goes into the symbol, the copy of the last frame keeps the text it has no room for. @@ -11780,6 +11933,10 @@ no file, and an import opens no document). A filter whose manifest asks for a he `plugin.inspect {path | dataBase64}` entry) needs a person's approval, and `plugin.install` refuses `allowHeavy: true` from a request. `plugin.run` runs it where it is called, so the call may take minutes; `notifications/cancelled` stops it. +The preference `pluginInstructionBudget` (`normal`, the default, or `large`; `prefs.set` refuses any other value) +sets the instructions every object filter run gets: Large gives a light filter 250 M instructions instead of 50 M, +plus 4,000 per input byte either way, with its 60 s time budget unchanged; a heavy filter keeps its own budget with +either value. The next `plugin.run` or plug-in command uses the value set ([plug-ins](plugins.md#instruction-budget-preference)). A plug-in whose manifest lists permissions (`permissions` in its `plugin.inspect` entry, with `needsApproval: true`) needs a person's approval too, and `plugin.install` refuses `grant: [permission]` from a request. With a desktop app connected, `ui.installPlugin` opens the approval dialog and returns `{pending: "pluginInstall"}`; `answer_dialog`, @@ -11872,6 +12029,7 @@ Disable and Continue can't save the plug-in it turns off, this launch skips it a {"name":"run_command","arguments":{"command":"plugin.setEnabled","params":{"id":"org.example.wobble","enabled":true}}} {"name":"run_command","arguments":{"command":"plugin.install","params":{"path":"/plugins/desaturate.wasm"}}} {"name":"run_command","arguments":{"command":"plugin.run","params":{"id":"org.vectorcraft.example.desaturate","params":{"amount":60}}}} +{"name":"run_command","arguments":{"command":"prefs.set","params":{"key":"pluginInstructionBudget","value":"large"}}} {"name":"run_command","arguments":{"command":"effect.apply","params":{"effect":"plugin.org.example.wobble","params":{"size":4}}}} {"name":"run_command","arguments":{"command":"document.open","params":{"path":"/tmp/plot.hpgl","importer":"plugin.org.example.hpgl"}}} {"name":"run_command","arguments":{"command":"plugin.org.example.tidy.grow","params":{"by":3}}} @@ -13107,6 +13265,18 @@ Commands: drawn, and the path's fills stay on it, below its dashes (a path without fills goes). A compound path's dashes are plain paths with its appearance. Paths without a dashed stroke stay as they are, and it is an error if none has one. The dashes are selected; more than 100,000 (or a pattern too fine to draw) is refused. → `{ids, dashes}`. +- `addon.pathtools.bridge {radius?, keepOriginals?, ids?}` joins two circles (`ids`, default: the selection; paths + whose outline is a circle, not hidden or locked) into one closed outline, as one undo step (Object › Plug-ins › Path + Precision Tools › Smooth Bridge…). The outline goes around each circle on its side away from the other and along two + concave arcs, one on each side of the line through the centers, each touching both circles from outside, so every + anchor is smooth. `radius` is the arcs' radius as a percentage of the smaller circle's radius (1 to 1,000, 100 by + default): a larger radius makes a wider, gentler bridge. Overlapping and touching circles are joined at every radius. + One circle inside the other is an error, and so are circles too far apart for the radius: the arcs would not reach + both circles, or would cross before they do. The error suggests a larger radius only when one up to 1,000 would + bridge the circles. The outline replaces the two circles, painted as the upper one (a plain + path), unless `keepOriginals` is true: then it goes directly above the upper circle, painted as it, and the circles + stay. The outline is selected. → `{id}`. Smooth Bridge… opens a dialog (`ui.menuDialog {command}`, kind + `smoothBridge`) with a Radius field in percent, Keep Originals and Preview. - `addon.pathtools.tangentCircle {ids?, radius?, circle?}` draws the circles that touch two paths or compound paths and have `radius` (0.01 to 1,000,000 pt, needed with two), or that touch three (which set the radius themselves, so `radius` is then an error), as one undo step (Object › Plug-ins › Path Precision Tools › Tangent Circle…). `ids` diff --git a/docs/plugins.md b/docs/plugins.md index 2702e4fe7b..344e3b7c00 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -126,7 +126,7 @@ defaults): | Module size | 32 MiB | rejected | | Linear memory | 512 MiB per instance (input and parameters: at most half) | `memory.grow` returns -1; oversized input or initial memory fails | | Output | 64 MiB of JSON | `Limit("output size")` | -| Instructions (fuel) | 50 M per call + 4,000 per input byte for `vc_run`; a [heavy filter](#heavy-filters) 1 G + 4,000 per byte; an export or import 10 G + 4,000 per byte | `Limit("instruction budget")` | +| Instructions (fuel) | 50 M per call + 4,000 per input byte for `vc_run`; an object filter with the [Large instruction budget](#instruction-budget-preference) 250 M + 4,000 per byte; a [heavy filter](#heavy-filters) 1 G + 4,000 per byte; an export or import 10 G + 4,000 per byte | `Limit("instruction budget")` | | Wall clock | 60 s per filter run, 5 s per live-effect run, 300 s per heavy filter run, export or import (checked every 20 M instructions; the web build reads the page's `performance.now()`) | `Limit("time budget")` | | Import input | 128 MiB of the file (`vectorcraft_plugins::import::MAX_INPUT_BYTES`) | the file doesn't open; a larger file named by `path` is not read past that | | Call depth | 1,024 frames | trap | @@ -136,6 +136,22 @@ An export runs where the export runs: with Background Export on, on the export's plug-in between two of those 20 M-instruction slices; nothing is written then. An import stops the same way when the open it runs in is cancelled, and nothing opens then. +### Instruction budget preference + +Preferences › Plug-ins & Scratch Disks › Plug-in Instruction Budget (`pluginInstructionBudget`, VectorCraft's own +setting) sets the instructions each object filter run gets, from the app, `plugin.run`, a plug-in's commands, scripts +and MCP alike: + +- **Normal** (`normal`, the default): the limits in the table above, 50 M + 4,000 per input byte. +- **Large** (`large`): 250 M + 4,000 per input byte (`vectorcraft_plugins::LARGE_FUEL`, 5 times Normal). The 60 s time + budget, the memory, output and call depth limits stay as they are. + +A [heavy filter](#heavy-filters) keeps its 1 G and 300 s with either choice. Live effects, exporters and importers keep +their own budgets. A change applies to the next run of every installed filter, without installing it again. Cancel and +the time budget stop a run between two 20 M-instruction slices with either choice. `prefs.set {key: +"pluginInstructionBudget", value}` takes `normal` or `large` (or the labels Normal and Large) and refuses any other +value; a saved preferences file with another value reads as Normal. + ### Live effects while a document opens While the app draws a document on screen, the live-effect runs of its first view share a 2,000 ms budget diff --git a/docs/roadmap.md b/docs/roadmap.md index 3c09bde829..2e9fe39fe9 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-17 · **Change:** minor (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: #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-18 · **Change:** minor (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: #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). > @@ -59,6 +59,7 @@ M7 type: Touch Type moves a right-to-left character along its line and up from i | Date | Change | Summary | |---|---|---| +| 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 | 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 | PDF import: glyphs inside a marked-content span with an empty `ActualText` come in as outlines in their fill and stroke instead of being left out, adding no text (#6971; `empty_actual_text_keeps_the_glyphs_art` in `crates/pdf/src/tests/actual_text.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. | @@ -173,7 +174,7 @@ Gujarati interface follow-up (2026-11-14): the catalog and zero/one plural rule | 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, 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); 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) | 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) | 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 | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 056c9f9df7..749dce93d3 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-17 · **Change:** minor (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: #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-18 · **Change:** minor (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: #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). > @@ -63,6 +63,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | Date | Change | Summary | |---|---|---| +| 2026-11-18 | minor | Hardening: PDF export writes the document language (Document Setup) as the catalog's `/Lang` and XMP `dc:language` (#3644). Scores and estimates unchanged. | | 2026-11-17 | minor | Distort & Transform › Twist: handles follow the rotation's derivative, so a strongly twisted path is a smooth spiral instead of pieces meeting at kinks (#7069; `twist_joins_its_pieces_smoothly` in `crates/effects/src/tests.rs`). Scores and estimates unchanged. | | 2026-11-17 | minor | PDF import (#8300): a glyph filled only (text rendering mode 0) right after one filled and stroked (mode 2) joined the stroked run and came in stroked too: `2 Tr (B) Tj 0 Tr (C) Tj` came in as `BC` stroked throughout. A glyph filled only now joins only a run drawn alike, so it starts a run of its own, filled only, in the same type object, and takes a stroke only when the file draws one over it (the #8015 matching); a word filled whole then stroked whole, and fill and stroke rendering glyph by glyph, still come in as one run filled and stroked. Tests: `a_glyph_filled_only_after_one_filled_and_stroked_is_not_stroked`, `glyphs_filled_and_stroked_one_by_one_stay_one_run`; scores and estimates unchanged. | | 2026-11-17 | minor | PDF import (#8015 follow-up): type filled and stroked at less than full opacity is no longer joined into one type object, since the file composites the fill and the stroke apiece, darker where they overlap, while one object's opacity applies to both together; it stays a filled object and a stroked one, as a fill and stroke at different opacities already did. An upright glyph (vertical type) filled and stroked is no longer kept as an outline for a line that comes in as its outlines, as glyphs filled only weren't, so such a line can't lose them. The #8015 entries now say what is left: translucent type filled and stroked, and a `TJ` whose kerning starts a new line part way through, still come in as two objects. Tests: `translucent_fill_and_stroke_text_stays_two_objects`, `a_vertical_line_with_one_glyph_filled_and_stroked_keeps_every_glyph_filled`; scores and estimates unchanged. | @@ -549,7 +550,7 @@ about 1–1.5 agent-hours each, so the other rows (estimated on the older scale) | Libraries, Links, Package | 2 | 82% | the Libraries panel is local only (no cloud by design: libraries are files on this machine) and has no shared libraries, linked graphics or gradients and patterns as items yet; its graphics, colours and text styles (#745), its search, groups and library export/import as `.vclibrary` files (#926), a list that scrolls, with items and groups reordered by dragging and items dragged into and out of groups, art and swatches dragged in added where they are dropped, and items shown as icons or in a list with their names, are done; Links and Package are done; placed VectorCraft documents are done (linked by default, vectors in every output, previews, Break Link, Expand, Edit Original, refresh on save) | 2–3 | | **Feature parity** | **103** | **~75%** | | **~210–330** | | Interaction-fidelity pass (side by side with Illustrator: every tool modifier, cursor, dialog, Properties context) | | | | 60–90 | -| Hardening (big-file corpus, fuzzing, cross-platform and browser QA, accessibility, packaging) | | | Bounded control socket waits (#1726); PngSuite pinned-file integrity and download budgets verified (#1729); RPM runtime capabilities and glibc floor checked (#1275); titled PDF exports ask viewers to display the document title (#3646); real-distro installation/start-up QA pending | 50–80 | +| Hardening (big-file corpus, fuzzing, cross-platform and browser QA, accessibility, packaging) | | | Bounded control socket waits (#1726); PngSuite pinned-file integrity and download budgets verified (#1729); RPM runtime capabilities and glibc floor checked (#1275); titled PDF exports ask viewers to display the document title (#3646); PDF exports give the document language as the catalog's `/Lang` (#3644); real-distro installation/start-up QA pending | 50–80 | | **Full parity** | | **~56%** | | **~320–500** | _Inventories (2026-10-07):_ 13 menu items still stubbed (`todo(…)` in `crates/ui-egui/src/menus.rs`); every tool @@ -636,6 +637,7 @@ since 2026-10-01. **Drawing tools, Dimension tool second point without construction guides through a first point off the anchors:** By VectorCraft's own rule, with Smart Guides on, the second Linear point does not snap to the construction guides through a first point that is not on an anchor, so a click beside a segment straight below such a first point lands on the segment; after a first point picked on an anchor, the construction guides through it still apply. The second point still snaps to anchors, centers and alignment lines, and with Snap to Perpendicular or Snap to Tangent on, it lands where the line from the first point meets a segment square or grazes a curve. `a_point_on_a_guide_stays_on_the_guide`, `the_second_point_after_an_anchor_lands_on_construction_guides`, `the_second_point_lands_square_to_a_segment_or_grazing_a_curve` and `linear_picks_show_and_snap_to_smart_guides` cover it. **Drawing tools, Dimension tool points land on dimensions already drawn (#8063):** By VectorCraft's own rule, with Smart Guides or Snap to Point on, a Linear point that no anchor of the art within 8 pixels takes lands on the end of a visible, unlocked dimension's dimension line, or on the far end of its extension line, within 8 pixels, and a point that nothing else places lands on the closest point of such a line within 8 pixels, so at any zoom a dimension can start where another one ends. The end of an extension line next to the point it measures does not pull points away from that anchor. With Smart Guides and Anchor/Path Labels on, a point on an anchor or line end shows the "anchor" label and a point on a segment or line shows the "path" label. `linear_picks_land_on_anchors_paths_and_drawn_dimensions` and `an_anchor_beside_a_drawn_dimension_takes_the_point` cover it. **Drawing tools, Dimension tool dimensions selected with their art keep their lines and label:** Object › Expand, Object › Expand Appearance and Object › Path › Outline Stroke leave a dimension selected with art it measures, directly or in selected groups without fills, strokes or effects of their own, as it is and change only the other art; when the new art no longer fits its link, the dimension stays where it was, no longer linked, and undo links it again. `expand_leaves_a_dimension_selected_with_its_art_as_it_is`, `expand_appearance_leaves_a_dimension_selected_with_its_art_as_it_is`, `outline_stroke_leaves_a_dimension_selected_with_its_art_as_it_is`, `a_dimension_selected_with_art_that_has_nothing_to_expand_changes_nothing`, `a_group_effect_expanded_reaches_the_dimension_it_holds`, `expand_keeps_a_dimension_in_its_asset_and_its_variable_binding`, `a_dimension_keeps_no_link_to_the_art_expand_replaced`, `a_dimension_outlasts_the_art_outline_stroke_or_expand_appearance_replaced`, `a_dimension_outlasts_the_stroke_expand_outlined` and `expand_appearance_in_safe_mode_leaves_a_dimension_selected_with_its_art` cover it. +**Drawing tools, Dimension tool Arrow Style shows each arrowhead (#8049):** The Arrow Style dropdown in Dimension Tool Options and in the Properties panel's Dimension section draws each style's arrowhead at the end of a short line before its name, in the open list and in the closed field, using the Stroke panel's arrowhead previews. Filled, Open, Tick and None are the same four styles, saved as before. `arrow_style_shows_a_drawn_arrowhead` and `each_arrow_style_draws_its_stroke_arrowhead_at_both_ends` cover it. **Drawing tools, Line Segment from one curve onto a common tangent of another:** By VectorCraft's own rule, with Smart Guides and Snap to Tangent on, a Line Segment drag pressed anywhere on a convex closed path with curves and dragged to within the snapping tolerance of another such path lands on a common tangent of the two ([tangent lines to circles](https://en.wikipedia.org/wiki/Tangent_lines_to_circles)): both ends move to where the line touches the paths, the start sliding along the first path, and each end shows the "tangent" label when Anchor/Path Labels is on, with the line drawn as a guide when Alignment Guides is on. The line is the tangent whose touch point on the second path is nearest the pointer, so moving the pointer around the second path switches between the outer tangent and the one crossing between the paths. The start stays where it was pressed when Shift, Alt or Space is held, when an anchor, center or crossing lies nearer the pointer than the second path does, when the press snapped to an anchor, center or crossing off the first path, when Snap to Tangent is off, when Snap to Grid or pixel snapping places drawn points, or when either path bends inward somewhere or has more than 512 segments. `a_line_from_one_circle_to_another_lands_on_their_common_tangent`, `a_line_from_a_turned_ellipse_lands_on_its_tangent_with_a_circle`, `a_line_near_the_second_path_takes_the_tangent_touching_it_nearest`, `a_line_keeps_its_start_without_a_tangent_snap`, `a_line_to_a_crescent_or_from_an_anchor_beside_the_curve_keeps_its_start` and `a_line_segment_drag_draws_the_common_tangent_as_one_undo_step` cover it. **Live trace result bounds and selection highlights exclude the retained bitmap except in source-image views:** `live_trace_result_bounds_exclude_the_retained_bitmap_at_any_angle` checks every TraceView, geometric and visual bounds and rotated result bounds. `live_trace_selection_highlight_excludes_the_retained_source_rectangle` checks result highlights and the existing ordinary-group policy. Shared editing-child traversal also preserves Shaper handling. **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:** Shared existing preset definitions are reused; no external preset assets are added. Presets preserve each selected artboard's orientation, and orientation choices apply even when the active board already matches. Fit operations draft bounds until OK, affect only the active artboard and leave artwork in place. Regression coverage checks draft/Cancel, selected-set application, active-only fitting and Undo. @@ -828,6 +830,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Document Setup › Color:** a Color tab shows the document color mode (RGB Color or CMYK Color), a Convert to CMYK or Convert to RGB box for a mode change (cleared: the colors keep their numbers), and the RGB and CMYK profiles assigned to the document, with a working-space entry for none. OK runs `edit.assignProfile` and then `file.documentColorMode` with the dialog's other changes in one `command.batch`, and the document's changes are one undo step. An unchanged Color tab adds no color commands, and Cancel, or OK with nothing changed, records no undo step. A Color tab field with a value of the wrong kind is an error, and the dialog stays open. The tab is VectorCraft's own layout; File › Document Color Mode and Edit › Assign Profile… stay as they are. Tests in `dialogs/document_setup.rs`. - **Assign Profile's three choices:** the Assign rows of Edit › Assign Profile… (the Separations panel's Color Settings section) offer Don't Color Manage This Document, the working space of the document's color mode (Working RGB or Working CMYK, with its name) and Profile with the other profiles of that kind, as [Assign or remove a color profile](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=150) lists them. They act on the profile of the document's color mode: an RGB document's RGB profile, a CMYK document's CMYK profile; the other model's profile stays as it is (VectorCraft's own rule; Document Setup › Color sets both). Picking the working space assigns its profile, which stays when the working space changes later. A choice the document already has runs nothing. Tests in `panels/separations.rs`. - **Canvas through the display's profile on Windows and X11:** Preferences › Performance › Use Monitor Profile for Canvas (on by default) converts the canvas's art, artboard paper and transparency grid from sRGB into the ICC profile of the display that shows most of the main window, after any proof, as the help page describes the monitor's profile translating the document's colors for the monitor ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=151)). Windows gives the display's default profile, and a display with Advanced Color on is left to Windows ([Microsoft Learn](https://learn.microsoft.com/en-us/windows/win32/wcs/advanced-color-icc-profiles)); X11 gives colord's profile for the output or the `_ICC_PROFILE` property. macOS converts the window itself, and a Wayland session stays sRGB. `ui.inspect` reports `displayProfile`. Tests in `color/src/cms/display.rs`, `ui-egui/src/display_profile.rs` and `canvas::tests::the_canvas_is_drawn_through_the_display_profile_while_the_preference_is_on`. +- **Refresh Monitor Profile:** Edit › Refresh Monitor Profile (`view.refreshMonitorProfile`), VectorCraft's own command, reads the display's profile again on the next frame instead of waiting up to 10 seconds, so a profile installed or changed while the app runs is used without a restart; a request made while a reading runs starts when it ends, and the command is off while Use Monitor Profile for Canvas is off. `ui.inspect`'s `displayProfile.readRequested` reports a request that hasn't started. Tests `display_profile::tests::a_requested_reading_starts_on_the_next_frame_past_both_intervals`, `a_request_made_while_a_reading_runs_waits_for_it_to_end`, `a_request_is_dropped_when_the_preference_goes_off` (desktop app) and `menus::tests::refresh_monitor_profile_asks_for_a_reading_of_the_display_profile`. - **Translucent art blended before the display profile:** with Use Monitor Profile for Canvas converting, translucent art and the anti-aliased edges of art over an artboard's paper, a colored artboard or the transparency grid are blended with it in sRGB and the blend is converted, so the monitor's profile translates the document's colors as they are composited ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=151)). The frame rendered whole, the part an edit renders again, the render worker's frame, the pan fill and the other windows' panes do the same; over the pasteboard and in Outline the art is converted on its own, and with no profile to convert into nothing changes. Tests `display_profile::tests::translucent_pixels_over_the_paper_are_blended_before_they_are_converted`, `the_transparency_grid_is_blended_cell_by_cell`, `the_backdrop_is_found_through_the_view` and `canvas::tests::translucent_art_over_the_paper_is_blended_before_the_display_profile`. - **Out-of-gamut warning after a profile change:** the out-of-gamut warning and its closest-color correction in the Color panel and Color Picker ([the help page](https://helpx.adobe.com/illustrator/using/adjusting-colors.html)) check the color against the document's assigned CMYK profile, else the working CMYK space, and update when Edit › Assign Profile… or Edit › Color Settings… changes that space or a loaded profile changes, without a change of color. Which CMYK space the warning uses is VectorCraft's own rule. Tests: `gamut_warning_follows_a_profile_change` and `gamut_warning_follows_a_profile_loaded_again` in `dialogs/color_picker/tests.rs`. - **Swatch Options and New Swatch color warnings:** both dialogs show the out-of-gamut triangle and the out-of-web-color cube under the color, each with its correction beside it, and a click on the icon or the correction shifts the color to the closest printable or web-safe color ([the archived user guide](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=236), Swatch options; [the help page](https://helpx.adobe.com/illustrator/using/adjusting-colors.html)). The icons in the Color panel and the Color Picker correct the color too. VectorCraft's own rules: the triangle shows in RGB, HSB and Lab and the cube in every mode but Web Safe RGB, both can show at once, a web correction of a Grayscale, Lab or CMYK color is edited in RGB, a gamut correction keeps the CMYK equivalent and is edited in CMYK, and a correction keeps the name, the color type and Global and changes the dialog's fields only, so OK records one undo step. Tests: `swatch_options_shows_and_corrects_both_warnings` and `swatch_warnings_follow_the_mode` in `dialogs/swatch_options.rs`, `a_warning_corrects_the_new_colour_only_until_ok` in `dialogs/new_swatch.rs`. @@ -914,6 +917,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Save for Web: Preview in Browser writes each preview's page and images to a folder of its own inside `VectorCraft Save for Web` in the system's temporary folder. A later preview, from the same app or another one running, does not overwrite an earlier one. Each preview first removes the preview folders there that are an hour old or older and, on Linux, macOS and FreeBSD, belong to the current user; it leaves other files and folders alone. The folders a preview makes there are open to their owner only on those systems. When `VectorCraft Save for Web` is a link or is not a folder, or on those systems belongs to another user or can be written by other users, the preview goes to a new folder of its own in the temporary folder, which a later preview removes once it is an hour old (`file.saveForWeb.browser`). - Save for Web: Optimize to File Size… opens rows for a desired file size in K, Start With (Current Settings, Auto Select GIF/JPEG) and, with slices, Use (Total of All Slices, Each Slice, Current Slice); OK takes the settings whose files fit and shows the size found, or says that no setting tried fits ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=395)). The search lowers JPEG quality or palette colors (GIF then lossy) and encodes at most 32 trial settings; Auto Select chooses GIF for transparent art or art of at most 256 colors and JPEG otherwise. The slices share one setting, so every Use choice changes all of them (`webExport.optimizeToFileSize`). Scores and estimates are unchanged. - Save for Web: while Alt (Option on macOS) is held, the dialog's Cancel button reads Reset, which puts the remembered settings back on the document's active artboard and leaves the dialog open (`ui.dialogReset`). + - Save for Web: the color table's trash button and Delete Color in its menu remove the selected GIF or PNG-8 colors, and their pixels take the nearest color left in the palette ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=404)). Click selects one color, Shift-click a range and Ctrl-click (Command-click on macOS) adds or removes one ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=398)). After the first deletion the table is a fixed Custom palette, so deleted colors stay out when the preview updates. These rules are VectorCraft's own: a deleted color is no longer locked, transparent or web-shifted; deleting every opaque color is refused; Restore Generated Table in the menu, or another reduction, goes back to the generated palette; presets and the remembered settings keep the edit (`colorTable.deleted`, `colorTable.customPalette`). Fixed palettes can also use all 256 entries when nothing is transparent. Scores and estimates are unchanged. - Export for Screens, Save for Web (slice images, and files named after the document's title) and the Libraries panel name files with the characters Windows does not allow written as `-` and with a `-` after a Windows device name such as `CON`, on every platform (`document.exportForScreens`, `document.exportForWeb`, `library.create`). - Variables (data merge): text, visibility and image variables bound to objects (an object may carry several), dataset rows applied in one undo step (`variable.*`, `dataset.*`) from a Variables panel and Window › Variables, with dialogs to define, bind and edit, Make Text/Visibility/Image Dynamic, Capture/Update Data Set, CSV import/export (`dataset.import` / `dataset.export`), and a row in italics when an edit leaves the art not matching it; an image dataset value is a file path and apply keeps the object's bounds; bindings let go of deleted art and locked art is left alone except by visibility values; every command, like the rest, is drivable over MCP and the CLI. - Export for Screens numbers distinct row files whose names collide, compared without case, as `-2`, `-3`… instead of leaving them out; identical rows still write one file. It puts row folders that differ only in case into one folder (`document.exportForScreens`). @@ -962,6 +966,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Clipboard flavors under `--automation-read-root`: `clipboard.flavours` leaves out the SVG, and its markup as text, that `clipboard.exportSvg` refuses. `crates/engine/src/tests/links.rs` (`confined_clipboard_flavours_leave_out_a_withheld_svg`). - Preserve Editing SVG under `--automation-read-root`: the native document an SVG or SVGZ carries leaves out an Export for Screens folder outside the read roots, and keeps the other export settings and the art; the open document keeps the folder, and a folder inside the roots is kept. `crates/engine/src/tests/links.rs` (`confined_preserve_editing_svg_leaves_out_an_export_folder_outside_the_read_roots`). - Native document output and linked images under `--automation-read-root`: the outputs that carry the native document (a native file or template, an EPS file, a `.ai` or `.ait` file of every artboard, a PDF of every artboard with Preserve Editing, also from `document.exportPdf`, the saves and Export for Screens rows) are refused, before any file or folder is written, with an error that names no file or folder, when that document names a linked image or placed file, a kept relative path or a data set's image outside the read roots, or holds a stored brush entry that does not read as a brush; files without the native document are written. Those documents, and the documents Package writes or rewrites, leave out an Export for Screens folder outside the read roots, and Package refuses a linked file it copies as it is whose native document keeps one; the open document keeps its links, data sets and folder. An Export for Screens row that writes one artboard is checked against that artboard's art, and each asset, layer or selected object writes its own native, `.ai` or EPS file. `crates/engine/src/tests/links.rs` (`confined_native_output_refuses_a_linked_image_file_outside_the_read_roots`, `confined_native_output_refuses_a_data_set_image_outside_the_read_roots`, `confined_native_output_leaves_out_an_export_folder_outside_the_read_roots`, `confined_screens_rows_check_the_artboard_each_file_holds`), `crates/engine/src/tests/package.rs` (`a_confined_package_refuses_a_linked_file_that_keeps_an_export_folder_outside_the_read_root`), `crates/engine/src/cmd/fileio/tests_screens.rs` (`each_piece_writes_its_own_native_document`). + - Exporter plug-ins and Package's unreadable linked files under `--automation-read-root`: an exporter plug-in's format, whose plug-in is given the native document's JSON, is refused before the plug-in runs when that document links a JavaScript file, a linked image or placed file or a data set's image outside the read roots, and the JSON leaves out an Export for Screens folder outside them; Package refuses, before anything is written, a linked native document, PDF, `.ai` or EPS file whose native document can't be read to check it (a PDF that needs a password to open, damaged editing data), and copies a PDF or EPS file without editing data. Errors name no file or folder, and the person at the keyboard exports and packages as before. `crates/engine/tests/plugin_export.rs` (`a_confined_exporter_is_refused_stored_paths_outside_the_read_roots`), `crates/engine/src/tests/package.rs` (`a_confined_package_refuses_a_linked_file_whose_editing_data_cannot_be_read`). - Linked-file and font-file searches under `--automation-read-root`: `links.findFiles` and `text.findFontFiles` replies, also later polls and stops of a search another client started, leave out the files found, a link's saved path and the folder searched outside the caller's read roots, and a failed search gives its reason without the path; `image.info` gives `link: null` for a linked file outside them; `text.addFontFiles` gives `folder: null` and the copies' file names when the Fonts folder is outside them. `crates/engine/src/tests/linkfiles.rs`, `crates/engine/src/tests/fontfiles.rs`, `crates/engine/tests/font_folder.rs`. - Swatch, brush, symbol and graphic style library lists under `--automation-read-root`: every library stays listed, the paths of library files and the user library folder outside the read roots are `null`, a library loaded from outside them is listed and found as `loaded/` and keeps that id for the session unless a library loaded later without a file shows that id itself, which moves it to the next free `loaded/ (N)`, and the app's own list is not changed. `crates/engine/src/tests/library_roots.rs`. - Preferences commands under `--automation-read-root`: `prefs.get`, `prefs.list`, `prefs.set` and `prefs.reset` show folder preferences outside the read roots as `null` and leave out an export preset's folder outside them, and the preferences are not changed. `crates/engine/src/tests/prefs_roots.rs`. @@ -1044,10 +1049,12 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The Czech catalog (`crates/ui-egui/src/i18n/cs.tsv`) translates 114 status and error messages that no catalog had a row for: the 3D and Revolve limits, image export and encoding errors, color profiles, color books and swatch exchange files, binary DXF and DWG import, path operations, swatch, graphic style and action set libraries, and zip, script and regular expression errors. The untranslated report (`untranslated_report`) still lists 54 messages for every language: the 53 composite font, SVG filter, read root and graph design errors that open #7211, #7378 and #7405 translate, and `` `index` must be a whole number ``. See [localization-parity.md](localization-parity.md). - The History panel, Edit › Undo and Edit › Redo translate the names of the steps that apply or redefine a character or paragraph style and of the step that redefines a graphic style: each such step keeps its template (`Apply {name}`, `Redefine {name}`, `Redefine Graphic Style “{name}”`) and the style's name, every complete catalog has a row for each template, and the panel and the menu show the style's name as the document holds it, except the Normal styles' names, which they show in the interface language (`steps_named_after_a_style_list_the_template_around_the_name`, `undo_and_redo_name_a_style_step_around_the_style_name`). - The Polish catalog (`crates/ui-egui/src/i18n/pl.tsv`) has an `@msg` row for the status and error messages the untranslated report (`untranslated_report`) finds in the sources, 3,439 `@msg` rows in all: the errors of commands, scripts, file import and export and plug-ins. The report lists 46 Polish messages: 44 that open #7211, #7214, #7116, #7330 and #1931 translate, and 2 that no language has a row for. A message with two placeholders in a row (`Template::parse` in `crates/ui-egui/src/i18n/catalog.rs`) is still shown in English. + - Polish labels and messages call drawn art and artwork *kompozycja*, the term the catalog's header sets, instead of *grafika* or *rysunek*. *Grafika* stays for what the English calls a graphic (graphic styles, library and 3D graphics, GPU graphics), and line art, the art brush and an artboard (*obszar kompozycji*) keep their own terms (`polish_rows_call_artwork_kompozycja`). - The status bar translates the limits a plug-in run can exceed (its instruction, time and memory budgets and its output size) and the error of a plug-in removal that leaves the plug-in's grant in the plug-in store, in every language that translates every message. The untranslated-strings report also lists messages that an error or a status takes from a `&str` constant (`plugin_limit_errors_are_translated`, `message_scan_reads_messages_held_in_constants`). - The untranslated-strings report reads a message written over two lines with a `\` at the end of the first as one line, the text the program shows, and the Georgian catalog's (`ka`) row for PDF export's warning about knockout groups with too many translucent elements matches that text (`message_scan_joins_a_literal_continued_on_the_next_line`, `untranslated_report`). - The status bar translates the plug-in host's other errors (manifest, module and run checks, the output an importer, exporter or effect returns, and the approval a plug-in's permissions need) in every language that translates every message. A JSON object or array inside a message stays as written, and a message that wraps another one, such as `plug-in manifest: {0}`, is matched by its own row before a row that starts with a placeholder. The reasons inside these errors (what is wrong with a parameter's spec or dialog keys, the value a parameter needs, what is wrong with an object, stroke, paint or effect in a plug-in's output) are translated with them, and the untranslated-strings report lists the reasons the plug-in host's error helpers take (`plugin_messages_are_translated_in_every_complete_catalog`, `plugin_errors_translate_with_their_values`, `plugin_error_reasons_are_translated_with_the_error`, `message_scan_reads_plugin_helpers`, `templates_that_start_with_text_match_first`). - The status bar translates `script.run`'s refusals of `answers` in every language that translates every message: a value that is not a list, more than 10,000 answers, more than 1 MiB, an answer at an index that is not an object, does not have exactly `kind` and `value`, has a `value` its kind of dialog does not take, holds a prompt's text longer than 16 KiB or has an unknown `kind`, and `answers` given to a run in the app. The index, the counts and the code names are shown as they are, and the command's error stays in English. The untranslated-strings report also lists the refusals of `script.run`'s parameters (`script_answers_errors_are_translated`, `message_scan_reads_script_run_param_refusals`). + - The status bar also translates `script.run`'s other refusals of its parameters in every language that translates every message: a `maxFuel` outside 1 to 100,000,000,000, `args` nested more than 64 levels deep (with the place in `args`), `args` that is not an object or is larger than 1 MiB, an empty `path`, a `source` given with `installed`, a `path` that does not name a .js or .jsx file, and neither or both of `path` and `source`. The code names, the place in `args`, the file suffixes and the limits are shown as they are, and the command's error stays in English (`script_run_param_errors_are_translated`). - The Japanese catalog (`crates/ui-egui/src/i18n/ja.tsv`) has 3,562 `@msg` rows and 49 `@msgplural` rows (counted 2026-11-14). The untranslated report (`untranslated_report`) lists 98 status and error messages in the sources that have no Japanese row: 77 that every complete-message language lacks, and 21 more. Open #7211 translates 34 of them, among them the composite font errors, and open #7116 translates the justification order error. The status bar does not use the rows for ``unknown parameter `{within}{key}`; {why}`` and `{name} must be {lo}–{hi}{unit} (got {v})`, because a message with two placeholders in a row cannot be matched (`Template::parse` in `crates/ui-egui/src/i18n/catalog.rs`). The row for `{k} has control characters{_1}` does not match the File Info error for a multi-line field, where the last placeholder is empty. A native speaker has not reviewed the wording. - A status or error message whose braces are literal, such as a plug-in's `expected {"objects": [...]}` or a command's `quotes must be {double?, single?}`, is translated only when the whole message matches its row: the row writes those braces doubled and has no placeholder, so it no longer replaces a different message that starts with the same words, such as a JSON reason `expected value at line 1 column 1`, which stays in English. A row without placeholders is found at any message length (`plain_message_keys_double_their_braces`, `literal_brace_rows_match_only_their_message`). - Every complete-message catalog translates five more messages with literal braces through such a row: the composite font errors `each font must be {name, parts}` and `give fonts: [{name, parts}…]`, `select.font`'s `` `scope` must be "document", {artboards: [index, …]} or {layers: [id, …]} ``, the script regular expression error `numbers out of order in {} quantifier` and `the paint is not a freeform gradient (apply one with paint.editGradient {kind: "freeform"})`. Each translation keeps the braced example as written, and no catalog keeps the older rows with a placeholder in place of the braces, which also translated other text with the same start and end (`literal_brace_messages_have_exact_rows_in_complete_languages`). @@ -1097,6 +1104,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - A Learn tutorial's steps are marked complete as the learner works, and a skill's progress ring fills as its tutorials are finished, as the help page describes ([the help page](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/learn-skills-quick-skill-guide.html)). Each step has a check box that marks it done once the tutorial's sample is open (`learn.markStep`); Finish tutorial marks every step done; a skill's count shows its tutorials finished of all, and a finished tutorial has a check mark in its skill's list. Marking steps by hand, the count, keeping the progress in the preferences (the web build keeps it while the page is open) and Reset progress (`learn.resetProgress`) are VectorCraft's own rules; `learn.list` reports the progress. Regression tests: `a_step_s_check_box_marks_only_that_step`, `a_step_s_check_box_works_from_the_keyboard`, `finishing_tutorials_fills_their_skill_s_ring_and_count`, `a_skill_with_no_tutorials_shows_0_of_0`, `learn_mark_step_checks_its_params`, `reset_progress_clears_only_the_progress`, `the_preferences_keep_the_progress` and `saved_progress_is_read_leniently` in `crates/ui-egui/src/panels/learn/tests.rs`. - The Home screen has a Learn section with the in-app tutorials, as the help page lists among the Home screen's options ([the help page](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/homescreen-overview.html)): the Quick skill guide card shows the Learn panel's list of skills (`learn.skills`), and each tutorial, listed under its skill, shows the panel at its steps (`learn.show`). It shows with no document open and over open documents, and a choice leaves the documents as they are. Its place between Recent Files and the new-file presets, its layout and what a choice opens are VectorCraft's own rules (`tests::home::home_has_a_learn_section_that_opens_the_learn_panel`, `home_learn_section_over_open_documents_leaves_them_as_they_are`, `home_quick_skill_guide_card_works_from_the_keyboard`). - The errors of the blend spine commands (Move Spine Point, Reshape Spine Segment, Add Spine Point and Delete Spine Point) show in the status bar in the interface language: each has a row in every catalog that translates all status and error messages and in Bulgarian (`blend_spine_param_errors_are_translated`). + - The errors of Automatic Plane Positioning (`perspective.plane.infer`) and of its two Perspective Grid Options (`perspective.widget.options`) show in the status bar in the interface language: a hidden grid, both options off, a negative `tolerance`, `at` given with `clear`, and an `anchorPoint` or `gridlineIntersection` that is not true or false. Each has a row in every catalog that translates all status and error messages, with the parameter names kept (`automatic_plane_positioning_errors_are_translated`). - The errors of the 3D effects (Extrude & Bevel, Revolve, Inflate, Rotate and their Classic forms) show in the status bar in the interface language: the art a 3D effect cannot build a solid from, invalid light, graphics and surface settings, and the notes for an object that draws no 3D faces or more wireframe edges than the limit. Each has a row in every catalog that translates all status and error messages, and the effect's name and the values in the message are translated or kept as written (`three_d_refusals_are_translated_in_every_complete_catalog`, `three_d_refusals_translate_with_their_values`). - The errors of an SVG filter that the New or Edit button of Apply SVG Filter or an `svg.filter` effect refuses show in the status bar in the interface language: XML that cannot be read, a missing or too long id, an element or event attribute a filter does not take, an image that is not a `data:` URL, and the limits on primitives, `numOctaves`, `order`, `radius`, `stdDeviation`, `kernelUnitLength`, image pixels, nesting and size. Each has a row in every catalog that translates all status and error messages, and the limits, element and attribute names and the XML parser's position are kept as written (`svg_filter_refusals_are_translated_in_every_complete_catalog`, `svg_filter_refusals_translate_with_their_values`). Items side by side in a menu show different labels in every interface language (Effect › 3D and Materials › Revolve… and Rotate… in Turkish and Bulgarian, Effect › Warp and Distort, the Pathfinder effects, the Warp styles, Window › Attributes and Properties, and the whitespace characters), and no menu item shows a command id in place of its label (`menu_items_side_by_side_have_different_labels`, `menu_items_never_show_an_id`). - Keyboard Shortcuts shows each entry under a name of its own in every interface language: the Scale and Zoom tools, the Column and Bar Graph tools and their stacked forms, the Pucker and Wrinkle tools, the Shear and Warp tools, Edit › Copy and Duplicate, Pathfinder Unite and Merge, and View › Saved View 2 to 17 have different names in every catalog (`no_two_entries_have_the_same_name_in_any_language`). The Line Graph tool reads as a line graph in Russian and Ukrainian, and in every catalog a row whose English name ends with a number keeps that number (`numbered_rows_keep_their_number`). @@ -1132,6 +1140,10 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Symbols panel context menu** ([Symbols panel](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html)): right-clicking a symbol in thumbnail view or list view displays a context menu with Place Symbol Instance (passes view center or artboard center), Edit Symbol, Duplicate Symbol, Delete Symbol, Break Link to Symbol (enabled when canvas selection includes instances of this symbol), and Select All Instances. Right-clicking an unselected symbol selects it first (`symbol.setCurrent`). Tests: `panels::symbols::tests::right_click_context_menu_in_symbols_panel_runs_actions`. - **Drag a symbol onto New Symbol to duplicate it** ([the help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=197), Duplicate a symbol in the panel section): a symbol dragged from the Symbols panel, in thumbnail view or a list view, and released on the New Symbol button is copied as Duplicate Symbol copies it (`symbol.duplicate`), with no Symbol Options dialog, even while no art is selected and the button is disabled for clicks. VectorCraft's own rules: the copy is made of the dragged symbol, not the current one, under Duplicate Symbol's default name, in one undo step; the current symbol and the selection stay as they were and no instance is placed; the button is outlined while a symbol of the document is held over it; a library symbol, art, a name the document no longer has or a symbol dragged from another document is ignored. Tests: `panels::symbols::tests::symbol_dropped_on_new_button_duplicates_the_dragged_symbol_in_both_views`, `new_symbol_button_ignores_other_drops_and_releases_outside`, `a_symbol_dragged_from_another_document_is_not_duplicated`. - **Drag a symbol onto Delete Symbol to delete it** ([the tutorial](https://shop.smashingmagazine.com/2011/09/an-in-depth-study-of-symbols-in-illustrator-cs5/), [Symbols panel](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html)): a symbol dragged from the Symbols panel, in thumbnail view or a list view, and released on the Delete Symbol button is deleted as a click on the button deletes it (`symbol.delete`): an unused symbol asks "Delete the selected symbol?", a symbol with placed instances asks with Expand Instances, Delete Instances and Cancel, and Alt held at the release deletes an unused symbol without asking. VectorCraft's own rules: the dragged symbol is deleted, not the current one, in one undo step; a symbol that Select All Unused picked deletes every picked symbol still unused, after one question, and a symbol outside the pick is deleted on its own; the button is outlined while a symbol of the document is held over it; a library symbol, art, a name the document no longer has or a symbol dragged from another document is ignored. Tests: `panels::symbols::tests::symbol_dropped_on_delete_button_deletes_the_dragged_symbol_in_both_views`, `a_picked_symbol_dropped_on_delete_deletes_the_picked_symbols`, `delete_symbol_button_ignores_other_drops_and_releases_outside`. + - **Alt-drag art onto a symbol to redefine it** ([the help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=194), Modify a symbol instance section): art dragged off the canvas and released on a symbol in the Symbols panel with Alt (Option on macOS) held replaces that symbol's art, and every instance of the symbol updates, as Redefine Symbol does (`symbol.update` with the dragged art's `ids`). Released without Alt, the art still becomes a new symbol. VectorCraft's own rules: the symbol under the pointer is redefined, not the current one, in thumbnail view and both list views; the art becomes an instance of it, in one undo step; only that tile or row is outlined while the art is held over it with Alt; art of another document, objects the document no longer has and art that holds an instance of the symbol (directly, in an opacity mask or through the symbols it nests, which Redefine Symbol from the menu also refuses) change nothing. Tests: `panels::symbols::tests::alt_art_drop_on_a_symbol_redefines_that_symbol_in_one_step`, `alt_let_go_after_the_release_in_the_same_frame_still_redefines`, `a_plain_art_drop_on_a_symbol_makes_a_new_symbol`, `an_alt_art_drop_that_cannot_redefine_changes_nothing`, `a_secondary_button_release_drops_no_art`, `tests::brushsym::redefine_refuses_art_holding_an_instance_of_the_symbol`. + - **Shift with Redefine Symbol keeps the art** ([the help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/edit-symbols.html), Redefine a symbol with another object section): Redefine Symbol chosen from the Symbols panel menu with Shift held updates the symbol and every instance of it from the selected art, and the selected art stays ordinary art instead of becoming an instance (`symbol.update {keepArt: true}`). Chosen without Shift, the art still becomes an instance. VectorCraft's own rules: the art keeps its ids, layer and place in the stacking order and stays selected, apart from art that is hidden or locked; the result has no instance id; the redefine is one undo step and, for the symbol being edited, also leaves symbol editing mode; `keepArt` defaults to false, and a value other than true or false is an error. Tests: `panels::symbols::tests::shift_redefine_symbol_in_the_menu_keeps_the_art_as_ordinary_art`, `tests::brushsym::redefine_with_keep_art_leaves_the_art_as_ordinary_art`, `redefine_with_keep_art_selects_only_selectable_art_and_refuses_a_bad_switch`, `tests::symboledit::redefining_the_symbol_being_edited_with_keep_art_leaves_the_art_and_the_mode`. + - **Shift with New Symbol keeps the art** ([the help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=192), Create a symbol section): holding Shift while making a new symbol from the selected art, with the Symbols panel's New Symbol button, its New Symbol… menu item or by dragging the art onto the panel, adds the symbol and leaves the art as ordinary art instead of turning it into an instance (`symbol.new {keepArt: true}`). Without Shift, the art still becomes an instance. VectorCraft's own rules: Shift is read when the button or menu item is clicked, or when the dragged art is released, and Symbol Options' OK uses it even if Shift has been let go; Shift with Alt on the button makes the symbol without Symbol Options and keeps the art; the art keeps its ids, layer and place in the stacking order and stays selected, apart from art that cannot be selected (hidden or locked art, art in a hidden or locked group or layer, template art, art outside an isolated group, art on a locked artboard); frames of threaded text stay in their thread; the result has no instance id; the new symbol becomes the current symbol in one undo step; `keepArt` defaults to false, and a value other than true or false is an error. Tests: `panels::symbols::tests::shift_new_symbol_in_the_menu_keeps_the_art_as_ordinary_art`, `shift_new_symbol_button_keeps_the_art_with_or_without_alt`, `shift_art_drop_on_the_panel_keeps_the_art_as_ordinary_art`, `symbol_options_checks_keep_art`, `tests::brushsym::new_symbol_with_keep_art_leaves_the_art_as_ordinary_art`, `new_symbol_with_keep_art_selects_only_selectable_art_and_refuses_a_bad_switch`, `cmd::threads::tests::frames_kept_as_art_by_a_new_or_redefined_symbol_stay_in_their_thread`. + - **Symbol Options button** ([Symbols panel options](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html), [Create and place symbols](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-and-place-symbols.html)): the help pages list a Symbol Options control among the Symbols panel's buttons, after Break Link to Symbol and before New Symbol, and it opens the settings of the chosen symbol. The panel's bottom bar has that button, and a click opens Symbol Options on the current symbol, as the panel menu's Symbol Options… does (`ui.symbolOptions {edit: true}`). VectorCraft's own rules: the button is disabled while the document has no current symbol, Alt-click does the same as a plain click, opening the dialog adds no undo step, and the icon is the one Swatch Options uses. Tests: `panels::symbols::tests::symbol_options_button_edits_the_current_symbol`. - **Symbols › Select All Unused** ([Symbols panel](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html), #4918): the Symbols panel menu's Select All Unused shows the symbols nothing places selected (`symbol.unused`): instances in the art (opacity masks included), graph designs, pattern tiles and brush art count, and so do instances in a used symbol's art. Delete Symbol, the button or the menu item, then asks "Delete the selected symbols?" once and deletes those still unused in one undo step (`symbol.delete {names}`); Alt-click on the button deletes them without asking, and a click on a symbol picks just it again. Tests: `tests::brushsym::symbol_unused_lists_the_symbols_nothing_places_and_delete_takes_several`, `panels::symbols::tests::select_all_unused_picks_the_unused_symbols_and_delete_deletes_them`, `dialogs::symbol_delete::tests::several_symbols_get_the_plural_question`. - **Symbols › Sort by Name and the list views** ([the help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html)): the Symbols panel menu's Sort by Name puts the symbols in alphabetical order (`symbol.sortByName`), and its Thumbnail View, Small List View and Large List View show them as thumbnails, in a compact list or in a list with larger thumbnails. VectorCraft's own rules: the sort ignores case and keeps names that differ only in case in their order; it changes the document's order, which `symbol.list` reports, as one undo step, keeps the current symbol and adds no undo step when the symbols are already in order; Thumbnail View is the default, Small List View has 18-point rows with 14-point thumbnails and Large List View 26-point rows with 22-point thumbnails, and a click or double-click on a symbol does the same in every view. `ui.panelView` sets the view of the Symbols panel, and of the Swatches and Graphic Styles panels, as their panel menus do. Tests: `tests::brushsym::symbol_sort_by_name_orders_the_symbols_in_one_undo_step`, `panels::symbols::tests::sort_by_name_and_the_small_and_large_list_views`, `panels::symbols::tests::panel_view_sets_the_view_of_each_panel`. - **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`. @@ -1267,6 +1279,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur `css.export` refuses a `scope` or `path` that is not a string (`5`, `true`, `["all"]`, `null`) before writing anything, instead of exporting the selection or returning the CSS as data; a left-out `scope` still exports the selection, and a left-out `path` still returns the CSS. `css.generate` and `css.export {scope: "all"}` refuse a malformed `ids` or `id`, which they do not use, as the selection's export does. Agents read the key object: `select.key` returns it, and `document.inspect` and the `ui.pointer` and `pointer_gesture` replies report it as `key`. `select.key` with an id that isn't a selected top-level object returns an error and leaves the key unchanged. The Select menu's Same commands, its Object commands that select art, Next Object Above and Below, saved selections and the Magic Wand (#2655) select only objects that Select All selects and objects inside them: nothing hidden or locked, nothing in a hidden or locked group, layer or sublayer, nothing on a template layer, and in isolation mode nothing outside the isolated group or layer. In isolation mode Select All, All on Active Artboard and Inverse select nothing while the isolated group or layer, or a group or layer it is in, is hidden, locked or a template layer. + Next Object Above and Below check only the siblings of the selected object, each through the layers and groups that hold it, instead of collecting every object Select All can reach on each press, and they select the same object. In a release build, stepping from the middle of 100,000 rectangles on one layer takes a median of 0.08 µs of thread CPU time per step, against 11.5 ms with a test-only copy of the earlier search, and 0.08 µs against 7.4 ms with 1,000 groups of 100 (7 alternating runs of each in one process; `next_object_perf`). The earlier search's time grows with the number of objects in the document, so the change matters on large documents. `next_object_gives_what_the_search_over_every_selectable_object_gave` compares every node and every step of random documents, isolation mode included, with the earlier search. In a CMYK document the Magic Wand's Fill Color and Stroke Color tolerances run from 0 to 100 and compare the colors' CMYK values; in an RGB document they run from 0 to 255 and compare RGB values, as the [help page](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf) gives the two ranges. The distance is VectorCraft's own: the Euclidean distance between the C, M, Y and K percentages, with RGB, Gray and Lab colors converted to CMYK. A tolerance above 100 set in an RGB document applies as 100 in a CMYK document and comes back in an RGB one. `magicWand.set` refuses a tolerance out of its range and changes nothing (`cmyk_document_compares_fill_and_stroke_colors_in_cmyk`, `set_rejects_tolerances_out_of_range_and_changes_nothing`). The Magic Wand finds compound paths, the selected objects and the objects it picks through hash sets instead of searching lists, and it selects the same objects in the same order. In a release build, with every second object selected in a document of 50,000 paths (12,500 of them in 6,250 compound paths), setting that selection and Shift-clicking takes a median of 142 ms of CPU time, against 353 ms for the same steps run with test-only copies of the earlier searches, and 30 ms against 61 ms at 20,000 paths (7 alternating runs of each in one process, measured while other builds were running; `magic_wand_membership_timing`). Small documents gain little: 2.1 ms against 2.3 ms at 2,000 paths. `membership_sets_give_the_same_objects_in_the_same_order_as_searches` compares the selection in each mode with the earlier searches. Select ▸ Object ▸ Bristle Brush Strokes selects the objects whose topmost stroke has a bristle brush, whatever the brush is named, and leaves out objects whose brush is of another type, also when its name has "Bristle" in it. @@ -1298,6 +1311,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Shapes:** all shape tools (including Flare) and the line, arc, spiral and grid tools. Space held while dragging out a shape, line, arc, spiral or grid moves it at its current size. The Flare tool's center drag turns the rays with the pointer, Shift keeps them in their original orientation (unturned, or turned by a nonzero General › Constrain Angle), and Space held during either of its drags moves the flare. While a grid is dragged out, Up/Down change its rows (concentric dividers) and Left/Right its columns (radial dividers). A click with a grid tool asks for the size, the divider counts and the grid options (#1377, in part): a skew for each set of dividers, Use Outside Rectangle As Frame or Create Compound Path From Ellipses, and Fill Grid; they are parameters of `shape.rectangularGrid` and `shape.polarGrid`, stay as the tool's options and apply to drags too. The curve a skew percentage follows and the direction of the radial skew are our own (the public documentation gives neither), and the dialogs have no reference point locator. An ellipse's Pie Start and End Angle and Invert Pie (Transform and Properties panels' Ellipse Properties, `object.setLiveShape {pieStart, pieEnd, invertPie}`) cut it as a pie (#812). With the bounding box showing, the Selection tool shows a selected ellipse's two pie widgets just outside it; dragging one sets its angle in one undo step and double-clicking one makes the ellipse whole again. A live polygon's Polygon Properties there: side count, angle, corner type and radius, radius, side length and Make Sides Equal once an uneven scale has made its sides differ (`object.setLiveShape {sides, polygonAngle, polygonRadius, sideLength, makeSidesEqual}`, part of #812); a star is a plain path, as in Illustrator. The Flare Tool Options last as the tool's options: the next flare dragged out uses them, a click's dialog shows them and double-clicking the tool opens them (part of #812). - **Shapes:** all shape tools (including Flare) and the line, arc, spiral and grid tools. Space held while dragging out a shape, line, arc, spiral or grid moves it at its current size. The Flare tool's center drag turns the rays with the pointer, Shift keeps them in their original orientation, and Space held during either of its drags moves the flare. While a grid is dragged out, Up/Down change its rows (concentric dividers) and Left/Right its columns (radial dividers). A click with a grid tool asks for the size, the divider counts and the grid options (#1377, in part): a skew for each set of dividers, Use Outside Rectangle As Frame or Create Compound Path From Ellipses, and Fill Grid; they are parameters of `shape.rectangularGrid` and `shape.polarGrid`, stay as the tool's options and apply to drags too. The curve a skew percentage follows and the direction of the radial skew are our own (the public documentation gives neither), and the dialogs have no reference point locator. An ellipse's Pie Start and End Angle and Invert Pie (Transform and Properties panels' Ellipse Properties, `object.setLiveShape {pieStart, pieEnd, invertPie}`) cut it as a pie (#812). With the bounding box showing, the Selection tool shows a selected ellipse's two pie widgets just outside it; dragging one sets its angle in one undo step and double-clicking one makes the ellipse whole again. A live polygon's Polygon Properties there: side count, angle, corner type and radius, radius, side length and Make Sides Equal once an uneven scale has made its sides differ (`object.setLiveShape {sides, polygonAngle, polygonRadius, sideLength, makeSidesEqual}`, part of #812); a star is a plain path, as in Illustrator. The Flare Tool Options last as the tool's options: the next flare dragged out uses them, a click's dialog shows them and double-clicking the tool opens them (part of #812). A live line drawn with the Line Segment tool shows Line Properties in the Transform panel and the Properties panel's Transform section: Line Length (a length above 0, in the document's units) and Line Angle (0° horizontal, 90° vertical, any value brought into 0° to 360°), the two properties that [the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/live-shape-properties.html) lists for a line (`object.setLiveShape {lineLength, lineAngle}`). Typing one sets every selected line in one undo step. These rules are VectorCraft's own: the angle runs counterclockwise from 3 o'clock, as the Rotate field does; a new length keeps the line's first end in place and a new angle turns it about its midpoint; a line whose ends meet reads 0°; the section shows only while every selected object is a live line; and a line that would reach past the document's coordinate limit is an error that changes nothing. Expand Shape makes the line a plain path without these properties (tests `a_line_shows_and_takes_its_line_properties` and, through the engine, `a_line_takes_its_length_and_angle`). + Ellipse Properties in the Transform panel and the Properties panel's Transform section has a Constrain Pie Angle link beside Pie Start and Pie End Angle: while it is on, a typed angle moves the other one by the same amount, so the pie keeps its size, as [the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/live-shape-properties.html) describes (`object.setLiveShape {pieStart or pieEnd, constrainPie}`). These rules are VectorCraft's own: the link starts off at every launch and is not saved; the two panels share it; each selected ellipse keeps its own span, counted counterclockwise from its start angle to its end angle and across 0°, in one undo step for all of them; a whole ellipse stays whole; after Invert Pie the swapped span is kept; and the on-canvas pie widgets still move one angle at a time (tests `the_constrain_pie_angle_link_keeps_the_span` and, through the engine, `constrain_pie_keeps_each_ellipses_span`). Backtick (`` ` ``) held while a rectangle, rounded rectangle, ellipse, polygon, star or line is dragged out leaves copies of the shape being drawn along the drag, each its own object: the continuous duplicate that the Keys for drawing table of [the help page](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=469) lists. Each copy is the shape as the drag showed it then, with its modifiers and Up/Down counts; the release keeps the copies and the last shape as one undo step, and Escape takes them all back. The spacing (a copy each time the pointer has moved 8 screen points with the key down, none for the key alone) and the limit of 128 copies a drag are VectorCraft's own values, and a shape with no width, height or length leaves no copy. The arc, spiral, grid and Flare tools do not leave copies (tests `backtick_drag_leaves_copies_of_the_rectangle_being_drawn` and, through the engine, `a_backtick_drag_leaves_copies_of_the_shape_as_one_undo_step`). Escape while a polygon, star or rounded rectangle is dragged out cancels it and puts back the side count, point count, corner radius or star ratio its Up/Down and Ctrl/Cmd changed, so the next drag, the tool's options and General › Corner Radius start from the values before the canceled drag; a drag that is let go keeps them, and an option set with `tool.setOption` during the drag stays. This is VectorCraft's own rule. A click with the Rounded Rectangle tool opens the size dialog with its radius at General › Corner Radius, and OK makes the radius typed there that preference, so later rounded rectangles and the dialog's next opening start from it while rounded rectangles already drawn keep their corners, as [the help page](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=64) describes. A radius outside the preference's range of 0 to 1296 pt, which is VectorCraft's own, or one that is not a length is refused with an error: the dialog stays open, nothing is drawn and the preference keeps its value. Evidence: `dialogs::shapes::tests::{rounded_rectangle_click_dialog_opens_on_and_sets_the_corner_radius, rounded_rectangle_click_dialog_refuses_a_radius_out_of_range}`. @@ -1321,13 +1335,15 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur The settled part of that outline is kept in paths of up to 64 pieces each. A path is shared from one frame to the next until a piece in it changes, and the canvas keeps the triangles it drew the path with while the view stays the same, so a frame does not copy, flatten or tessellate a settled path again; a pan, zoom or rotation draws each one once more. This is VectorCraft's own rule. The line that a drag of more than 64 segments shows with a round Eraser tip, the Knife, the Path Eraser or the Pencil with Live preview off is kept the same way, in pieces of 64 segments: a frame builds again only the last piece, and the Knife's dashes run on from one piece to the next. With the Eraser's Size set to a mode that follows the pen, each step of such a drag is kept as its own path and a frame builds only a new step. A smoothing drag's band is kept until it changes. The canvas still copies the kept triangles of every piece into each frame. - **Transform:** Rotate, Reflect, Scale, Shear (click or Alt-click snaps the reference point to anchors and centres; Alt-click opens the tool's dialog, and a drag with Alt down at the release, from the press or pressed mid-drag, transforms a copy), Reshape, Free Transform (free and perspective distort and shear, switched by the keys held during a handle drag). A Reshape drag stretches part of a path from the dragged point without losing the path's general form, as [Adjust path segments](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/adjust-path-segments.html) has it. On an open path the stretch reaches both ends: the end anchors stay in place, each anchor between moves less the nearer it lies to an end, and the handles of a smooth anchor stay in line (`path.reshape`; the reach and the shares are VectorCraft's own rule, in `docs/mcp.md`). A click sets a focal point and a click on a segment adds a highlighted anchor there; Shift-click adds more, and a drag from any of them moves them all. The anchors that are not direct-selected stay in place and a closed path selected whole moves whole (VectorCraft's own rule, in `docs/mcp.md`). - Align, Distribute, Distribute Spacing, Reflect and Shear return an error for any `horizontal`, `vertical`, `to`, `axis`, `bounds` or `spacing` value they don't take, listing the choices, and Align returns one when a call gives neither `horizontal` nor `vertical`; nothing moves and no undo step is recorded. Align and Distribute act on the anchor points selected with Direct Selection: the points of one path align to each other, not to the artboard, and Distribute spaces them (#1641, fixes #1636; aligning to a key anchor is still missing). + Align, Distribute, Distribute Spacing, Reflect and Shear return an error for any `horizontal`, `vertical`, `to`, `axis`, `bounds` or `spacing` value they don't take, listing the choices, and Align returns one when a call gives neither `horizontal` nor `vertical`; nothing moves and no undo step is recorded. Shear takes an angle from -359° to 359° and shears by its tangent, so 120° slants as -60°; an angle outside that range, and ±90° and ±270° (VectorCraft's own rule), return an error ([shear objects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/shear-objects.html); `shear_angles_slant_by_their_tangent`, `shear_rejects_angles_with_no_shear_or_out_of_range`). Align and Distribute act on the anchor points selected with Direct Selection: the points of one path align to each other, not to the artboard, and Distribute spaces them (#1641, fixes #1636; aligning to a key anchor is still missing). Transform Each opens on the scale, move, rotate, reflect, Random, reference point, Transform Objects and Preview it was last confirmed with (kept with the UI state; Copy never is), and its Copy button, left of Cancel, transforms a copy of each object as the [Scale multiple objects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/scale-multiple-objects.html) help page has it; the Copy checkbox is gone (#1732; the remembered values follow a maintainer comment on the issue, not the help page). Its Scale section has the Relative and Absolute radio buttons the same page describes: percentages of each object's size, or the width and height it becomes (`object.transformEach` `relative`, which Transform Again repeats); Absolute measures each object's own box, and the scales act along its axes about that box's reference point, so a turned shape keeps its shape and objects of different sizes come out alike; the fields show the width and height the selected objects share and read "Mixed" when they differ or a side is 0 (a line's), each object measured by its own box, rotated with it, as the Transform panel and the Control bar show it (sizes they show alike count as the same), and a size typed into them sets every object to it (a side left Mixed keeps its size), our choices where the page leaves them open; a live Repeat scales its spacing by the geometric mean of the two factors, so its Absolute size is approximate. The link beside the two scales keeps them in proportion, as the shape dialogs' Width and Height link does (`__constrain`, kept with the dialog's values; where it sits is our choice, the public pages don't establish it). The panel lists Scale, Move and Rotate, then the Options in two columns (Transform Objects, Transform Patterns, Scale Strokes & Effects, Scale Corners; Reflect X, Reflect Y, Random), the Reference Point, and Preview at the left of the button row, level with Copy, Cancel and OK. Transform Again uses the Copy, Transform Patterns, Scale Strokes & Effects and Scale Corners choices of the transform it repeats; after a bounding-box handle drag on area type, it resizes the type area again and the type keeps its size (`object.transformAgain`). With anchors selected with Direct Selection, Move, Rotate, Scale, Reflect, Shear and Transform Again (the commands, their dialogs and the four tools' drags) transform only those anchors, their handles with them, about the centre of the box around them unless a point was clicked; a copy still copies the whole object (#1408; behaviour reference: [adjust path segments](https://helpx.adobe.com/illustrator/using/adjust-path-segments.html); the default reference point and the copy are our choices). The Move, Rotate, Scale, Reflect and Shear dialogs have a Preview checkbox, off when they open: while it is on the canvas follows the values, Cancel rolls it back and OK is still one undo step; Up/Down step the Rotate and Shear angles and the Scale percentages by 1, Shift by 10 (#1412). The five dialogs and Transform Each have Transform Objects beside Transform Patterns: off, the art stays and only its pattern tiles transform (`objects` on the transform commands), and Transform Again repeats the choice (#1448; behaviour reference: [scale objects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/scale-objects.html); the checkboxes are always enabled and the Scale page's pair is applied to all of them, our choices). Reflect's axis is Horizontal, Vertical or an angle (#1460; [reflect objects along an axis](https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/reflect-objects-along-an-axis.html)). + Shear's axis is Horizontal, Vertical or Angle: the Shear dialog's Axis Angle field, and a numeric `axis` on `object.shear`, set a line on the page from -359° to 359° that the art slides along, apart from the shear angle; an axis angle outside that range is an error and nothing changes ([the help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/shear-objects.html) describes this angled axis and its range; counter-clockwise from horizontal and the field's 0° start are our choices). Tests: `shear_along_an_axis_at_an_angle`, `reflect_and_shear_reject_unknown_axes_without_changing_state` and `shear_takes_an_axis_angle`. - **Pen:** Alt pressed in the middle of dragging out an anchor splits its handles and keeps the curve already shaped into it (only the outgoing handle follows the pointer); Space held while dragging out an anchor moves it, handles and all. A press on the first anchor of the path being drawn closes it whatever the drag then does: the drag shapes the closing curve and the release closes the path wherever it ends (#501). The first anchor's incoming handle mirrors the pointer, and a click leaves it retracted and the anchor a corner. Its outgoing handle stays where it is on a corner, so the first segment keeps its shape, and on a smooth anchor it turns to stay in line at its own length; Alt makes the anchor a corner and leaves the outgoing handle where it was when Alt went down. The Smart Pen's closing drag does the same (fixes #6634; `path.close`'s `in` and `out`; behavior reference: [draw with the Pen, Curvature, or Pencil tool](https://web.archive.org/web/20220614224656/https://helpx.adobe.com/illustrator/using/drawing-pen-curvature-or-pencil.html), where a click or drag on the first anchor closes the path and Alt breaks the pairing of the closing anchor's handles; which handles the drag sets are our choices). Space held during the Pen's closing drag moves the first anchor, handles and all, as that page also describes (`path.close`'s `at`). Clicking the last anchor of the path being drawn retracts its outgoing handle (convert cursor), and dragging from it pulls out a new one on its own. Auto Add/Delete: over a selected path, a click on a segment adds an anchor and a click on an anchor deletes it (add and delete cursors); Shift held, or Preferences › General › Disable Auto Add/Delete, starts a new path instead. Alt held over a handle end or an anchor of a selected path (the one being drawn too) works as the Anchor Point tool, with its convert cursor: dragging a handle moves it alone, clicking a smooth anchor makes it a corner, dragging an anchor pulls out new symmetric handles, dragging a segment reshapes it; drawing then goes on. Cmd (Ctrl) held drags with the selection tool chosen last, Direct Selection until one is (handles, anchors and segments of the path being drawn or another), and the Pen then goes on drawing its path while that stays selected; the pointer shows that tool's while Cmd is held. The same holds for agents (`pointer_gesture` with `mods.cmd`), as the borrowing now lives in the engine (#494). A drag's preview (the Pen's, the Anchor Point tool's, Direct Selection's handles and anchors) follows every position the pointer is seen at (#834): the canvas sends the tool a drag whenever the pointer's document position differs from the last one it sent, not only when egui's frame delta is non-zero (zero when a compositor coalesces motion and in the frame the pointer comes back into the window after leaving it), and a move that arrives in the release's own frame shapes the preview before the release commits it, once the press has dragged. With the Pen, a press that moves under 3 screen pixels is a click (a corner without handles), and a Precise Cursors command toggles the existing preference and can take a shortcut (#1663). Choosing the Pen again while it draws a path (P, a click on its button, `tool.select`) ends the path as Escape does: the path stays open and selected (a path inside a compound path leaves the compound path selected), the Pen stays chosen, and the next click starts a new path. The [help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/preview-paths-drawn.html) describes P doing this with the preview off; doing it with Rubber Band on and for the button and `tool.select` are VectorCraft's own rules. - **Direct Selection (#1278):** clicking a segment picks its connection, with hollow endpoint anchors and only that curve's direction handles. Delete leaves the neighboring curves and appearance intact, opens/splits contours in one undo step, and another Delete removes the remaining selected path. A whole-path drag and deliberate anchor selection keep their existing behavior; egui frames and native control/art checked, OS mouse/visual QA pending. Where anchors of overlapping objects coincide, a click or drag takes the anchor of the selected object, also when another object lies over it (#1509, fixes #1508). Delete removes every selected anchor of a closed path (it used to remove the wrong ones), removes objects selected whole along with the selected anchors of others, and keeps the remainder selected so a second Delete removes it (#1674). In isolation mode Direct Selection and Group Selection pick only inside the isolated object (#1666). Escape cancels a Direct Selection drag (#1803, #1743). Double-clicking type (including type nested inside a group) switches to the Type tool and puts the caret at the clicked character. With Direct Selection and Group Selection, a drag that starts on an object while the selection also holds direct-selected anchors or segments moves those anchors and the objects selected whole in one undo step (`path.moveAnchors`), as a drag of a selected anchor does, and the other anchors of a partly selected path stay in place. While Alt is held during the drag, it copies the selected objects instead (`object.transform`). When direct-selected anchors are moved or transformed together with objects selected whole (such a drag, an anchor drag, an arrow key, or Move, Rotate, Scale, Reflect and Shear without a copy), a path inside a selected group is transformed once, with the group. + VectorCraft's own preference General › Interpolate Control Points When Moving Anchors (`interpolateControlPoints`, off by default, fixes #7832): on, a Direct Selection drag, an arrow-key nudge, a Move or a Transform Again of selected anchors re-maps both handles of each segment with one moved end by the turn, uniform scale and move that take its old ends to its new ends, so a segment between corner anchors keeps its shape; a segment with both ends moved, or with its ends at the same place before or after the move, moves rigidly, and a smooth anchor keeps its handles in line. The commands take an `interpolate` param that defaults to the preference, and the value used joins the journal and Transform Again. Each drag or nudge is one undo step (`a_nudge_with_the_preference_on_re_maps_both_handles_of_the_segment`, `a_direct_selection_drag_with_the_preference_on_re_maps_the_handles_in_one_undo_step`, `a_smooth_anchor_keeps_its_handles_in_line`). A path segment with a control point whose x or y is infinite or larger in size than `f64::MAX / 16` is measured by its control points, so its bounds hold the whole curve and the canvas check refuses an edit that leaves such a path selected (`path.create` included). With Direct Selection, the Pen and the anchor tools, a group, compound path or clip group selected whole shows the anchors of its paths filled, as a path selected whole does; the direction handles still show only on a path that is selected itself. Public references: [Adjust anchor point, handle, and bounding box display size](https://web.archive.org/web/20251114182206/https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/adjust-anchor-point-handle-and-bounding-box-display-size.html) and [Drawing basics](https://web.archive.org/web/20231130064834/https://helpx.adobe.com/illustrator/using/drawing-basics.html) (archived copies). When the Add Anchor Point tool, the Pen's Auto Add, the Smart Pen's Alt-click on a segment or Alt-click with the Scissors adds an anchor to a path with direct-selected anchors or segments (`path.insertAnchor`), the same points stay selected: the anchors and segments after the new anchor are numbered one higher, and a selected segment that the new anchor splits stays selected as its two halves. @@ -1348,6 +1364,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur 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. - **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). - **Blend spine points by marquee:** with Direct Selection, a marquee picks the spine points inside it on a selected blend, the topmost one when several are selected, and the picked points drag together as Shift-clicked ones do; Shift-marquee adds points or takes picked ones away, a plain marquee around none of them drops the picks, and Escape during the marquee keeps them. Unselected, locked and hidden blends are skipped. The spine's points are anchor points edited with Direct Selection ([the help page](https://helpx.adobe.com/illustrator/desktop/manage-colors/apply-transparency-and-blending/modify-spine-of-blended-objects.html)), and a boundary drag with the tool selects anchor points ([the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-paths/select-anchor-points-in-paths.html)); the rules for selected, topmost and Shift are VectorCraft's own (`crates/tools/src/direct/tests.rs`, `marquee_picks_selected_blend_spine_points_which_drag_together`, `shift_marquee_toggles_selected_blend_spine_points`, `marquee_skips_unselected_locked_and_hidden_blend_spines`, `escape_cancels_a_marquee_and_keeps_the_picked_spine_points`). + When no selected object is a blend, the selected-spine checks of Direct Selection's hover, press and marquee, the Anchor Point tool and the Pen return at once instead of building every blend's spine first; on 20,000 paths and 200 blends with one path selected, 500 checks took 24 µs instead of 336 ms, and the results are the same (`the_selected_spine_check_builds_no_spine_without_a_selected_blend`, `the_selected_spine_check_matches_a_filter_of_every_spine`; `selected_spine_check_timing` times it). - **Blend steps of brushed strokes:** the steps interpolate the pen pressure, tilt, bearing and rotation recorded with the Paintbrush, so a Calligraphic, Scatter or Art brush that varies with the pen changes gradually from one key to the next. A key without a recording counts as half pressure, half tilt and 0°, as brushes read it, and angles turn the shorter way round. When the blend starts a key's path at another anchor (an open path run from its end, a closed one turned to another start), the key's recordings, width profile, arrowheads, dashes and a gradient along or across the stroke turn with the path. Different brushes still switch halfway (VectorCraft's own rule; strokes blend their options, as [Blended objects overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/apply-transparency-and-blending/blended-objects-overview.html) describes; `crates/doc/src/blend.rs`, `pen_pressure_tilt_and_angles_interpolate_for_brushes`, `stroke_profiles_turn_with_a_key_path_started_elsewhere`, `stroke_gradients_and_dashes_turn_with_a_key_path_started_elsewhere`). - **Blend steps of spot gradients with process plates:** when the matching stops of two gradients, or of a gradient and a solid, are tints of one spot swatch, each step's stop stays linked to it at a tint between the two and keeps the process inks printed with it, each of C, M, Y and K between the two stops' amounts; a stop or solid without process inks counts as none of each. Gradients with different stop counts keep the inks at every resampled stop. PDF export writes such a step as one DeviceN shading of the spot and process inks. Tints of one spot color blend into tints of it, as [the help page](https://helpx.adobe.com/illustrator/desktop/manage-colors/apply-transparency-and-blending/blended-objects-overview.html) describes; the process-ink interpolation is VectorCraft's own rule (`crates/doc/src/blend.rs`, `blend_gradient_spot_process_plates_interpolate`, `resampled_gradient_spot_process_plates_interpolate`, `blend_gradient_missing_plates_mean_zero`, `blend_solid_to_spot_gradient_does_not_copy_plates`; `crates/pdf/src/tests/output.rs`, `blend_steps_between_spot_gradients_with_process_plates_print_both_inks`). - **Path editing (#494):** the handles shown are the handles that drag: Direct Selection drags those of a path selected as a whole (as the Pen leaves it), the Anchor Point tool and Pen+Alt no longer grab handles that Show handles when multiple anchors are selected hides, a handle shorter than the tolerance leaves its anchor to be picked, and the anchor tools pick within Selection & Anchor Display › Tolerance. A dragged segment keeps a smooth anchor at either end smooth. With Direct Selection, the Pen, the Curvature and the anchor tools, a path selected as a whole shows all its anchors selected, and the Control bar and the Properties panel offer Convert (corner, smooth) for them too; Remove and Cut wait for anchors direct-selected (#504). A handle drag gathers its snap targets once per drag (it took 21 ms per pointer move on a 20,000-path document, now 1 ms; `vectorcraft-cli perf` measures handle and segment drags on a 5,000-anchor path). Join merges the selected anchor points that lie on one another, as after Average, into one anchor (#1582, fixes #1533), and removes the merged anchors in one pass over the path, so a long run of them no longer moves the anchors after it once per merge (`cmd::path::tests::a_long_run_before_many_other_anchors_merges_in_one_pass`); Object › Path › Average & Join… (`path.averageJoin`, Cmd+Alt+Shift+J, the "Create corner or smooth join" shortcut of [Default keyboard shortcuts](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)) moves two open path ends to their midpoint and joins them there, a corner or smooth point as its dialog's Points choice asks, in one undo step. @@ -1409,10 +1426,12 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur A Shift-drag with the Shape Builder tool draws a rectangular marquee for merging many paths at once, as [Combine shapes with the Shape Builder tool](https://web.archive.org/web/20251006211643/https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/combine-shapes-with-shape-builder-tool.html) describes: the regions it reaches are shaded while it is drawn and merge into one shape on release, or with Alt they are deleted. The marquee reaches each region whose outline crosses it or has an anchor inside it, and the region that holds the whole marquee; this rule is VectorCraft's own. For Pick Color From Artwork, the marquee's starting corner is where the drag starts and the opposite corner is where it ends (`shapeBuilder.merge` `rect`). The Shape Builder works on the selected paths, as [Combine shapes with the Shape Builder tool](https://web.archive.org/web/20251006211643/https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/combine-shapes-with-shape-builder-tool.html) describes. As VectorCraft's own rule, a click or drag that builds nothing says why in the status bar when it is released: "Shape Builder: select paths or compound paths" when nothing is selected or the selection holds no unlocked, visible path; "Shape Builder: select all paths you want to merge" when the release is over a path or compound path that is not selected; and "Shape Builder: no region under the pointer" otherwise. The document, the selection and the undo history stay as they were, and the next gesture that builds something clears the message. Regression tests: `shape_builder_with_nothing_selected_says_what_to_select`, `shape_builder_names_the_unselected_path_under_a_release_that_built_nothing` and `shape_builder_replayed_gesture_over_nothing_gives_its_status_once` in `builder/tests.rs`, and `tests::build::shape_builder_click_that_builds_nothing_shows_why`. Shape Builder pieces on dense hatches (lines at exact 0.25 or 0.5 pt steps across another line) come back one per stretch between crossings, with no speck where the sweep cut a line's two passes a rounding error apart: the planar map contracts the stub between such cuts into one vertex, bounded by each cluster's extent so a run of tiny level segments keeps its length (`crates/pathops/src/planar.rs` tests `a_dense_hatch_at_exact_binary_steps_cuts_each_line_once_per_crossing`, `a_run_of_tiny_level_segments_is_not_contracted_as_stubs`, `a_line_crossed_where_its_two_passes_part_is_cut_once`). + The Shape Builder's gray hatch over the region under the pointer and the regions a drag has touched is drawn by a sweep that tests each hatch line only against the region's edges that span it, instead of every edge on every line. The hatch lines are the same, coordinate for coordinate; on a 2,000-sided region 1,000 hatches take about 83 ms of CPU time instead of 356 ms (release build, median of 7 alternating runs), and on a region of 40 sides the time is about the same, so the gain is on large, complex regions such as traced art (`crates/tools/src/builder/tests.rs` tests `hatch_matches_testing_every_edge`, `hatch_tests_only_the_edges_spanning_each_line` and `hatch_sweep_finds_the_crossings_of_every_edge`; timing: `hatch_perf`). The planar map's edge-source grid stays linear in memory on any input: a segment is filed once per cell it crosses, and the grid holds at most a budget of cell references (a few dozen per item plus a few rows' worth), past which the remaining items go to a short scanned list and are still found, so thousands of coincident segments cannot make the index quadratic (`crates/pathops/src/planar.rs` test `rect_index_holds_a_bounded_number_of_references`). The Blob Brush Tool Options have Keep selected and Merge only with selection, both off by default: while Keep selected is off, the blob a stroke draws or merges into is not selected afterwards, and while Merge only with selection is on, a stroke merges only with selected blobs of its color that it touches (`path.blob` `keepSelected` and `mergeOnlySelection`). The Blob Brush Tool Options also have Angle and Roundness, as the reference app's [Blob Brush options](https://web.archive.org/web/20261012042029/https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/blob-brush-options-and-best-practices.html) list them: Angle from −180° to 180° (0° by default) and Roundness from 0% to 100% (100%, a round tip, by default). The elliptical tip keeps its angle on the page along a stroke, a 0% tip is drawn 0.1% as wide as it is long, and the dialog shows the tip and three dabs of it. The values are kept with the tool's options (`path.blob` `angle` and `roundness`). Not done: the Random and pen-driven variations of Angle and Roundness. The Blob Brush Tool Options' tip preview is the Angle slider for screen readers, with the Angle in degrees as its value: a click or a drag in it points the Angle at the pointer and gives it the keyboard focus, Tab reaches it after the Roundness field, and the arrow keys step the Angle by 1° (10° with Shift, Home and End to −180° and 180°). + The tip preview also has an arrowhead on its Angle line and a black dot at each end of the tip's short axis. A drag that starts on a dot sets the Roundness: moving the dot toward the center makes the tip flatter and moving it away makes it rounder, as the Blob Brush tool options section of the [help page](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=183) describes. A click or a drag that starts anywhere else in the square still sets only the Angle. The mapping is VectorCraft's own: the Roundness is the pointer's distance from the center along the short axis as a percentage of half the tip's length (18 pt in the preview), in whole percent from 0% to 100%, and the drag goes on past the square's edge until the release. A press within 8 pt of a dot takes the dot. The dot drag gives the keyboard focus to a Roundness slider, which screen readers get after the Angle slider and which Tab reaches after it; its arrow keys step the Roundness by 1% (10% with Shift, Home and End to 0% and 100%). Regression tests: `dialogs::tests::a_drag_on_a_blob_brush_tip_dot_sets_the_roundness`, `dialogs::freehand::tests::a_roundness_dot_sets_its_distance_along_the_short_axis`. The Blob Brush Tool Options also have Fidelity, which the reference app's [Blob Brush options](https://web.archive.org/web/20261012042029/https://helpx.adobe.com/illustrator/desktop/paint-and-fill/learn-painting-basics/blob-brush-options-and-best-practices.html) list as setting how far the pointer moves before the path gets a new anchor point. The range and default are VectorCraft's own values: the Pencil's logarithmic slider from Accurate (0.01 pt) to Smooth (20 pt) and its field (up to 100 pt), 1.5 pt by default and kept with the tool's options. The brush follows the stroke fitted at the Fidelity, as a Pencil stroke is fitted: a low value follows the drag closely, jitter included, and a higher one gives smoother curves (`path.blob` `fidelity`). `path.blob` rejects an Angle outside −180° to 180°, a Roundness outside 0% to 100% and a Fidelity outside 0.01 to 100 pt with an error and leaves the document unchanged; a key left out or null takes its default (0°, 100% and no fitting). A Blob Brush stroke merges with the topmost path of its fill color and no stroke that it touches, and with the other such paths it touches in the same group or layer that are next to that path in stacking order with no other kind of object between them; matching paths in other groups or layers are left alone, as the Blob Brush tool guidelines in [Paint with fills and strokes](https://web.archive.org/web/20241219085603/https://helpx.adobe.com/illustrator/using/painting-fills-strokes.html) describe (`path.blob`). @@ -1432,6 +1451,10 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur A modal window that opens without a press in the window (a dialog opened from the macOS menu bar or by an automation command, the About window, a file dialog, the update prompt, or the progress window of a plug-in, trace or open run) closes the Command Palette, a tool group's flyout, the All Tools drawer and any open menu or popup in the pass it opens. While such a window is open, the palette stays closed, so opening it from the macOS menu bar or by an automation command does not take the keyboard from the window; it opens again once the window closes (`palette` tests `a_dialog_opened_from_the_system_menu_closes_the_palette`, `the_about_window_closes_the_palette`, `a_progress_window_closes_the_palette`, `the_palette_opened_over_a_dialog_closes`, `a_click_on_the_menu_bar_closes_the_palette_before_a_dialog_opens`, `a_dialog_opened_without_a_press_closes_a_flyout`, `a_dialog_opened_without_a_press_closes_the_tools_drawer`, `a_dialog_opened_without_a_press_closes_a_menu`, `the_palette_opened_as_a_dialog_closes_stays_open_until_the_next_dialog`). The Command Palette ranks its results by how well they match. A query that is a result's id lists that result first (`view.goto1` lists Saved View 1 above Saved View 10); then come results whose name is the query, results whose name without its menu path starts with it, and results whose initials it is ("ea" finds Export As…). Within each of those, a result where every word of the query is a whole word of its name ranks above one where a word only starts a word of the name, then one where it is a word of the menu that holds it, then of its id, then text inside a word, so a query that is a menu's title ("object") lists results named with that word above the items of that menu. A tool ranks above a menu command, panel, effect or filter plug-in that matches as well, so "rect" lists the Rectangle Tool above Effect › Convert to Shape › Rectangle…, and of two results of the same kind the shorter name comes first. Words of the menu bar item that runs a result also find it, the item's own label included ("exit" finds Quit VectorCraft, which File › Exit runs); with the native macOS menu bar, the items that bar moves into its application menu are found under it (Preferences… under Settings). Every result the earlier search found is still found, and the highlight stays on its result when a plug-in is installed, a shortcut changes or the language changes while the palette is open (`palette::search` tests `a_better_word_grade_ranks_first`, `a_better_whole_query_tier_ranks_first`, `kind_and_length_never_lift_a_worse_grade`, `a_menu_title_does_not_lift_its_items`, `common_queries_list_the_command_near_the_top`, `every_result_is_found_first_by_its_name_and_its_id`, `every_result_found_before_is_still_found_and_shown`, `results_know_their_place_in_the_menu_bar`, `native_homes_follow_the_native_application_menu`; `palette` test `the_highlight_stays_on_its_result_when_the_results_change`). 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 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 without one, and 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 results without typos keep their order (`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`, `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`). + 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`). `object.setProps` with `visible: false` or `locked: true` deselects every selected object that is then hidden or locked, the key object included, as the eye and lock columns do. Ctrl/Cmd+Alt-clicking an eye switches the other layers to Outline and the row's layer to Preview, or switches all layers back to Preview when the others are in Outline (`layer.outlineOthers`, `layer.previewAll`). Ctrl/Cmd+Alt-clicking New Layer adds a layer directly below the current layer, at its level (`layer.new {below: true}`), and Ctrl/Cmd+Alt-clicking New Sublayer adds a sublayer under the contents of the layer it goes into (`layer.newSublayer {bottom: true}`), each in one undo step. The reference app's [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) page lists these clicks for placing a layer below the selected layer and a new sublayer at the bottom of the layer list. @@ -1522,6 +1545,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Export 3D Object (Asset Export's menu): an object with Extrude & Bevel, Revolve, Inflate or Rotate becomes a 3D asset whose Format is USDA (the default), USDZ, glTF or OBJ, and Export writes each of its solids as a mesh with a material in its paint's color (`assets.add3D`, `assets.set3DFormat`, `assets.export3D`; [export 3D vector artwork](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/export-3d-vector-artwork.html)). - Export 3D Object builds each Extrude & Bevel (both kinds) and Inflate solid once: the same build gives the faces that count toward the object's limit and the faces of its mesh, and the meshes match those of a separate build bit for bit. Tests `mesh::tests::a_meshed_solid_is_built_once`, `an_extruded_solid_and_its_mesh_match_the_two_built_apart`, `inflated_solids_and_their_meshes_match_the_two_built_apart`, `solids::tests_mesh::one_build_exports_the_meshes_built_apart`, `a_stroke_past_the_limits_is_left_out_of_the_export`. - Export 3D Object writes the graphics mapped onto a plane or onto Extrude & Bevel's front and back caps as a PNG texture of each face, the face's color with its graphics drawn flat and unlit over it, on a mesh of that face with texture coordinates, in all four formats (glTF embeds it, USDZ packs it after the layer, OBJ and USDA write `-texture-1.png` beside them; `assets.export3D` `textureSize`, 128 to 4096 pixels, default 1024, VectorCraft's own values; [the help page](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/map-artwork-on-3d-objects.html)). Graphics on Revolve's side, materials and lighting are not exported. Tests `a_caps_mesh_corners_go_back_to_the_art_they_were_made_from`, `a_mesh_carries_its_caps_graphics_flat_in_the_arts_plane`, `each_format_carries_a_textured_part_with_its_coordinates_and_picture`, `export_3d_paints_mapped_graphics_on_their_caps_in_every_format`. + - The 3D and Materials panel works out whether Export 3D Object is available once for each document revision and reuses it on later frames. The button shows the same state. With 200,000 paths selected, working it out on every frame took a median 61.6 ms of thread CPU time per frame in a release build on Linux (57.1 ms with a path of a compound path with Extrude & Bevel selected last); the first frame after a change still takes about as long, and later frames take about 2 ns (`panels::three_d::tests::export_3d_object_state_kept_for_a_revision_equals_a_fresh_one`, `export_3d_object_state_is_worked_out_once_per_revision`, `export_3d_object_state_timing`). - Checking an Extrude & Bevel (both kinds) or Inflate effect builds each solid the effect draws once, about the bounds the effect draws it about; a shape with no fill still has its profile built on its own. Tests `solids::tests::the_check_builds_each_drawn_solid_once`, `the_check_builds_the_profile_of_a_shape_with_no_fill`. - Initial live Revolve (#605, #846): a portable geometry and shading crate (`three-d`), editable path and compound profiles, compact options with artboard rotation and light gizmos, SVG/PDF vector output and Expand Appearance that can trim covered faces. Open ends have continuous caps by default, shading is smooth with one to ten colored lights, and intersecting surfaces' visibility is approximate ([revolve.md](revolve.md)). - Revolve takes graphics on its swept side, shaded with the object's light ([the archived reference, page 185](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=185)). By VectorCraft's own rule a graphic wraps around the axis at its own size at every distance from it, narrows toward the silhouette, follows the profile along its length and is hidden where the side faces away (`threeD.mapGraphic`; `revolve::tests_graphics`, `tests::side_faces_lie_on_the_unrolled_surface_and_caps_do_not`, `map_graphic_puts_a_graphic_on_the_side_of_a_revolve`). @@ -1573,8 +1597,9 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Find Font: Escape and the replacement search:** Escape with the Replace With Font From or Find In list open closes only the list. The dialog stays open with its choices and its search, also while Escape is held down, and the next press of Escape closes it. Done, Enter, Escape, and Find in Folder… once the Missing Fonts dialog opens, each forget the replacement search, so the next Find Font starts with an empty one; with no folder picked, Find Font stays open with its search. This is VectorCraft's own rule: a dropdown or popover open in a dialog closes before the dialog. Tests: `crates/ui-egui/src/find_font.rs`. - **Select Text by Font: scope (a VectorCraft addition, #5529):** `select.font` takes `scope`: `"document"` (the default, as before), `{artboards: [index, …]}` or `{layers: [id, …]}` (sublayers included). On an artboard means what All on Active Artboard takes (the bounds overlap it or the center is on it; one shared test, `select::on_artboard`); hidden and locked text stays out as before; a symbol instance counts where the instance is. Type › Find Font…'s Find In dropdown passes the active artboard or the selected layers (else the current layer). Tests: `crates/engine/src/cmd/fonts.rs`, `crates/ui-egui/src/find_font.rs`, `crates/engine/tests/command_sweep.rs`. - **Find Font: type in opacity masks and pattern swatches:** Type › Find Font…'s Document list (`text.fonts`), Find (`select.font`), Change and Change All (`text.replaceFont`), Replace Missing Fonts (`addon.cleanup.replaceFonts`), the Missing Fonts dialog (`text.missingFonts`), Document Info's Fonts and Font Details for the whole document (`document.info`), File › Package and the export warning about fonts that aren't available include the type in opacity masks (on objects and layers, disabled masks and masks inside mask, symbol or pattern art included) and in the art of pattern swatches, also a swatch that nothing paints with. A pattern's type is listed and changed once, however many objects the pattern paints. Find selects the objects whose mask holds the font, the text whose inline graphics draw a symbol whose art uses it, and the objects painted with a pattern whose art uses it by a visible fill or stroke above 0% opacity (VectorCraft's own rule; a layer's mask and a swatch that nothing paints with select nothing); Change and Change All leave the type in the mask of a hidden or locked object in its font and count it in `skipped`, and Change does the same with the type of a pattern that only hidden or locked selected objects paint with. The help page (https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/find-and-replace-fonts.html) says the Document list holds all the fonts the document uses. Tests: `crates/engine/src/cmd/fonts.rs`, `crates/engine/src/cmd/addons/cleanup/text/tests.rs`, `crates/engine/src/cmd/docinfo.rs`. +- **Find Font works out the document's fonts once per version:** while Type › Find Font… is open, its Document list (`text.fonts`) and whether it shows Find in Folder… (the document misses a font) are worked out once for each version of the document's content and of the available fonts, and later frames reuse them. The list and the button are the same as before; an edit, an undo, another document in front, entering or leaving pattern editing, a composite font defined or taken out, and fonts added or scanned again give them anew. With 2,000 point-type objects of 50 characters each, set in five installed faces and a missing family, working them out took a median 1.53 ms of thread CPU time per frame in a release build on Linux; the first frame after a change still takes about as long, and later frames take about 10 ns. With 20 such objects it took 58 µs per frame. Tests: `find_font::tests::the_font_list_is_worked_out_once_per_document_version`, `an_edit_works_the_font_list_out_again`, `other_available_fonts_work_the_font_list_out_again`, `the_font_list_follows_the_document_in_front`; the timing probe is `find_font::tests::find_font_list_timing`. - **Mouse wheel over the font family field (#5253):** In the Character and Properties panels and the Control bar, turning the mouse wheel over the closed font family field applies the next family to the selected type (the previous one when turned up), keeping the style when the family has it, else its closest. Each notch is one undo step; leaving the field or Escape keeps the family, and Undo takes it back. The steps use the font menu's order at the first turn and keep it until the pointer leaves the field or the text selection changes, so recent-font updates do not reshuffle later turns. That order follows the font filters every font menu shares (one chosen in the Glyphs panel's menu or a dialog's applies too) but ignores its search text, puts recent families first, and stops at the first and last family. A turn with a modifier key is left to the panel and the canvas. Behavior reference: the [Illustrator CS6 reference](https://help.adobe.com/archive/en/illustrator/cs6/illustrator_reference.pdf#page=10) describes editing hovered dropdown controls with the mouse wheel; [Find and apply fonts](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/find-and-apply-fonts.html) names the family field's places. Applying it to the font field, the order, the ends and the undo steps are VectorCraft's own rules. Tests: `crates/ui-egui/src/tests/font_menu.rs`, `crates/ui-egui/src/font_menu/tests.rs`, `crates/ui-egui/tests/font_wheel.rs`. -- **Type:** Character size, leading, baseline shift and horizontal-scale controls account for object/group transforms (#1034): exact document-point sizes, mixed-value display and keyboard increments, range edits, resettable horizontal stretch, undo/redo and native save/reopen (`tests_typescale`, Character panel tests). Point size is the transformed em-height axis, independent of glyph ink bounds; affine rotation, reflection and shear are retained. Group scaling still scales text; preserving font sizes is a separate enhancement. Behaviour reference: [Transform text](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/transform-text.html) (public documentation). Text Wrap, Type on a Path effects (Rainbow/Skew/3D Ribbon/Stair Step/Gravity) and Options (Flip, Align to Path, Spacing; OK keeps the type where it is), type on a path's start, centre and end brackets (Selection and Direct Selection drag them to set where the type runs, slide it along its path and, across the path, flip it: #429), Character and Paragraph Styles (override-preserving redefine), paragraph attributes per paragraph (alignment, indents, spacing, hyphenation, hanging punctuation, tab stops, paragraph style, direction, mojikumi and leading model; the Paragraph, Tabs and Paragraph Styles panels act on the paragraphs the Type tool's selection or caret touches, Return continues the paragraph's style, threads and SVG keep them), Area Type Options (rows/columns/inset/first baseline, Text Flow by rows or by columns (#4978), vertical Align Top/Center/Bottom/Justify per row/column, reflowing non-rectangular frames and text wrap), threaded text across any closed shapes, Fit Headline, the Every-line Composer for justified and ragged text (paragraph-wide breaks for an even rag, Single-line per object from the Paragraph panel menu or `text.setFormat {composer}`). Area type resizes like Illustrator's type areas: a bounding-box handle drag (Selection tool) or Area Type Options Width/Height size the frame and the text reflows at its size (threads too); Direct Selection drags a frame corner or edge (`text.reshapeArea`), and an anchor of the path of type on a path outside perspective, the type reflowing along it (`text.reshapePath`, #3980). Point type still scales. Auto Size: the frame height follows the text after every edit, in the same undo step (rectangular frames of horizontal type in one row; columns get the least height that holds them; a height set by hand or threading turns it off), and the "Auto Size New Area Type" preference gives it to new area type. Shrink Text to Fit (beyond Illustrator): overflowing area type scales its sizes, leading and baseline shifts down by the largest factor (in 0.1 pt steps of the first run, down to a minimum percentage) that fits, at layout time so every export sees it. `text.areaOptions` and `document.inspect` report overflow and the shrink factor. The Selection tool shows the type widget beside selected type's bounding box (hollow on point type, filled on area type); double-clicking it converts between them (Type › Convert To Area Type / Convert To Point Type), keeping the text and its styles in place. Variable fonts list every named instance as a style of their family (Figtree Light to Black and their italics, Bahnschrift, Segoe UI Variable), and the instance chosen is shaped, drawn, outlined and measured at its axis settings; PDF and SVG embed it as that instance. The Character panel's Variable Font sliders set each axis (see Fonts). Beyond Illustrator: inline graphics (`text.insertInline`, Type ▸ Insert Inline Symbol) set a document symbol in a run of type as one character that flows, wraps and justifies like a glyph (InDesign-style inline objects, e.g. mana symbols in card rules text): sized to a multiple of the font size, centred on the cap height, opening up tall lines, following Redefine Symbol; a character of its run's size for Character Alignment and Top-to-Top leading, placed by the bidi reordering in right-to-left text (a neutral U+FFFC); drawn on the canvas, kept as live text plus a `` in SVG and as vector art in PDF; Backspace removes it whole. Hebrew and Arabic are laid out right to left with the Unicode bidirectional algorithm (embedded Latin and numbers keep their direction, lines put in visual order after wrapping) in point, area and path type, with caret, selection and arrow keys in visual order; each paragraph's direction comes from its first strong character unless Paragraph Direction sets it (Paragraph panel with Show Indic Options, `text.setFormat {direction}`), and new type aligns to the start of its direction. SVG export outlines right-to-left text. Arabic typefaces: builds made with a craft-fonts checkout that holds its Arabic families (Noto Sans Arabic, the Arabic fallback, plus Cairo, Tajawal, Almarai, IBM Plex Sans Arabic, Noto Kufi Arabic, Amiri, Alexandria, Fustat, Reem Kufi, Aref Ruqaa and Gulzar once craft-fonts adds them, storytold/craft-fonts#11; releases get them when their craft-fonts pin moves) list them in the font menus on desktop; the web build fetches them from beside the wasm (Noto Sans Arabic before start, so Arabic never shows as boxes, the rest in the background). Font Size and Leading are combo boxes in the Character and Properties panels (Font Size in the Control bar too, beside the Character link, font family and style): type, step with ↑/↓ or the spinner, scrub the label, or pick a preset (6–72 pt, shown in the type unit; Leading also Auto), each pick one undo step; Kerning and Tracking list -100…200; a size, leading, kerning or tracking the selected text doesn't share shows blank (#458). Type › Bold and Italic (beyond Illustrator, as page layout apps have them; Cmd+Shift+B / Cmd+Shift+I while the Type tool edits text) switch the selected type to its family's own Bold or Italic face and back, keeping its width (a Narrow face stays Narrow); a family without that face says so (#724). The commands that make or restyle type (and the MCP `add_text` tool) say in their result when area type does not fit its frame, and `add_text` takes Auto Size and Shrink Text to Fit (#1500, fixes #1471). Cmd+Shift+C (Align center) works on Windows and Linux too (#1940). A double-click on area type's bottom middle handle turns on Auto Size (#1940). Print and Print Preview warn about the area type and type on a path that prints without the text that doesn't fit, and give their ids. A tab stop in the Tabs panel drags from where the press landed, a stop just added included (#1487, fixes #1458). Area type in a non-rectangular shape moves a word too wide for the top lines down to the first line that holds it instead of breaking it (#1617, fixes #1615). Stylistic sets (ss01–ss20), stylistic and titling alternates, proportional and lining figures, and superscript and subscript glyphs can be turned on as OpenType features of a character style (`text.setStyle {features}`), and the OpenType panel keeps them (#1611, fixes #1607). Escape while typing ends the edit, keeps the type selected and switches back to the tool that was active before type editing began (kept while clicks move editing to other text), or to the Selection tool when there was none (#1802, #1686, #1656). Select › Same matches type on its characters' fill and stroke (#1746, #1737). `text.create`, `text.createInPath` and the MCP `add_text` tool take `justify`, so point type can be centred on or end at its point (#1752, #1748). New type, made with the Type tools, `text.create`, `text.createInPath` or by pasting plain text, starts in [Normal Character Style] as every character does by default ([Character and paragraph styles](https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html)), so it is filled black, or with the fill a redefined [Normal Character Style] has (editing that style is how new type's defaults change: [FAQs on fonts in Illustrator](https://helpx.adobe.com/illustrator/using/fonts-faq.html), "How to change the default font"), not with the current fill left from the last shape; a `color` given to the command still wins (#7975). Tests: `new_type_takes_the_normal_character_style_fill_not_the_current_fill`, `pasted_plain_text_takes_the_normal_character_style_fill`. +- **Type:** Character size, leading, baseline shift and horizontal-scale controls account for object/group transforms (#1034): exact document-point sizes, mixed-value display and keyboard increments, range edits, resettable horizontal stretch, undo/redo and native save/reopen (`tests_typescale`, Character panel tests). Point size is the transformed em-height axis, independent of glyph ink bounds; affine rotation, reflection and shear are retained. Group scaling still scales text; preserving font sizes is a separate enhancement. Behaviour reference: [Transform text](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/transform-text.html) (public documentation). Text Wrap, Type on a Path effects (Rainbow/Skew/3D Ribbon/Stair Step/Gravity) and Options (Flip, Align to Path, Spacing; OK keeps the type where it is), type on a path's start, centre and end brackets (Selection and Direct Selection drag them to set where the type runs, slide it along its path and, across the path, flip it: #429), Character and Paragraph Styles (override-preserving redefine), paragraph attributes per paragraph (alignment, indents, spacing, hyphenation, hanging punctuation, tab stops, paragraph style, direction, mojikumi and leading model; the Paragraph, Tabs and Paragraph Styles panels act on the paragraphs the Type tool's selection or caret touches, Return continues the paragraph's style, threads and SVG keep them), Area Type Options (rows/columns/inset/first baseline, Text Flow by rows or by columns (#4978), vertical Align Top/Center/Bottom/Justify per row/column, reflowing non-rectangular frames and text wrap), threaded text across any closed shapes, Fit Headline, the Every-line Composer for justified and ragged text (paragraph-wide breaks for an even rag, Single-line per object from the Paragraph panel menu or `text.setFormat {composer}`). Area type resizes like Illustrator's type areas: a bounding-box handle drag (Selection tool) or Area Type Options Width/Height size the frame and the text reflows at its size (threads too); Direct Selection drags a frame corner or edge (`text.reshapeArea`), and an anchor of the path of type on a path outside perspective, the type reflowing along it (`text.reshapePath`, #3980). Point type still scales. Auto Size: the frame height follows the text after every edit, in the same undo step (rectangular frames of horizontal type in one row; columns get the least height that holds them; a height set by hand or threading turns it off), and the "Auto Size New Area Type" preference gives it to new area type. Shrink Text to Fit (beyond Illustrator): overflowing area type scales its sizes, leading and baseline shifts down by the largest factor (in 0.1 pt steps of the first run, down to a minimum percentage) that fits, at layout time so every export sees it. `text.areaOptions` and `document.inspect` report overflow and the shrink factor. The Selection tool shows the type widget beside selected type's bounding box (hollow on point type, filled on area type); double-clicking it converts between them (Type › Convert To Area Type / Convert To Point Type), keeping the text and its styles in place. Variable fonts list every named instance as a style of their family (Figtree Light to Black and their italics, Bahnschrift, Segoe UI Variable), and the instance chosen is shaped, drawn, outlined and measured at its axis settings; PDF and SVG embed it as that instance. The Character panel's Variable Font sliders set each axis (see Fonts). Beyond Illustrator: inline graphics (`text.insertInline`, Type ▸ Insert Inline Symbol) set a document symbol in a run of type as one character that flows, wraps and justifies like a glyph (InDesign-style inline objects, e.g. mana symbols in card rules text): sized to a multiple of the font size, centred on the cap height, opening up tall lines, following Redefine Symbol; a character of its run's size for Character Alignment and Top-to-Top leading, placed by the bidi reordering in right-to-left text (a neutral U+FFFC); drawn on the canvas, kept as live text plus a `` in SVG and as vector art in PDF; Backspace removes it whole. Hebrew and Arabic are laid out right to left with the Unicode bidirectional algorithm (embedded Latin and numbers keep their direction, lines put in visual order after wrapping) in point, area and path type, with caret, selection and arrow keys in visual order; each paragraph's direction comes from its first strong character unless Paragraph Direction sets it (Paragraph panel with Show Indic Options, `text.setFormat {direction}`), and new type aligns to the start of its direction. SVG export outlines right-to-left text. Arabic typefaces: builds made with a craft-fonts checkout that holds its Arabic families (Noto Sans Arabic, the Arabic fallback, plus Cairo, Tajawal, Almarai, IBM Plex Sans Arabic, Noto Kufi Arabic, Amiri, Alexandria, Fustat, Reem Kufi, Aref Ruqaa and Gulzar once craft-fonts adds them, storytold/craft-fonts#11; releases get them when their craft-fonts pin moves) list them in the font menus on desktop; the web build fetches them from beside the wasm (Noto Sans Arabic before start, so Arabic never shows as boxes, the rest in the background). Font Size and Leading are combo boxes in the Character and Properties panels (Font Size in the Control bar too, beside the Character link, font family and style): type, step with ↑/↓ or the spinner, scrub the label, or pick a preset (6–72 pt, shown in the type unit; Leading also Auto), each pick one undo step; Kerning and Tracking list -100…200; a size, leading, kerning or tracking the selected text doesn't share shows blank (#458). Type › Bold and Italic (beyond Illustrator, as page layout apps have them; Cmd+Shift+B / Cmd+Shift+I while the Type tool edits text) switch the selected type to its family's own Bold or Italic face and back, keeping its width (a Narrow face stays Narrow); a family without that face says so (#724). The commands that make or restyle type (and the MCP `add_text` tool) say in their result when area type does not fit its frame, and `add_text` takes Auto Size and Shrink Text to Fit (#1500, fixes #1471). Cmd+Shift+C (Align center) works on Windows and Linux too (#1940). A double-click on area type's bottom middle handle turns on Auto Size (#1940). Print and Print Preview warn about the area type and type on a path that prints without the text that doesn't fit, and give their ids. A tab stop in the Tabs panel drags from where the press landed, a stop just added included (#1487, fixes #1458). Area type in a non-rectangular shape moves a word too wide for the top lines down to the first line that holds it instead of breaking it (#1617, fixes #1615). Stylistic sets (ss01–ss20), stylistic and titling alternates, proportional and lining figures, and superscript and subscript glyphs can be turned on as OpenType features of a character style (`text.setStyle {features}`), and the OpenType panel keeps them (#1611, fixes #1607). Escape while typing ends the edit, keeps the type selected and switches back to the tool that was active before type editing began (kept while clicks move editing to other text), or to the Selection tool when there was none (#1802, #1686, #1656). Select › Same matches type on its characters' fill and stroke (#1746, #1737). `text.create`, `text.createInPath` and the MCP `add_text` tool take `justify`, so point type can be centred on or end at its point (#1752, #1748). New type, made with the Type tools, `text.create`, `text.createInPath` or by pasting plain text, starts in [Normal Character Style] as every character does by default ([Character and paragraph styles](https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html)), so it is filled black, or with the fill a redefined [Normal Character Style] has (editing that style is how new type's defaults change: [FAQs on fonts in Illustrator](https://helpx.adobe.com/illustrator/using/fonts-faq.html), "How to change the default font"), not with the current fill left from the last shape; a `color` given to the command still wins (#7975). It also takes the font, style, size and other character attributes of a redefined [Normal Character Style], so redefining that style in a New Document profile sets the default font of the profile's documents ([Change the default font](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/change-the-default-font-in-illustrator.html)); a `font`, `style` or `size` given to the command still wins. Tests: `new_type_takes_the_normal_character_style_fill_not_the_current_fill`, `pasted_plain_text_takes_the_normal_character_style_fill`, `tests::newdoc::a_profiles_normal_character_style_is_the_default_font`. The Character panel menu's Show Font Height Options shows a Set Font Height Reference dropdown under Font Size (`text.setFormat` or `text.setRangeStyle` `{fontHeightReference}`). Each reference shows an icon of the height it measures before its name, in the open list and in the closed field (#6304): a frame around a letter for Em Box, a bar from the baseline to the top of a capital for Cap Height and of a lowercase x for x-Height, and a frame inset in the em square for ICF Box. With Em Box, the default, the font size is the size of the em square; with Cap Height, x-Height or ICF Box, the characters are set at the em size at which the font's OS/2 cap height, its x height or the height of its ideographic character face equals the font size. With a font that has no such value, or one outside 0.1 to 2 em, the size measures the em box. SVG, PDF and legacy `.ai` export and the CSS Properties rules write the em size the characters are drawn at, and DXF export writes 0.7 times that em size as each TEXT entity's height (group 40, the height of its capitals). Behavior reference: [Vary font height](https://web.archive.org/web/20251118174722/https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/vary-font-height.html). The Every-line Composer composes a paragraph whose characters differ in line metrics (type size, font, leading or vertical scale, or an inline graphic taller than the text) in area type of any shape, rows, columns and text wrap included. In a frame that is not a rectangle, or with text wrap, each line it tries is measured where the lines above it put it, across the line's own height, so a taller line gets the room of the narrower part of the frame, or of the span beside a wrap object, that it reaches. When the frame cannot hold all of such a paragraph, the lines it holds are still composed with the whole paragraph, the lines past the frame's end measured as wide as the last line the frame holds (VectorCraft's own rule); they overflow or go on in the next threaded frame, which composes them again. Such a paragraph is broken with the Single-line Composer when the frame has no room for its first line or when the search passes VectorCraft's own limits. The Single-line Composer measures a line's room across the height of its tallest character too: a line that takes in a taller character is placed again and broken again in the room there. Behavior reference: [the help page](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/set-hyphenation-and-line-breaks.html), and for text that flows on between threaded objects, [the help page](https://helpx.adobe.com/illustrator/desktop/design-with-text/add-manage-text/create-text-threads-between-objects.html). A text wrap object's Offset may be negative as well as positive ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=307)). A negative Offset (to -1000 pt) shrinks the wrap object by that distance, measured from each edge itself and from the edges of its holes, so lines beside it, above it and below it run that far into it, and an object narrower than twice the distance no longer moves text aside. With Invert Wrap, a negative Offset keeps the text that far inside the object. These are VectorCraft's own rules for the shape of the shrunk object. Text Wrap Options, `object.textWrap.make` and `object.textWrap.options` and the MCP `text_wrap` tool take the negative value, and layout uses it (`crates/text/src/layout/region.rs` tests, `cmd::textwrap::tests::text_wrap_options_negative_offset_reflows_and_round_trips`). @@ -1778,6 +1803,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Window › Blend opens the Blend panel: Make, the selected blend's Spacing and Orientation (with no blend selected, the options new blends start with), Reverse Front to Back, Reverse Spine, Replace Spine, Expand and Release, each running its Object › Blend command. Make is dimmed until two or more objects are selected. Spacing and Orientation are dimmed until a blend or two or more objects are selected, and the other buttons are dimmed until a blend is selected. The Blend panel's Create Spine menu (Auto, Always, Never; `object.blend.createSpine`) sets whether new blends get a spine, from the Blend tool, Make and `object.blend.make` alike ([Blend panel overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/apply-transparency-and-blending/blend-panel-overview.html)). Auto and Always give every new blend a straight spine, as before; Never makes blends without one, which keep their steps on the straight lines between the keys, have Type and Ramp dimmed, refuse Reverse Spine and spine edits, release without a spine path, and get a spine from Replace Spine. The setting is kept with the preferences and leaves blends already made as they are; Auto as the starting value and keeping the setting across sessions are VectorCraft's own rules. Builds on #5177 by adambelis. Evidence: `tests::blendopts::{create_spine_sets_whether_new_blends_get_a_spine, a_blend_without_a_spine_has_none_to_edit_reverse_ease_or_release, whether_a_blend_has_a_spine_is_saved_and_old_blends_have_one}` and `panels::tests_blend::create_spine_sets_what_new_blends_get_whatever_is_selected`. Blend Options on several selected blends (the Blend Options dialog, the Blend panel's Type, Ramp and Shift, and `object.blend.options`) sets only the values given or set in the dialog, and each blend keeps its own spacing, orientation, type, ramp and shift for the rest instead of taking the first blend's; a spacing mode given without a count keeps the count of a blend already in that mode. `object.blend.options {id}` edits that blend alone; a hidden or locked blend, an object that is not a blend, a value out of range and an unknown orientation are errors that change nothing, and a call that changes nothing records no undo step. A drag of the panel's Ramp or Shift slider previews on the canvas and records one undo step on release, and Type, Ramp and Reverse Spine are dimmed while a selected blend, or the blend of a key selected with Direct Selection, has no spine. Builds on #8022 by ruchirguitar. Evidence: `tests::blendopts::{options_on_several_blends_set_only_the_values_given, options_with_an_id_edit_that_blend_alone, options_that_change_nothing_or_are_refused_record_no_undo_step}`, `dialogs::blend_options::tests::on_several_blends_ok_sets_only_the_fields_changed` and `panels::tests_blend::{a_ramp_or_shift_drag_is_one_undo_step, ramp_and_shift_edit_every_selected_blend_and_keep_their_other_options, ramp_is_dimmed_while_a_selected_blend_has_no_spine, ramp_and_reverse_spine_are_dimmed_while_a_selected_key_belongs_to_a_blend_with_no_spine}`. + The Blend panel, the Object › Blend, Envelope Distort and Gradient Mesh menu items and their commands find each selected object's nearest blend, envelope or mesh by reading the object's place in the tree once, instead of looking up every ancestor by id, and the checks of whether one is selected stop at the first one found. The results, their order and the errors are the same. With Select All of 102,200 objects (100,000 rectangles, 2,000 blends and 200 envelopes in 10 layers), a release build took a median of 16.5 ms of thread CPU time for the Blend check before and 0.5 ms after, and 18.4 ms before and 8.2 ms after to list the selected blends. Evidence: `cmd::live::selected_tests` and `tests::lookups::nearest_finder_*`. With the Blend tool, Escape drops the object clicked first and stops the next click adding to the blend just made, so the next click picks a new first object; the document and the selection stay as they are. Regression tests: `escape_drops_the_blend_tools_first_pick` in `meshblend.rs` and `tests/blendopts.rs`. Objects on Path (#2545): a click with the Objects on Path tool (in Edit Toolbar's Modify section and the Blend tool's flyout; Object › Objects on Path › Attach and the context menu with two or more objects selected choose it) attaches the selected objects to the path clicked, open or closed, in an Objects on Path group with the path at its bottom. The objects go along the path column by column from left to right, spread evenly from its first anchor (the last one sits on the end of an open path), each turned to the path at its attachment point; Pivot and Rotate set where each one attaches and how far it tilts (`object.objectsOnPath.attach`, `object.objectsOnPath.options`), and with Objects on Path groups selected the Properties panel's Objects on Path Options section shows them as a nine-point Pivot grid and a Rotate field with common angles, each change one undo step for every selected group. Editing the path moves the objects, an object moved on its own goes back, objects moved into or out of the group in the Layers panel join or leave the path, and Object › Objects on Path › Expand leaves a plain group. The group saves and reopens live and exports as plain art. With one Objects on Path group selected, the Selection and Objects on Path tools show the Rotate All widget beside its first object: dragging it turns every object about its attachment point by the angle the pointer turns, adding it to the group's Rotate in one undo step, in 15° steps with Shift ([Objects on Path](https://helpx.adobe.com/illustrator/using/objects-on-path.html)). Detach is in its own entry below. Objects on Path Space widget: with one Objects on Path group of two or more objects selected, the Selection and Objects on Path tools show a square handle beyond its last object; dragging it along the path, round its bends, sets the distance between the objects' attachment points in one undo step, the first object staying where it is, and with Alt (Option on macOS) the objects spread from both ends toward the center; the distance shows next to the pointer during the drag, in the document's units ([Rearrange and edit objects on a path](https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/rearrange-and-edit-objects-on-a-path.html), [Objects on Path](https://helpx.adobe.com/illustrator/using/objects-on-path.html)). The group keeps the distance (`object.objectsOnPath.options {spacing, start}`) through Pivot and Rotate changes, path edits, copies, saving and reopening, and scales it with the group; by default (`"auto"`) the objects are spread evenly as before. Evidence: `objects_on_path::tests::{space_sets_the_distance_between_the_stops, space_on_a_closed_path_wraps_at_the_first_anchor_and_stops_short_of_the_first_object}` in `crates/doc`, `tests::objects_on_path::space_sets_the_distance_between_the_objects_in_one_undo_step` in `crates/engine`, `objects_on_path::tests::dragging_the_space_widget_spaces_the_objects_from_the_first_one` in `crates/tools`. @@ -1814,6 +1840,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur A double-click right of an RGB field switches the Color panel's R, G and B between percent and 0 to 255 ([Default keyboard shortcuts](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html), Color panel). In VectorCraft the color does not change, Web Safe RGB and the hex field stay in 0 to 255, and the panel keeps the choice between sessions (`ui.colorPanel {rgbPercent}`); the color mixer of the Fill and Stroke chips and the gradient stop dialog follow the same setting. Toggle RGB Percent (`ui.colorRgbPercent`) in the command palette and Keyboard Shortcuts switches the units from the keyboard. Tests: `rgb_percent_switches_the_rgb_fields_between_percent_and_0_to_255`, `rgb_percent_does_not_switch_while_the_rows_are_disabled`, `rgb_percent_comes_back_after_a_restart` and `toggle_rgb_percent_switches_the_units_from_the_keyboard` in `crates/ui-egui/src/panels/color/tests.rs`. View › Proof Setup › Color blindness – Tritanopia-type turns Proof Colors on and proofs the canvas with the tritanopia simulation of Brettel, Viénot and Mollon (1997). The Separations Preview panel's Proof Setup list offers the same target (`view.proofSetup {target: "tritanopia"}`). Grays keep their value. The Separations Preview panel's Gamut Check button reports one color outside the CMYK gamut in the singular and more in the plural, in English and in each language's plural forms (`gamut_check_status_takes_the_plural_form` in `crates/ui-egui/src/i18n/tests.rs`). + The "?" on the Fill and Stroke proxies finds a few selected objects along their cached places in the document instead of walking every object; a large selection takes one walk, as before. The proxies show the same paints and question marks as before, also for an id that a damaged file repeats. On a document of 50,000 rectangles in 500 groups on 5 layers with one object selected, the check takes under 5 µs of CPU time instead of a median of 995 µs in a release build on Linux, so the gain shows on large documents (seven alternating runs, `cargo test --release -p vectorcraft-engine --lib proxy_mixed_timing -- --ignored --nocapture`). - **Document Color Mode outside the layers:** File › Document Color Mode (in one undo step) and `document.open {colorMode}` also convert the colors of graph designs, graphic styles, opacity-mask art, the tile that pattern editing's Cancel puts back and the art of brushes (with a Hue Shift brush's key color); a tint of a global swatch there becomes the converted swatch's color at its tint, as in the art. - **Segments dragged onto the grid (#3835):** with View › Snap to Grid (or Snap to Pixel) on, a straight segment dragged with Direct Selection or Group Selection lands its anchors on the grid, the box round them putting an edge on a gridline on each axis as a moved object's does (Shift keeps the move on its line), instead of the point it was pressed at landing on an intersection and leaving both anchors off the grid; a dragged anchor still lands on an intersection itself, and drawn points and resize handles already snapped (`direct::tests::a_dragged_segment_lands_its_anchors_on_the_grid`). - **Spinner arrows in the shadow and glow dialogs (#5367, #5368):** Drop Shadow's Opacity, X Offset, Y Offset, Blur and Darkness and the Outer and Inner Glow's Opacity and Blur have up and down arrows beside the field, as the other number fields with arrows do: a click steps by one (a unit for distances; Shift ×10, Ctrl/Cmd ÷10), holding repeats, Opacity and Darkness stop at 0 and 100 % and Blur at 0 (`dialogs::effect` test `drop_shadow_and_outer_glow_fields_have_spinner_arrows`). @@ -1863,6 +1890,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Under Tints and Tints and Shades, art in black ink alone goes by its ink amount, and a process or gray stroke color's tints and shades stay in that color's model; these are VectorCraft's own rules. Scale Proportionately art is scaled across by the stroke weight and the Width, as Stretch to Fit Stroke Length and Stretch Between Guides art is, on top of the scale the path length gives it, so a 3 pt stroke draws the art three times as wide as a 1 pt stroke. The [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page says Scale Proportionately keeps the art's proportions and does not say how the stroke weight applies; that rule is VectorCraft's own. Evidence: `tests::art_brush_proportional_grows_with_weight` (vectorcraft-brush). Type in a scatter brush's art takes the brush's colorization as its paths do: Tints, Tints and Shades and Hue Shift recolor the characters' solid fills and strokes in each copy the brush draws, and Brush Options' Key Color list, whose first color is Hue Shift's default key, counts the characters' fills and their strokes wider than 0. The Brushes page says that a scatter, art or pattern brush takes its colors from the current stroke color and the brush's colorization method () and does not mention type there; recoloring the characters' paints like the art's fills and strokes is VectorCraft's own rule. The Symbol Stainer mixes the characters' strokes of type toward the stain as it mixes their fills. Evidence: `tests::scatter_colorization_recolors_type`, `tests::art_colors_list_the_most_used_first`, `tests::stain_mixes_type_strokes_too` (vectorcraft-brush). + Scatter Brush Options has Hue Jitter (0° to 180°, 0 by default), VectorCraft's own option: each copy turns the hue of its solid colors, after the colorization, by its own amount up to that far either way. The stroke's path and the brush name fix the amounts, so a stroke draws the same colors every time, and the copies' places, sizes and rotations stay as they are without it. Evidence: `tests::hue_jitter_turns_each_copy_the_same_every_time`, `tests::hue_jitter_of_zero_changes_nothing`, `tests::hue_jitter_turns_after_the_colorization` (vectorcraft-brush), `tests::brushsym::scatter_hue_jitter_saves_and_exports` (vectorcraft-engine). - **Pen tilt, bearing and rotation (part of #764):** Calligraphic and Scatter Brush Options offer Tilt, Bearing and Rotation beside Fixed, Random and Pressure. The Paintbrush records along each stroke how far the pen leans, which way, and how far its barrel is turned (kept with the path, saved, and joined when a stroke continues a path). A Calligraphic value on Tilt goes from value − variation with the pen lying flat to value + variation upright; on Bearing or Rotation it adds variation × the angle over 180°, so Angle on Bearing with a Variation of 180° turns the nib with the way the pen leans. A Scatter value goes from its first value to its second over the same ranges. A stroke without that input draws the brush's own value. On Linux under X11 and XWayland the app reads the tilt and an Art Pen's barrel rotation from XInput2, on macOS it reads them from AppKit's tablet events, and `path.freehand` points and `pointer_gesture` events carry them on every platform. The [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page defines the three options and does not say which way each one runs; that mapping is VectorCraft's own rule. Evidence: `tests::tilt_maps_to_roundness_along_the_stroke`, `tests::bearing_and_rotation_turn_the_nib`, `tests::scatter_values_follow_tilt_and_bearing` (vectorcraft-brush), `tests_brushsym::paintbrush_records_the_pens_tilt_on_the_stroke` (vectorcraft-engine), `tablet::tests::a_pens_tilt_and_rotation_go_into_the_feed` and `mac_tablet::tests::a_pens_tilt_and_rotation_go_into_the_feed` (vectorcraft). Art Brush Options' Width (1% to 1000%) and Pattern Brush Options' Scale (1% to 10000%) each have a slider beside the field, over the same range in whole percents; screen readers name the slider as its row and read the field's value. Art Brush Options' Width has a Fixed or Pressure menu, from the pen tablet options of the Width pop-up menu on the [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page (archived copy). With Pressure, the art is Width wide at the lightest pen pressure and the second width at the heaviest, following the pressure the Paintbrush recorded along the stroke, and half way between them on a stroke without recorded pressure (`brush.options` `width_mode` and `width_max`); a stroke inside the art takes the width at the middle of its object. The page does not say how the pressure maps to the width; taking the Scatter brush's minimum and maximum rule and the stroke rule are VectorCraft's own. The menu also offers Tilt, Bearing and Rotation: the art goes from Width with the pen lying flat to the second width upright, and from Width at −180° to the second width at 180° of the pen's bearing or barrel rotation, as Scatter Brush Options' modes do, and half way on a stroke without that input; the page does not say which way each runs, so that mapping is VectorCraft's own. Evidence: `tests::art_brush_width_follows_tilt_bearing_and_rotation` (vectorcraft-brush). Stylus Wheel is not built. @@ -1898,7 +1926,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Outline Object on an image's own fill or stroke follows the outline of the image's opaque area, and the image's frame when the image has no transparency. Path effects apply to a fill or stroke added to a bitmap object ([archived reference manual, page 561](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=561)), and with Outline Object such a stroke follows the boundary of the art when the image has transparent areas and the image's frame when it has none ([CreativePro article on strokes for placed images](https://web.archive.org/web/20250815214529/https://creativepro.com/add-strokes-placed-images-illustrator/)). VectorCraft's own rules: the opaque area is the pixels at least 50% opaque, and its outline is traced as Image Trace's Black and White mode traces at threshold 128 and fitted with curves. Evidence: `tests::imageoutline` (vectorcraft-effects), `opaque::tests` (vectorcraft-trace), `tests::containers::an_images_stroke_with_outline_object_follows_its_opaque_area` and `tests::containers::an_images_outline_object_stroke_exports_selects_and_measures_along_its_opaque_area` (vectorcraft-engine), `tests::objectfx::an_images_outline_object_stroke_follows_new_pixels_under_the_same_key` (vectorcraft-render). A geometry effect on one of type's own fills or strokes reshapes the whole outline that the fill or stroke paints, on the canvas and in exports; PDF, SVG, EPS and the other vector exports write such type as paths. On type that holds inline graphics, those effects are drawn and exported only when the type has a geometry effect or perspective of its own. A geometry effect on a symbol instance's fill reshapes the filled shapes of the symbol's art and leaves their strokes as they are; one on the instance's stroke reshapes the stroked shapes and leaves their fills as they are. The shapes keep their colors. Only the instance's topmost fill and topmost stroke count, and only while they are visible with an opacity above 0. The canvas and Object › Expand Appearance use the same art, SVG and PDF export bake the same shapes, and Expand Appearance turns the instance into an editable group in one undo step. A group's own fills and strokes in the art take the effects too. An instance inside the art passes the effects on to its own art, and a dynamic symbol's instance reshapes the fills and strokes it paints on the art. How the effects map onto the symbol's art is VectorCraft's own rule. The help page describes effects on one fill or stroke, and the help page describes Expand Appearance (engine `expand::a_symbol_instance_fill_effect_reshapes_its_filled_art_and_expands`, `a_symbol_instance_stroke_effect_reshapes_its_stroked_art_and_expands`, `a_stroke_effect_reshapes_a_stroke_a_dynamic_instance_adds`, `a_fill_effect_reshapes_the_fill_of_a_group_in_the_art`, `only_the_topmost_visible_instance_fill_reshapes_the_art`, `a_nested_symbol_instance_takes_the_outer_fill_effect`, `export_bakes_a_symbol_instance_fill_effect`, `a_fill_effect_on_an_instance_of_a_symbol_that_holds_itself_ends`). Existing documents with a geometry effect on a symbol instance's fill or stroke draw differently: before, the effect drew nothing. - Effect › Pathfinder takes a symbol instance as the art it draws with the geometry effects of its fill and stroke, as they take a path with such effects: the result painted by the instance's art carries those effects, also when the instance has geometry effects of its own and when the instance sits inside another symbol's art. A click where those effects paint the art outside the instance's bounds selects the instance, a fill only when Selection by Path Only is off, and outline mode still takes the instance's bounds alone. A compound shape's area leaves out its members' fill and stroke effects for symbol instances as for paths, since the compound shape paints the area with its own appearance. These are VectorCraft's own rules (engine `expand::pathfinder_takes_a_symbol_instance_fill_and_stroke_effects`, `a_click_where_a_symbol_instance_fill_or_stroke_effect_paints_selects_it`, `a_stroke_effect_reshapes_a_stroke_a_dynamic_instance_adds`, `a_fill_effect_reshapes_the_fill_of_a_group_in_the_art`, `a_click_on_the_grown_fill_of_an_image_in_the_art_selects_the_instance`). Before, Pathfinder dropped those effects and clicks took only the instance's bounds. + Effect › Pathfinder takes a symbol instance as the art it draws with the geometry effects of its fill and stroke, as they take a path with such effects: the result painted by the instance's art carries those effects, also when the instance has geometry effects of its own and when the instance sits inside another symbol's art. A click where those effects paint the art outside the instance's bounds selects the instance, a fill only when Selection by Path Only is off, and outline mode still takes the instance's bounds alone. A marquee across those shapes selects the instance too, and a marquee across the shape an image's own fill or stroke paints outside its frame selects the image, except in outline mode. A compound shape's area leaves out its members' fill and stroke effects for symbol instances as for paths, since the compound shape paints the area with its own appearance. These are VectorCraft's own rules (engine `expand::pathfinder_takes_a_symbol_instance_fill_and_stroke_effects`, `a_click_where_a_symbol_instance_fill_or_stroke_effect_paints_selects_it`, `a_stroke_effect_reshapes_a_stroke_a_dynamic_instance_adds`, `a_fill_effect_reshapes_the_fill_of_a_group_in_the_art`, `a_click_on_the_grown_fill_of_an_image_in_the_art_selects_the_instance`, `a_marquee_where_a_symbol_instance_fill_or_stroke_effect_paints_selects_it`, `a_marquee_on_the_shape_of_an_image_fill_selects_it`). Before, Pathfinder dropped those effects, and clicks and marquees took only the instance's bounds. Live effects inside a symbol's art (geometry effects, color adjustments and the rest that export bakes) are written where each instance places the art in PDF, print, EPS and DXF, as the canvas draws them: the art is placed first and its effects are applied after, so an instance that scales its art does not scale the distance a Transform effect moves it. Symbols nested in the art, a dynamic symbol instance's own paint changes and the stain an instance's fill gives its art are kept, and the art is stained before its effects apply. A linked instance's PDF link covers its art where the effects draw it. A symbol whose art holds itself stops at the nesting limit, and the symbols' own art keeps its effects. An instance stays an instance in these exports when the objects its art makes once baked (the copies a Transform effect makes included) would take the export's placed symbol art past 16,000,000 objects, or when its baked art would draw deeper than the 128 levels a document may draw; these are VectorCraft's own limits. Art baked for an instance that then stays an instance still counts toward that limit, and while an instance's art bakes, the art's own objects are held in the limit for the instances nested in it. Instances the export leaves out (hidden ones, those in hidden groups, on template layers, and on hidden layers or layers that do not print when the export leaves those out) are not placed and do not count toward that limit. Before, these exports wrote the art without its effects (effects `bake::placing_symbols_bakes_their_art_where_each_instance_places_it`, `placing_symbols_reaches_the_art_of_nested_instances`, `placing_a_symbol_that_holds_itself_stops`, `placing_symbols_keeps_dynamic_instances_changes`, `placing_symbols_keeps_the_instances_stain`, `placing_symbols_counts_the_baked_art`, `placing_symbols_counts_nested_art_once`, `placing_symbols_holds_the_outer_art_while_it_bakes`, `placing_symbols_counts_the_art_it_drops`, `placing_symbols_counts_art_dropped_for_depth_against_later_baked_art`, `placing_symbols_keeps_the_baked_art_within_the_drawn_depth`, `placing_symbols_skips_instances_the_export_leaves_out`; doc `depth::tests::drawn_heights_measure_objects_outside_the_layers`; PDF, print, EPS and DXF `symbol_art_effects_are_written_where_they_draw`, `symbol_art_effects_print_where_they_draw`; PDF `a_stained_instance_keeps_its_stain_when_its_art_has_effects`, `a_linked_instance_keeps_its_link_when_its_art_has_effects`). EMF, WMF and SVG export write the same symbol art the same way: an instance of a symbol whose art, or the art of a symbol nested in it, has such effects is written as that art placed by the instance and then baked, so a square that a Transform effect moves 100 pt right draws 100 pt right of where the instance places it at any scale or rotation, and art the effect moves onto the artboard is written. EMF and SVG clip 9-slice cells and WMF does not, as each places other instances. In SVG those instances use no ``, and instances of symbols without such effects still share one; named objects in a symbol's art take no ids there, as in an instance with its own copy of the art, so two instances do not write the same id; with Hidden Layers on, hidden instances are placed too and written hidden. An SVG instance nested in another instance's art is shared through `` only when the transform it is drawn with, the outer instances' included, keeps the shared art as the canvas draws it, so a nested stroke keeps its weight in a scaled instance. Preserve Editing still embeds the document with its live effects. Before, these exports wrote the art without its effects (metafile `tests::import::symbol_art_effects_are_written_where_they_draw`; SVG `symbols_layers::symbol_art_effects_are_written_where_the_canvas_draws_them`, `a_kept_hidden_instance_is_written_with_its_symbols_effects`, `instances_written_as_their_art_give_its_names_no_id`, `a_nested_instance_is_shared_only_under_the_transform_it_is_drawn_with`; effects `bake::placing_symbols_skips_instances_the_export_leaves_out`). EMF and WMF export with Use Artboards applies the document's live effects once for all the chosen artboards instead of once for each, and writes the same files byte for byte (metafile `tests::export_regions_writes_what_each_region_writes_alone`; `export_regions_perf` times it). @@ -1924,6 +1952,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur A graphic style dragged onto the Graphic Styles panel's New Graphic Style button is duplicated, as the panel menu's Duplicate Graphic Style does, and both put the copy at the end of the list, as the help page describes ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=391)). VectorCraft's own rules: the button takes the drop with no art selected; a dragged style that is highlighted brings the other highlighted styles, copied in panel order in one undo step, and the copies are highlighted; the copy is named ` copy`, with a number when that is taken, and no art is linked to it (`a_style_dropped_on_new_graphic_style_is_duplicated_at_the_end` in `crates/ui-egui/src/panels/graphic_styles.rs`, `tests::styles::duplicate_puts_the_copy_at_the_end_of_the_list_in_one_undo_step`). A graphic style dragged onto the Graphic Styles panel's Delete Graphic Style button is deleted, which the help page gives as another way to delete a style besides the panel menu's Delete Graphic Style; art that used the style keeps its look and is no longer linked to it ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=392)). VectorCraft's own rules: the drop asks first as the button does, and with Alt held it deletes without asking; the button takes the drop with no style highlighted; a dragged style that is highlighted brings the other highlighted styles, deleted in one undo step (`a_style_dropped_on_delete_graphic_style_is_deleted_as_the_button_deletes` in `crates/ui-egui/src/panels/graphic_styles.rs`). 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`). 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). @@ -1963,7 +1992,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Fonts:** a font is found by any of its names (family and style in every language of its name table, legacy family/style pairs, PostScript name), so documents from other apps open with the font they name; Find Font and `text.fonts` say for each font whether it was found exactly, by another name, substituted or missing, and how many glyphs are missing. PDF and `.ai` import brings Japanese text back as live type: CID fonts without a ToUnicode map read through the standard CMaps, vertical columns (WMode 1) as vertical type, letter spacing as tracking; a glyph is live type only when the installed font (in the closest style of its family) draws the same glyph, and text in a font that isn't installed comes in as live type shown in the fallback font until the font is installed (exports that draw it — PDF, EPS, EMF/WMF, raster, SVG outlines or embedded fonts — warn that they wrote the fallback font, and Print and Print Preview warn about the type that prints in it; `textAs: outlines` keeps the PDF's embedded glyphs). Two installed versions of one family and style (a font library keeping an old file beside a new one) both load, the first staying the one the family and style resolve to; PDF and `.ai` import tries each version when the glyphs differ, and type set in a version other than that one names it (`CharStyle::font_version`), which layout, the substituted-glyph highlight, Find Font, Package and Document Info follow. Fonts outside the font folders are listed too: those font services such as Adobe Fonts load on Windows, through DirectWrite and, for those only GDI lists, through GDI (#1258), and those apps and font managers register with CoreText on macOS (#579). When a document opens with fonts that aren't available, fonts used only in symbols included, a Missing Fonts dialog lists them after the linked-file questions, with Find Fonts (Type › Find Font on them) and Close. Its Find in Folder… (in Find Font too) searches a folder on several threads, reads only what the font scan reads of font files and skips app packages, the Program Files and ProgramData folders, the system's folders and the app data folders in a home folder; Add Fonts copies the font files the user chooses, suitcase fonts with their resource fork, into VectorCraft's own Fonts folder, which the desktop app and `vectorcraft-cli` read (`text.missingFonts`, `text.findFontFiles`, `text.addFontFiles`). The font scan on Linux also reads the folders fontconfig's configuration lists, such as TeX fonts under `/usr/share/texmf/fonts` (#1548, fixes #1529; not verified on Linux). A variable font's type gets one slider and field per variation axis under the Character panel's Variable Font button, each named as the font names the axis (Weight, Width), so the type can be set between or past its named instances: the settings stay with the characters (`CharStyle::font_axes`, `text.setFormat {fontAxes}` and `text.setRangeStyle {fontAxes}`, clamped to each axis's range; `text.fontList {family, style}` lists the axes), and layout, outlines, the substituted-glyph highlight and PDF and SVG export (`font-variation-settings`, embedded fonts) use the font instanced at them. Another font or style clears them; legacy `.ai` export writes the style and warns that they are left out. The font menu's Font Technology › Variable (under the kind filter, as [Find, apply, and adjust variable fonts](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/find-apply-and-adjust-variable-fonts.html) places Variable in the classification filter's Font Technology section) lists only the families with variation axes, a family with a variable file beside static ones included, and works together with the script, kind, ★ and search filters; it stays set from one opening to the next. Measured by `font_menu::tests::the_variable_filter_lists_only_variable_families`, `font_menu::tests::the_variable_filter_is_named_as_fonts_are`, `tests_axes::a_family_with_variation_axes_is_variable` and `tests_sysfonts::a_family_with_a_variable_file_beside_static_ones_is_variable`. - The font menu's Document filter (beside ★) lists only the families that type in the current document is set in, as the quick filter for fonts used in the document does on the [font browser overview](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/font-options-overview.html). It works together with the search, script, kind, Variable and ★ filters, Recent Fonts and Show Similar Fonts, steers the closed field's wheel, follows edits and undo while the menu is open, and is shared by every font menu for the session like the other filters. VectorCraft's own rules: hidden, locked, masked, symbol, pattern and graph design type counts, styles no type uses do not, a composite font lists under its own name, a family the document names but this computer lacks is not listed (Find Font reports it), a document without available fonts lists nothing with its own message, and with no document open the filter is unavailable. Measured by `font_menu::tests::the_document_filter_lists_the_families_the_documents_type_uses`, `font_menu::tests::the_document_filter_combines_with_the_others_and_follows_edits`, `font_menu::tests::the_document_filter_counts_type_in_graph_designs` and `font_menu::tests::the_document_filter_on_an_empty_document_or_none`. + The font menu's Document filter (beside ★) lists only the families that type in the current document is set in, as the quick filter for fonts used in the document does on the [font browser overview](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/font-options-overview.html). It works together with the search, script, kind, Variable and ★ filters, Recent Fonts and Show Similar Fonts, steers the closed field's wheel, follows edits and undo while the menu is open, and is shared by every font menu for the session like the other filters. VectorCraft's own rules: hidden, locked, masked, symbol, pattern and graph design type counts, as does type in the art of a stored scatter brush (art and pattern brushes leave type out when they bend their art, so their type does not count), styles no type uses do not, a composite font lists under its own name, a family the document names but this computer lacks is not listed (Find Font reports it), a document without available fonts lists nothing with its own message, and with no document open the filter is unavailable. Measured by `font_menu::tests::the_document_filter_lists_the_families_the_documents_type_uses`, `font_menu::tests::the_document_filter_combines_with_the_others_and_follows_edits`, `font_menu::tests::the_document_filter_counts_type_in_graph_designs`, `font_menu::tests::the_document_filter_counts_type_in_scatter_brushes`, `font_menu::tests::the_document_filter_follows_a_scatter_brushs_edits_and_undo` and `font_menu::tests::the_document_filter_on_an_empty_document_or_none`. The font menu's Recently Added filter (on its own row under Font Technology) lists only the installed families added in the last 30 days, the newest at the top, as the [user guide](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=486) and the [font browser overview](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/font-options-overview.html) describe it (`vectorcraft_text::FontDb::recently_added`). It works together with the search, script, kind, Variable, ★ and Document filters, lists only the families every active filter matches, steers the closed field's wheel, and is shared by every font menu for the session like the other filters. VectorCraft's own rules: a family is dated by the creation time of its newest font file on this computer (a file the file system keeps no creation time for, or one dated in the future, does not count), the 30th day is included, families added at the same instant are in name order, the recently used families appear in that order without the Recent Fonts section, Show Similar Fonts orders only the families the filter lists, a family leaves the list when its 30 days end while the menu is open, an empty list keeps the filter on and says no fonts match, and fonts bundled with the app or loaded from documents are never listed. Measured by `font_menu::tests::the_recently_added_filter_lists_new_families_newest_first`, `font_menu::tests::the_recently_added_filter_drops_families_as_their_30_days_end`, `font_menu::tests::the_recently_added_filter_lists_a_font_installed_just_now`, `tests::recently_added::families_added_in_the_last_30_days_are_listed_newest_first`, `tests::recently_added::a_family_is_dated_by_its_newest_valid_file` and `tests::sysfonts::installed_fonts_are_recently_added_by_their_files_creation_time`. While the samples are shown, the font menu's row under the filters sets the sample size to Small, Medium or Large from inside the menu, as the [font browser overview](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/font-options-overview.html) and the [user guide](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=485) describe the sample size control; with Enable in-menu font previews off, the row is not shown, as the user guide describes. VectorCraft's own rules: the row sits under the filters and sets Preferences › Type › Font Preview Size (`fontPreviewSize`), so every font menu takes the new row height, the Composite Fonts and Dimension dialogs' included, and the open list stays on the rows it showed; the current size is selected and a click on it changes nothing; screen readers find the three sizes as radio buttons in a group named Font Preview Size; a saved value that is none of the three sizes shows Medium and a click replaces it; the change adds no undo step and leaves a font previewed on the selected type in place. Measured by `font_menu::tests::the_preview_size_row_asks_for_the_size_clicked`, `font_menu::tests::a_preview_size_asked_for_sets_the_preference_and_keeps_the_preview`, `font_menu::tests::the_preview_size_row_is_a_radio_group_showing_the_size` and `font_menu::tests::a_new_preview_size_keeps_the_list_on_its_rows`. The font database looks up a name that is neither a loaded nor an installed family among the other names of the loaded and installed fonts once for each style it is asked in, and keeps the answer until fonts are added or rescanned. Laying out a story of 1,000 paragraphs set in a font that is not installed, with 400 more fonts loaded, takes a median of 56 to 71 ms instead of 409 to 507 ms on Windows 11 (`CRAFT_FONTS_DIR= cargo test --release -p vectorcraft-text --lib missing_font_story_layout_timing -- --ignored --nocapture`). @@ -2233,6 +2262,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Import and export, later 2026-10-13 merges: SVGs that move objects with a CSS transform (`translate(100px, 0)`, `rotate(45deg)`) or style type with the `font` shorthand import as drawn (#1565); SVG symbols whose shapes use percentage lengths import at the size and place they are drawn, the percentages being of the symbol's `viewBox` (#1596); Inkscape's flowed text (`flowRoot`) opens as area type in its rectangle, a paragraph per `flowPara`, instead of being dropped, and a region that can't be read is left out with a warning (#1569, fixes #1568); the warning for an unsupported SVG filter names the filter, its primitives and the object, and says the object is drawn without it (#1599, fixes #1598); the pages of an Inkscape multi-page SVG become artboards, named by their labels (#1603, fixes #1601); SVG export with CSS classes or style entities stays fast in documents with many distinct styles (#1567); PDF and `.ai` import: evenly letter-spaced or tightened type on a path keeps its length along the path instead of closing up to the font's advances (#1586), and type on a path whose stroke is written glyph by glyph comes in as one text object with its stroke, not one object per glyph (#1585); the ICC profiles embedded in JPEG, TIFF and PSD exports have every tag on a 4-byte boundary (ICC.1 §7.1.2), so strict readers accept them (#1589, fixes #1584); GIF, PNG-8 and other indexed exports find each pixel's palette colour through an index instead of a scan, with identical output (#1576); a zero-length subpath draws its round cap as a dot and its projecting cap as a square, so dots in imported `.ai` and SVG files show (#1619, fixes #1613). - Files and untrusted input, 2026-10-14 merges: EPS import: a stitched shading keeps its hard colour changes (#1654, #1653). WMF/EMF import refuses an oversized embedded PNG or JPEG from its header, before any pixels are decoded (#1776). PDF open no longer takes exponential time on a crafted name tree with shared nodes when it looks for the editing data (#1781). The size limits on a native file's embedded data also apply to files read from memory, not only streamed ones (#1783). Saving over a private file on Unix no longer leaves a readable temporary copy beside it while the file is written (#1778). An Export for Screens suffix can no longer place files outside the export folder (#1777). Package refuses a folder where it would overwrite the open document or one of its linked files (#1786). ruzstd 0.9.1 fixes a decompression bomb (RUSTSEC-2026-0344) reachable from EPS/`.ai` and Affinity import (#1807). File Info dates are stamped only after a save succeeds, so a failed save no longer changes them (#1774). Linked files that change during a drag are updated after the drag instead of being missed (#1773). - EPS import: `readhexstring` and `readline` read the data left in a file in one pass instead of one byte per call, with the same bytes, result and next unread byte as before (about nine times less reader time on 6 MB of hex image data and on 8 MB of lines). + - EPS import: `token` on a string, `search` and `anchorsearch` read their strings in place instead of copying the rest of the string on each call, with the same results, errors and operation count as before. Walking a 512 KiB string by what each call leaves takes 16 ms instead of 518 ms with `token` and 1.0 ms instead of 27 ms with `search`, and a 64 KiB string 2.2 ms instead of 10 ms with `token`; on a 4 KiB string the difference is under 0.1 ms (release build on Linux under load from other builds, median of 7 alternating runs, `cargo test --release -p vectorcraft-eps --lib tests_strings::string_walks_timed -- --ignored --nocapture`). - **Fields, search and window, 2026-10-14 merges:** Fields commit what was typed when you click away or move to another field, as Enter does; Escape still discards it (#1787). Up and Down move through the command search results and Enter runs the highlighted one (#1798, #1757). Slider rails show on Medium Dark (#1808, #1662). On Windows the custom title bar's window stays truly borderless, so the pointer lines up with what is drawn on systems where the hidden caption offset it (#1791, #1758; awaiting the reporter's confirmation). - **Tools, panels and type, later 2026-10-14 merges:** the Transform panel's, Properties panel's and Control bar's X, Y, W and H show and edit the bounds of the anchor points selected with Direct Selection, and a whole-object selection is unchanged (#1839, fixes #1824). With Snap to Grid on, anchors and objects snap to the grid even when Snap to Pixel is also ticked: the grid wins (#1840; #1816 stays open until the reporter confirms). A marquee with the Selection or Direct Selection tool also selects the unlocked ruler guides it crosses (#1836). The toolbar shows no group labels by default (a preference brings them back) and runs on in one or two columns; the All Tools drawer lists the tools by flyout group with their shortcuts, has a menu (Reset, Basic, Advanced) and a Show section for the Fill/Stroke, Coloring, Draw Mode and Screen Mode controls (`toolbar.show`, #1751). An action clicked in the Actions panel stays selected, so Play Current Selection and Delete Selection act on it (#1853, part of #1629; editing actions and action shortcuts remain). Redo pressed during a drag keeps the drag as a step instead of losing the redone edit (#1856, #1719). Preferences are written as soon as OK is pressed, so they survive a session that doesn't end with a normal quit (#1857; #1747 stays open until the reporter confirms). New and Redefine Character Style take the format of the selected text range, also while typing (#1634). Type inside symbols, pattern tiles, graph designs and opacity masks gets its layout bounds back when a native file opens, so warped type in a symbol looks the same after save and reopen (#1833, #1738). Editing, renaming, deleting or merging a global swatch reaches the art of opacity masks, and a swatch used only in a mask is no longer listed as unused (#1830, #1735). On macOS, Save As, Save a Copy and the first Save show their sheet again; the Format menu on the sheet (#866) is withdrawn until the format can be set before the sheet opens, and #866 is open again (#1855; #1800, #1831 and #1518 stay open until confirmed on a Mac). - **Files and untrusted input, later 2026-10-14 merges:** SVG import applies style sheet rules with `:not()` selectors, with their nesting bounded (#1799, #1557), no longer stalls on a style sheet with many stacked descendant selectors over deep nesting (#1834, #1703), and reads an SVG's linked files within the automation roots in force again (#1870). DXF export writes the VPORT record's view direction once (group code 36 was written twice, which strict readers reject, #1789). A deeply nested file no longer overflows the stack: nesting is capped at 32 objects (deeper groups are merged with a warning; SVG past 256 elements and PDF past 256 nested arrays are refused), symbols and patterns that use themselves open without the offending instance or paint, and a document nested more than about 40 deep can no longer be saved to a file that won't open again (#1852). PDF and `.ai` files nested deeply inside compressed streams, page trees holding themselves and functions or colour spaces built on themselves no longer crash the app (hayro 0.8; the import runs on a 16 MB thread, #1871); a decompression bomb or impossible predictor parameters are refused (#1873, #1700, #1701); a brush whose art draws the brush again through a symbol or pattern no longer crashes the app, and graph designs, Affinity, DXF, metafiles and plug-ins were probed with hostile input (#1872). Hostile EPS, Affinity and native files can no longer run memory or CPU away through ASCII85 data, PostScript objects holding themselves, flat-colour pixel layers or far and overlapping data offsets (#1863: #1715, #1714, #1704, #1699), and the save fallback for folders that refuse a rename keeps the old file's content until the new one is in (#1695). A file whose ids sit at their largest value no longer breaks new objects (#1718); a failed `command.batch` puts each document back whole, its file, history and a drag in progress included (#1697); a control request that timed out before the app took it never runs later, and the reply says which case it was (#1725, [control-protocol.md](control-protocol.md)); the Eyedropper and recolouring refuse an image too large as RGBA before decoding it (#1717) (all #1862). A save or export that fails is reported in a dialog that names the file and stays until closed, with the document left modified and the old file untouched (#1685); a browser download that can't start fails the save instead of marking it saved (#1693); a file that finishes opening waits while a dialog is open, so Save As options can't save the wrong document (#1694) (all #1865). krilla is built without its text shaping, so the unmaintained rustybuzz and ttf-parser don't ship (#1874, #1730); the CI gate compiles the web app for wasm, and the web's SVG nesting cap (34) follows from its 1 MiB stack (#1875). @@ -2401,6 +2431,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Changed plug-in gradients lose spot plates (G17):** a gradient that a filter or importer changes loses each stop's swatch link, tint and process `plates` together, in fills and strokes, and keeps the stop's color, offset, opacity and midpoint; a gradient returned unchanged keeps all three. Regressions: `crates/plugins/src/objects/tests.rs` (`changed_gradient_fill_and_stroke_drop_spot_plates`, `unchanged_gradient_paint_keeps_spot_plates`). Scores and hours unchanged. - **Plug-in data kept with the document (G17):** a filter writes JSON of at most 1 MiB with `documentData` (one undo step with its objects; `null` removes it) and reads it back in `_context.documentData`, which no other filter is given. It is the document's foreign data (`unknown.pluginData`, by plug-in id), as the perspective grid is, so the native file keeps it with no section of its own; an exporter is given the whole document, so it can read every plug-in's. Regressions: `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_export.rs` (the exporter), `crates/doc/src/plugin_data.rs`, `crates/plugins/src/objects/tests.rs`. Scores and hours unchanged. - **Heavy filter plug-ins (G17):** a filter's manifest may ask for `"budget": "heavy"`: 1 G instructions (20 times a light run's) and 300 s a run, for routing, packing or simulation. Install Plug-in… and File › Open ask the user first, `plugin.install` needs `allowHeavy: true` (`plugin.inspect` tells beforehand), the Additional Plug-ins Folder skips such filters, and the plug-in store keeps the answer. Its dialog has no Preview; the app runs it on a thread of its own with a progress window (Cancel, Continue in Background) and applies the result as `plugin.run` with the same parameters, one undo step, unless the document or the plug-in changed meanwhile. Regressions: `crates/plugins/tests/abi.rs`, `crates/plugins/src/manifest.rs`, `crates/engine/src/tests/plugins.rs`, `crates/ui-egui/src/tests/plugin_runs.rs`. Scores and hours unchanged. +- **Plug-in instruction budget preference (G17, VectorCraft's own setting):** Preferences › Plug-ins & Scratch Disks › Plug-in Instruction Budget (`pluginInstructionBudget`) is Normal by default, which keeps the 50 M instructions a light filter run gets, or Large, which gives each object filter run 250 M plus the 4,000 per input byte, with the 60 s time budget, Cancel and the other limits unchanged. A heavy filter keeps its 1 G and 300 s with either choice; live effects, exporters and importers keep their own budgets. A change applies to the next run of an installed filter; `prefs.set` refuses any other value, and a saved file with another value reads as Normal. Regressions: `crates/plugins/tests/abi.rs`, `crates/engine/src/tests/plugins.rs`, `crates/engine/src/tests/prefs.rs`, `crates/ui-egui/src/prefs_dialog/tests.rs`. Scores and hours unchanged. - **Safe Mode for plug-ins (G17):** `vectorcraft --safe-mode` and `vectorcraft-cli --safe-mode ` start without plug-ins. When a launch stopped while a plug-in was loading or drawing its first live effect, the next launch names that plug-in, without saying it caused the stop, and offers Disable and Continue, Start Normally or Start in Safe Mode. Help › Safe Mode lists the disabled plug-ins with Enable on Re-launch, which takes effect at the next launch, and the app bar and the window title show Safe Mode. The help page (https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf, pages 65 to 69) describes the same choice between diagnosing and starting normally, a Safe Mode with the problem item off and the rest of the app working, and turning the item back on at the next launch. In Safe Mode no plug-in loads or runs, and a live-effect plug-in draws its object's geometry unchanged while the object keeps the effect, which the Appearance panel marks "(Safe Mode)" with the plug-in's id in its tooltip and `effect.list` marks `skipped`; Expand Appearance refuses such an object. The web build keeps no plug-ins between page loads and has no marker. Each desktop launch with preferences keeps a marker in the `Launch` folder next to them; `vectorcraft-cli` and a desktop launch without preferences keep none, so a stop there leads to no choice at the next launch. Disabled plug-ins are listed in `Plug-ins/disabled.json`. `plugin.safeMode` reports Safe Mode and the disabled plug-ins, and `plugin.setEnabled` changes the list. Regressions: `crates/plugins/src/safe_mode.rs`, `crates/plugins/tests/safe_mode.rs`, `crates/engine/tests/plugin_safe_mode.rs`, `crates/ui-egui/tests/safe_mode.rs`. Scores and hours unchanged. - **Hang report and Copy Troubleshooting Info:** when the desktop app's interface thread stays in one part of a frame for 3 s (VectorCraft's own value), a watching thread writes a hang report to the log and to `logs/hang-report-.txt`, and removes the file when the interface answers again. A later launch that finds a report no process holds writes it to the log, keeps it as `logs/hang-report.1.txt` and, unless another start-up message is showing, says so in the status bar. Help › Copy Troubleshooting Info (`help.copyTroubleshootingInfo`) copies the platform facts, the recent commands and frame times, and the reports of this session and the last one. Regressions: `apps/vectorcraft/src/hang_watch/tests.rs`, `crates/ui-egui/src/hang_beacon.rs`, `crates/ui-egui/src/troubleshooting.rs`. Scores and hours unchanged. - **A disabled plug-in whose update stays in the store is turned on:** when `plugin.install` writes a module that lists permissions to the `Plug-ins` folder, its grant can't be written, and the folder can't be returned to the old module (or, on a first install, the new module can't be removed), the folder holds the new module, so a disabled plug-in is turned on, by id and by stored file, as for any install the folder holds. The old grant, or none, doesn't cover the new module, so the next start skips it until it is approved. Regressions: `crates/engine/src/tests/plugins.rs`. Scores and hours unchanged. @@ -2753,6 +2784,10 @@ A VectorCraft addition, not a feature of the reference app, so no area score mov A trim reads the selection through a set and changes it once at the end, instead of going through the selected objects once for each trimmed path and each piece, with the same resulting selection as before. With 2,000 selected lines each split in two, the selection update took 7.7 ms and now takes 0.2 ms (the whole command about 75 ms); with 7,000 lines it took 96 ms and now takes 0.7 ms. The times are wall-clock medians of 7 runs while other builds shared the CPU. Test: `the_selection_after_a_trim_is_the_one_changing_it_one_id_at_a_time_gives` in `cmd::addons::pathtools::trim::tests` in `vectorcraft-engine`. +## Path Precision Tools add-on: Smooth Bridge (2026-11-15) + +A VectorCraft addition, so no area score moves. Object › Plug-ins › Path Precision Tools › Smooth Bridge… (`addon.pathtools.bridge`) joins two selected circles into one closed outline, like two drops of liquid pulling apart: the outline goes around each circle on its side away from the other and along two concave arcs, one on each side, each touching both circles from outside, so the outline runs on smoothly from each circle into the bridge and every anchor is smooth. The arcs' radius is a percentage of the smaller circle's radius (1 to 1000%, 100% by default); a larger radius makes a wider, gentler bridge, and circles farther apart make a narrower one. Overlapping and touching circles are joined at every radius; one circle inside the other, or circles too far apart for the radius (the arcs would not reach both circles, or would cross), is refused with a message, which suggests a larger radius only when one up to 1000% would bridge them. The outline replaces the two circles, painted as the upper one, or with Keep Originals goes directly above the upper circle and the circles stay. One undo step; the dialog previews on the canvas. Tests: `bridge::tests` in `vectorcraft-pathops` (equal and unequal circles, overlapping and touching ones, unequal ones at large radii, the neck's width, the arcs tangent to both circles at every anchor, far apart and nested circles refused, circles told from other paths), `bridge::tests` in `cmd::addons::pathtools` in `vectorcraft-engine` (the outline in place of the circles or above them, one undo step, the radius, unequal overlapping circles up to the largest radius, refused selections and parameters with and without a larger radius suggested, locked and hidden circles), `smooth_bridge_opens_its_dialog_previews_and_runs_on_ok` in `vectorcraft-ui-egui` and `command_sweep`. Commands: `docs/mcp.md` › Path Precision Tools add-on. + ## Document Tools add-on: Save a Timestamped Copy (2026-11-01) A VectorCraft addition, not a feature of the reference app, so no area score moves. Object › Plug-ins › Document Tools › Save a Timestamped Copy writes a copy of the document named `_YYYY-MM-DD_HH-MM.` (the date and time in UTC, through chrono; `-2`, `-3`… added when that name is taken) next to the document, or into a folder picked (the folder picker) when it was never saved, in the document's own format or another save format. It writes through File › Save a Copy's save, so the document keeps its path, title and modified state, no undo step is made, and the write stays inside the automation roots in force. It is off on the web, which has no clock. Tests: `cmd::addons::document::tests` in `vectorcraft-engine` (the name and place, numbered names, the document unchanged and its content in the copy, an unsaved document needing a folder, other formats, bad params refused, automation roots), `addons::document::tests` in `vectorcraft-ui-egui` (the submenu, beside the document, the folder picked or cancelled) and `command_sweep`. Commands: `docs/mcp.md` › Document Tools add-on. diff --git a/docs/three-d.md b/docs/three-d.md index d01b6ab6de..17acee78e3 100644 --- a/docs/three-d.md +++ b/docs/three-d.md @@ -469,8 +469,9 @@ The public [Map artworks on 3D object](https://helpx.adobe.com/illustrator/deskt page describes graphics: art kept with the document and placed on single surfaces of a 3D object, and the [3D and Materials panel options](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/3d-materials-panel-options.html) page lists Graphics and Add Materials and Graphics on the Materials tab. VectorCraft maps graphics onto -Extrude & Bevel's front and back caps, the plane of the Plane type (Rotate), the swept side of Revolve, which the -public page's example of a label on a bottle describes, and Inflate's puffed front and back. +Extrude & Bevel's front and back caps and its side (its walls and bevels), the plane of the Plane type (Rotate), +the swept side of Revolve, which the public page's example of a label on a bottle describes, and Inflate's puffed +front and back. - The panel's **Materials** tab shows the document's graphics as thumbnails. A graphic is a document symbol, as the public page allows existing symbols to be used. **Add as Single Graphic** keeps the selected art as a new @@ -479,9 +480,9 @@ public page's example of a label on a bottle describes, and Inflate's puffed fro - Clicking a thumbnail maps that graphic onto the front of the 3D effect of each selected object (`threeD.mapGraphic`), in one undo step. A graphic larger than the object starts scaled down to fit inside it. - Below the thumbnails the tab lists the graphics mapped onto the first selected object. The selected one shows - its Face (Front or Back, on Inflate its puffed front or back; Plane and Revolve show no Face, as a plane has only a front and Revolve's graphics go - on its side), X and Y (the offset of its center from the center of the - object's bounds, in the face's plane), Scale (a percentage of the symbol's size) and Rotation + its Face (Front, Back or Side, on Inflate Front or Back for its puffed front or back; Plane and Revolve show no + Face, as a plane has only a front and Revolve's graphics go on its side), X and Y (the offset of its center from + the center of the object's bounds, in the face's plane, or on a side from its middle unrolled flat), Scale (a percentage of the symbol's size) and Rotation (counterclockwise), and **Remove Graphic** takes it off. Each change is one undo step. - While the tab is open, a blue handle sits on the center of each mapped graphic whose face is turned toward the viewer. Dragging a handle moves that graphic over its face, previewed while the pointer is down and recorded as @@ -534,6 +535,20 @@ These rules are VectorCraft's own: or point, takes none. A graphic larger than the half of the side seen from the front starts scaled to fit it. The panel shows no handle for a Revolve's graphics; X and Y move them. Expand Appearance keeps every face of a surface with graphics. +- On Extrude & Bevel a graphic on the Side lies on the walls and bevels, unrolled flat. X runs along the art's own + outline (the front cap's edge, or with a bevel carved into the shape the walls' outline), through its corners and + around its curves: 0 is where the outline's top crosses the vertical line + through the middle of its bounds, and X grows clockwise around the outline as the front is seen, so the graphic + reads the right way round from outside. Y runs from the front cap's edge toward the back cap's, measured from the + middle: across each bevel step along its slant, and across the walls along the depth. Both are lengths before + the twist and the taper, which carry the graphic with the side. The side is cut at the anchor of the outline + nearest half way around from X = 0. On a compound shape the graphics go on its longest contour, and on an object + with several solids (a fill and its stroke's outline, or the members of a group or layer) they go once, on the + side of the solid with the longest outline. Each piece of the side that shows its outside to the viewer draws the + part of the graphic that falls on it, shaded as the piece is, with the same cutting and seams as on Revolve; a + piece of a stroke's face cut where it passes through a wall draws the part within its own outline. A graphic larger than the + part of the side unrolled about X = 0 that does not reach its cut starts scaled to fit it. The blue handle sits on the graphic's center while that point is on a + piece the viewer sees, and dragging it moves the graphic over the visible part of the side. - The symbol's fills and strokes are drawn as filled areas, a stroke as its outline, and their gradients and patterns are placed with the graphic. Images, hidden objects, guides and clipping paths in the symbol are left out, and clipping groups draw their art unclipped. Instances @@ -542,15 +557,17 @@ These rules are VectorCraft's own: - Without perspective, the graphic maps exactly. With perspective, straight lines stay straight and each curve is cut into 8 cubic pieces before it is mapped. The part of a graphic at or behind the eye is left out. - An object takes up to 64 graphics. One graphic draws up to 4,096 fills and strokes, and the graphics of one 3D - effect draw up to 400,000 path elements together (on Revolve, 400,000 points after the curves are cut, and up to + effect draw up to 400,000 path elements together (on Revolve's side and Extrude & Bevel's, 400,000 points after the curves are cut, and up to 2,000,000 once they are cut at the faces, with up to 64,000,000 points cut together, and the copies of their paints in the parts take up to 256 MiB per object, apart from those of the surfaces). Commands refuse a graphic past either limit. A loaded file draws the object without a graphic past the first limit, and without all of its graphics past the second. -- A hollow Extrude & Bevel has no caps, so its graphics are not drawn until Cap is turned on again, and - `threeD.mapGraphic` refuses to map a new one onto it. Changing between Extrude, Plane, Revolve and Inflate keeps - the graphics, except that Plane and Revolve drop the graphics on the back cap; on Revolve the front's graphics go - on its side, and on Inflate they go on the puffed faces. +- A hollow Extrude & Bevel has no caps, so the graphics on its caps are not drawn until Cap is turned on again, + and `threeD.mapGraphic` refuses to map a new one onto a cap; its side takes graphics. With a depth of 0 the object + is a plane, and `threeD.mapGraphic` maps graphics onto its front only. Changing between Extrude, Plane, Revolve + and Inflate keeps the graphics, except that Plane and Revolve drop the graphics on the back cap, and Plane, Revolve + and Inflate drop the graphics on Extrude & Bevel's side; on Revolve the front's graphics go on its side, and on + Inflate the front's and back's go on the puffed faces. - `effect.apply` and `effect.setParams` refuse a graphic that names a symbol the document does not have, unless the effect already holds a graphic of that symbol. A graphic whose symbol is deleted is no longer drawn. Renaming a symbol renames it in the graphics that use it, in the layers, in the art of symbols, patterns, graph designs, brushes and opacity masks, and in graphic @@ -565,8 +582,8 @@ uses: `rotationX`, `rotationY`, `rotationZ`, `perspectiveAngle` (degrees), `shad `lightHeight` (degrees), `lightSoftness` (%), `ambient` (%, to 200), `lightBehind`. Lengths are points and scale with the object (Scale Strokes & Effects). Commands validate the shape and the parameters before the document changes. All four also take `lights`: null (the default, use the earlier single-light fields), or an array of one to ten objects. Each object takes `color` (opaque `#rrggbb`, white), `intensity` (0..100%, 80), `rotation` (-180..180 degrees, 125.26), `height` (0..90 degrees, 30), `softness` (0..100%, 0), and `behind` (boolean, false). Omitted settings use those defaults. An explicit list replaces the earlier single light; `ambient` and `shade` remain shared. Set `lights` to null to return to the single-light fields. Invalid lists, counts, keys and values are rejected before editing; malformed loaded lists fall back to the earlier light safely. All four take `shadow` (boolean, false), `shadowPosition` (`behind` or `below`), `shadowDistance` (0..100%, 0) and `shadowBounds` (10..400%, 100) ([Shadows](#shadows)); values out of range are rejected before editing. `threeD.extrude`, `threeD.rotate`, `threeD.revolve` and `threeD.inflate` take `graphics` ([Graphics](#graphics)): an array of up to 64 objects, each -with `symbol` (the name of a document symbol), `face` (`front` or `back`, default `front`; `threeD.rotate` and -`threeD.revolve` take `front` only), `x` and `y` (points, default 0), `scale` (1..10000%, default 100) and `rotation` (-360..360 degrees, +with `symbol` (the name of a document symbol), `face` (`front`, `back` or `side`, default `front`; `threeD.rotate` and +`threeD.revolve` take `front` only, and `threeD.inflate` `front` or `back`), `x` and `y` (points, default 0), `scale` (1..10000%, default 100) and `rotation` (-360..360 degrees, default 0). Other keys, values out of range and graphics on the other 3D effects are rejected before editing. All four take `render` ([3D and Materials panel](#3d-and-materials-panel)): an object whose `mode` is `shaded` (the default) or `wireframe`. A `render` that is not an object, a key other than `mode`, another mode, and `render` on @@ -579,11 +596,11 @@ and [Create 3D objects](https://helpx.adobe.com/illustrator/desktop/special-effe pages, and the archived Extrude & Bevel option list (depth 0–2,000, cap on/off, bevel height, bevel extent in or out, perspective). No Adobe software, assets, presets or bevel shapes were used. -- **Materials** (base and Adobe Substance), graphics on Extrude & Bevel's walls and bevels, - shadows of lights after the first, and **ray-traced rendering** are not built: shading uses directional - lights, in the paint of the fill or stroke the solid is built for ([Fills and strokes](#fills-and-strokes)), and - only the first light casts a shadow ([Shadows](#shadows)). Graphics map onto planar faces, Revolve's side and Inflate's puffed faces only - ([Graphics](#graphics)). +- **Materials** (base and Adobe Substance), shadows of lights after the first, and **ray-traced rendering** are not + built: shading uses directional lights, in the paint of the fill or stroke the solid is built for + ([Fills and strokes](#fills-and-strokes)), and only the first light casts a shadow ([Shadows](#shadows)). + Graphics map onto planar faces, Extrude & Bevel's side as one surface unrolled flat, Revolve's side and Inflate's + puffed faces only ([Graphics](#graphics)). - The bevel shapes and their names are our own; custom bevel paths are not supported. - 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 diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 9d2b582f34..e44a28165c 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -408,6 +408,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po |---|---|---| | Effect > Warp Options: style previews, orientation choices and percent controls | done | #1760; focused input, mixed-style and history checks passed; original captures reviewed. No geometry or optional Properties changes. | | Command search: Up and Down move through the results, Enter runs the highlighted one | done | #1798 (#1757) | +| Help › VectorCraft Help… and F1 show in-app search for tools, menu commands, and built-in tutorials. Tool results mark their toolbar location; command results show their menu path and shortcut without running them; tutorial results show their steps. Home clears the search, Back returns to the results, and Escape in the search field closes the panel. | partial | [Public source](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/learn-with-discover-panel.html); `help.discover`, `help.discover.search`, `help.discover.choose`, `help.discover.back`; `menus::tests::help_f1_opens_discover_without_a_document`. Articles, Quick Actions, and Discover preferences are not implemented. Menu-path text instead of a menu location marker is VectorCraft's current guidance. | | Learn panel: Window › Learn and Explore tutorials on the app bar open it; For you holds a Quick skill guide card, Skills lists VectorCraft's own skills with progress rings that fill and counts of tutorials finished, a tutorial shows its numbered steps with a check box each that marks the step done once its sample is open, a finished tutorial has a check mark, Back goes up a level; a tool's name in a step is a link that marks the tool where the toolbars show it (its button, its group's flyout, a torn-off strip, a toolbar made with New Toolbar or the All Tools drawer) without choosing it; View more opens the tutorial's practice sample as a new untitled document, Finish tutorial then marks it finished with all its steps, and Next Up shows the next tutorial in the same skill; Reset progress clears the progress (no video) | done | [the help page](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/learn-skills-quick-skill-guide.html); `learn.list`, `learn.tab`, `learn.skills`, `learn.skill`, `learn.show`, `learn.back`, `learn.locateTool`, `learn.openSample`, `learn.markStep`, `learn.finish`, `learn.next`, `learn.resetProgress`; the mark's look and 3-second lifetime, marking steps by hand, keeping the progress in the preferences and Reset progress are VectorCraft's own rules; `panels::learn::tests`, `toolbar::tests` | | Pathfinder panel: a group selected alone counts its nested shapes, so an expanded stroked object keeps the Shape Modes enabled | done | #1642 (#1635) | | Selected Grid Repeat shows row, column and corner handles and spacing sliders; bounding-box handles take priority where they meet | done | #2691, `tools/src/repeat_grid.rs`; [public behavior reference](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-patterns/set-grid-repeat-options.html); drags preview and commit `object.repeat.options` as one undo step, Escape cancels; a selected Radial Repeat shows an instances handle below it (16 px of drag per instance, 1 to 1,000) and a radius handle on its circle the same way (`tools/src/repeat_radial.rs`; [public behavior reference](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/create-and-edit-patterns/create-radial-repeats.html)), and a splitter on its circle that hides the instances it is dragged back past while the others keep their places, and shows them again when dragged forward (its place half a step past the last instance shown and its limit of one instance shown are VectorCraft's own rules) | @@ -506,6 +507,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Set Corners… (also a button in the Anchor Inspector's Corners section: Radius in any unit, Corner kind, Anchors: All, Odd-Numbered or Even-Numbered, counted from each path's first anchor; Angle: from … to …°, only the corners whose sides meet at an angle in that range; Preview) cuts corners on the chosen anchors of every selected path, one undo step | done | #5546, #5545; `addon.pathtools.cornerSet` (`every`, `minAngle`, `maxAngle`), `crates/ui-egui/src/addons/pathtools/set_corners.rs` and their tests; not a feature of the reference app, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Trim at Crossings Tool (also in the Scissors tool's group in both shipped toolbars, after the Knife, and listed there in the All Tools drawer; a toolbar edited before keeps its saved layout until Reset Toolbar; no shortcut until one is set in Edit › Keyboard Shortcuts › Tools; the Knife's cursor, drawn as a knife with the blade's point on the hotspot) removes stretches of paths between the places where they are crossed, on any editable path, selected or not: a click removes the stretch under the pointer, a drag removes every stretch its rectangle touches, and an Alt-drag removes every stretch its freehand line crosses; one undo step each; Escape during a drag removes nothing; hovering shows in red the stretch a click would remove, and a drag that reaches few paths shows what its release would remove | done | `addon.pathtools.trim` (in `crates/engine/src/cmd/addons/pathtools/trim.rs`), `crates/tools/src/addons/trim.rs` and their tests; not a feature of the reference app, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Expand Dashes into Paths turns each selected path's dashed stroke into separate open paths, one per dash, laid out as the stroke draws them (pattern, offset, Align Dashes to Corners and Path Ends), each keeping the stroke with the dashes off; one undo step | done | #4922; `addon.pathtools.expandDashes` (in `crates/engine/src/cmd/addons/pathtools.rs`, using the renderer's dash layout) and its tests; not a feature of the reference app, so it is not scored | +| Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Smooth Bridge… (Radius as a percentage of the smaller circle's radius, Keep Originals; Preview) joins two selected circles into one outline with two concave arcs that touch both circles, in place of the circles or above them; one undo step | done | `addon.pathtools.bridge`, `crates/pathops/src/addons/pathtools/bridge.rs`, `crates/ui-egui/src/addons/pathtools/bridge.rs` and their tests; a VectorCraft addition, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools › Tangent Circle… draws the circles that touch two selected paths or compound paths at a radius, or three of them, each touching the outlines without crossing them; Radius (two shapes), a Circle menu (All or one by number) and Preview; one undo step | done | `addon.pathtools.tangentCircle` (in `crates/engine/src/cmd/addons/pathtools/tangent_circle.rs`, geometry in `crates/pathops/src/addons/pathtools/tangent_circle.rs`) and its tests; a VectorCraft addition, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Effect › Path Effects lists its live effects (Dashes to Geometry, Add Anchors, Extend Path, Close Path, Smooth Anchors, Retract Handles, Reverse Direction, Simplify Anchors, Split at Anchors), each with the effect dialog's live Preview except Reverse Direction, which has no options, and listed in the Appearance panel like any effect | done | `addon.path.*`, `crates/effects/src/addons/path.rs`, `crates/ui-egui/src/addons/pathtools.rs` and their tests; not a feature of the reference app, so it is not scored | | Path Precision Tools add-on (VectorCraft addition): Object › Plug-ins › Path Precision Tools selects its four tools (Anchor Eraser Brush, Extend Path, Measure & Inspect, Parametric Shape), which the All Tools drawer lists under their own heading but neither toolbar shows as shipped, opens the Anchor Inspector panel (the selected anchor's X/Y and handle lengths and angles as fields; Make Smooth, Make Corner, Equalize Handles, Remove Points Keep Shape, Add Points, the three ways to close) and the Parametric Shape panel (kind, count, W/H, rotation, the kind's own values and corner radius of the selected parametric shape, or of the tool's next one), and runs Add Points at / Split at Crossings and Convert to Parametric Shape; the Parametric Shape Tool draws ten re-editable kinds from the centre (↑/↓ and ←/→ change their numbers while dragging) and edits a selected one with handles; a double-click on the brush or Extend Path tool opens its options | done | `addon.pathtools.*`, `crates/tools/src/addons/`, `crates/ui-egui/src/addons/pathtools.rs`, `crates/ui-egui/src/addons/pathtools/shape.rs` and their tests; not a feature of the reference app, so it is not scored |